/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { __markAsModule(target); for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __reExport = (target, module2, desc) => { if (module2 && typeof module2 === "object" || typeof module2 === "function") { for (let key of __getOwnPropNames(module2)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); } return target; }; var __toModule = (module2) => { return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); }; // node_modules/diff-match-patch/index.js var require_diff_match_patch = __commonJS({ "node_modules/diff-match-patch/index.js"(exports, module2) { var diff_match_patch3 = function() { this.Diff_Timeout = 1; this.Diff_EditCost = 4; this.Match_Threshold = 0.5; this.Match_Distance = 1e3; this.Patch_DeleteThreshold = 0.5; this.Patch_Margin = 4; this.Match_MaxBits = 32; }; var DIFF_DELETE3 = -1; var DIFF_INSERT3 = 1; var DIFF_EQUAL3 = 0; diff_match_patch3.Diff = function(op, text2) { return [op, text2]; }; diff_match_patch3.prototype.diff_main = function(text1, text2, opt_checklines, opt_deadline) { if (typeof opt_deadline == "undefined") { if (this.Diff_Timeout <= 0) { opt_deadline = Number.MAX_VALUE; } else { opt_deadline = new Date().getTime() + this.Diff_Timeout * 1e3; } } var deadline = opt_deadline; if (text1 == null || text2 == null) { throw new Error("Null input. (diff_main)"); } if (text1 == text2) { if (text1) { return [new diff_match_patch3.Diff(DIFF_EQUAL3, text1)]; } return []; } if (typeof opt_checklines == "undefined") { opt_checklines = true; } var checklines = opt_checklines; var commonlength = this.diff_commonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); commonlength = this.diff_commonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); var diffs = this.diff_compute_(text1, text2, checklines, deadline); if (commonprefix) { diffs.unshift(new diff_match_patch3.Diff(DIFF_EQUAL3, commonprefix)); } if (commonsuffix) { diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, commonsuffix)); } this.diff_cleanupMerge(diffs); return diffs; }; diff_match_patch3.prototype.diff_compute_ = function(text1, text2, checklines, deadline) { var diffs; if (!text1) { return [new diff_match_patch3.Diff(DIFF_INSERT3, text2)]; } if (!text2) { return [new diff_match_patch3.Diff(DIFF_DELETE3, text1)]; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; var i2 = longtext.indexOf(shorttext); if (i2 != -1) { diffs = [ new diff_match_patch3.Diff(DIFF_INSERT3, longtext.substring(0, i2)), new diff_match_patch3.Diff(DIFF_EQUAL3, shorttext), new diff_match_patch3.Diff(DIFF_INSERT3, longtext.substring(i2 + shorttext.length)) ]; if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE3; } return diffs; } if (shorttext.length == 1) { return [ new diff_match_patch3.Diff(DIFF_DELETE3, text1), new diff_match_patch3.Diff(DIFF_INSERT3, text2) ]; } var hm = this.diff_halfMatch_(text1, text2); if (hm) { var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); return diffs_a.concat([new diff_match_patch3.Diff(DIFF_EQUAL3, mid_common)], diffs_b); } if (checklines && text1.length > 100 && text2.length > 100) { return this.diff_lineMode_(text1, text2, deadline); } return this.diff_bisect_(text1, text2, deadline); }; diff_match_patch3.prototype.diff_lineMode_ = function(text1, text2, deadline) { var a = this.diff_linesToChars_(text1, text2); text1 = a.chars1; text2 = a.chars2; var linearray = a.lineArray; var diffs = this.diff_main(text1, text2, false, deadline); this.diff_charsToLines_(diffs, linearray); this.diff_cleanupSemantic(diffs); diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, "")); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT3: count_insert++; text_insert += diffs[pointer][1]; break; case DIFF_DELETE3: count_delete++; text_delete += diffs[pointer][1]; break; case DIFF_EQUAL3: if (count_delete >= 1 && count_insert >= 1) { diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert); pointer = pointer - count_delete - count_insert; var subDiff = this.diff_main(text_delete, text_insert, false, deadline); for (var j = subDiff.length - 1; j >= 0; j--) { diffs.splice(pointer, 0, subDiff[j]); } pointer = pointer + subDiff.length; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } pointer++; } diffs.pop(); return diffs; }; diff_match_patch3.prototype.diff_bisect_ = function(text1, text2, deadline) { var text1_length = text1.length; var text2_length = text2.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); for (var x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; var front = delta % 2 != 0; var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < max_d; d++) { if (new Date().getTime() > deadline) { break; } for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 == -d || k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1]) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { k1end += 2; } else if (y1 > text2_length) { k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { var x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); } } } } for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x2; if (k2 == -d || k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1]) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) == text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { k2end += 2; } else if (y2 > text2_length) { k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; x2 = text1_length - x2; if (x1 >= x2) { return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); } } } } } return [ new diff_match_patch3.Diff(DIFF_DELETE3, text1), new diff_match_patch3.Diff(DIFF_INSERT3, text2) ]; }; diff_match_patch3.prototype.diff_bisectSplit_ = function(text1, text2, x, y, deadline) { var text1a = text1.substring(0, x); var text2a = text2.substring(0, y); var text1b = text1.substring(x); var text2b = text2.substring(y); var diffs = this.diff_main(text1a, text2a, false, deadline); var diffsb = this.diff_main(text1b, text2b, false, deadline); return diffs.concat(diffsb); }; diff_match_patch3.prototype.diff_linesToChars_ = function(text1, text2) { var lineArray = []; var lineHash = {}; lineArray[0] = ""; function diff_linesToCharsMunge_(text3) { var chars = ""; var lineStart = 0; var lineEnd = -1; var lineArrayLength = lineArray.length; while (lineEnd < text3.length - 1) { lineEnd = text3.indexOf("\n", lineStart); if (lineEnd == -1) { lineEnd = text3.length - 1; } var line = text3.substring(lineStart, lineEnd + 1); if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) { chars += String.fromCharCode(lineHash[line]); } else { if (lineArrayLength == maxLines) { line = text3.substring(lineStart); lineEnd = text3.length; } chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } lineStart = lineEnd + 1; } return chars; } var maxLines = 4e4; var chars1 = diff_linesToCharsMunge_(text1); maxLines = 65535; var chars2 = diff_linesToCharsMunge_(text2); return { chars1, chars2, lineArray }; }; diff_match_patch3.prototype.diff_charsToLines_ = function(diffs, lineArray) { for (var i2 = 0; i2 < diffs.length; i2++) { var chars = diffs[i2][1]; var text2 = []; for (var j = 0; j < chars.length; j++) { text2[j] = lineArray[chars.charCodeAt(j)]; } diffs[i2][1] = text2.join(""); } }; diff_match_patch3.prototype.diff_commonPrefix = function(text1, text2) { if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; diff_match_patch3.prototype.diff_commonSuffix = function(text1, text2) { if (!text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; diff_match_patch3.prototype.diff_commonOverlap_ = function(text1, text2) { var text1_length = text1.length; var text2_length = text2.length; if (text1_length == 0 || text2_length == 0) { return 0; } if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text2 = text2.substring(0, text1_length); } var text_length = Math.min(text1_length, text2_length); if (text1 == text2) { return text_length; } var best = 0; var length = 1; while (true) { var pattern = text1.substring(text_length - length); var found = text2.indexOf(pattern); if (found == -1) { return best; } length += found; if (found == 0 || text1.substring(text_length - length) == text2.substring(0, length)) { best = length; length++; } } }; diff_match_patch3.prototype.diff_halfMatch_ = function(text1, text2) { if (this.Diff_Timeout <= 0) { return null; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; } var dmp = this; function diff_halfMatchI_(longtext2, shorttext2, i2) { var seed = longtext2.substring(i2, i2 + Math.floor(longtext2.length / 4)); var j = -1; var best_common = ""; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext2.indexOf(seed, j + 1)) != -1) { var prefixLength = dmp.diff_commonPrefix(longtext2.substring(i2), shorttext2.substring(j)); var suffixLength = dmp.diff_commonSuffix(longtext2.substring(0, i2), shorttext2.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); best_longtext_a = longtext2.substring(0, i2 - suffixLength); best_longtext_b = longtext2.substring(i2 + prefixLength); best_shorttext_a = shorttext2.substring(0, j - suffixLength); best_shorttext_b = shorttext2.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext2.length) { return [ best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common ]; } else { return null; } } var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } var text1_a, text1_b, text2_a, text2_b; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; }; diff_match_patch3.prototype.diff_cleanupSemantic = function(diffs) { var changes = false; var equalities = []; var equalitiesLength = 0; var lastEquality = null; var pointer = 0; var length_insertions1 = 0; var length_deletions1 = 0; var length_insertions2 = 0; var length_deletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL3) { equalities[equalitiesLength++] = pointer; length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastEquality = diffs[pointer][1]; } else { if (diffs[pointer][0] == DIFF_INSERT3) { length_insertions2 += diffs[pointer][1].length; } else { length_deletions2 += diffs[pointer][1].length; } if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch3.Diff(DIFF_DELETE3, lastEquality)); diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT3; equalitiesLength--; equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; length_insertions1 = 0; length_deletions1 = 0; length_insertions2 = 0; length_deletions2 = 0; lastEquality = null; changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } this.diff_cleanupSemanticLossless(diffs); pointer = 1; while (pointer < diffs.length) { if (diffs[pointer - 1][0] == DIFF_DELETE3 && diffs[pointer][0] == DIFF_INSERT3) { var deletion = diffs[pointer - 1][1]; var insertion = diffs[pointer][1]; var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); if (overlap_length1 >= overlap_length2) { if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { diffs.splice(pointer, 0, new diff_match_patch3.Diff(DIFF_EQUAL3, insertion.substring(0, overlap_length1))); diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); diffs[pointer + 1][1] = insertion.substring(overlap_length1); pointer++; } } else { if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { diffs.splice(pointer, 0, new diff_match_patch3.Diff(DIFF_EQUAL3, deletion.substring(0, overlap_length2))); diffs[pointer - 1][0] = DIFF_INSERT3; diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); diffs[pointer + 1][0] = DIFF_DELETE3; diffs[pointer + 1][1] = deletion.substring(overlap_length2); pointer++; } } pointer++; } pointer++; } }; diff_match_patch3.prototype.diff_cleanupSemanticLossless = function(diffs) { function diff_cleanupSemanticScore_(one, two) { if (!one || !two) { return 6; } var char1 = one.charAt(one.length - 1); var char2 = two.charAt(0); var nonAlphaNumeric1 = char1.match(diff_match_patch3.nonAlphaNumericRegex_); var nonAlphaNumeric2 = char2.match(diff_match_patch3.nonAlphaNumericRegex_); var whitespace1 = nonAlphaNumeric1 && char1.match(diff_match_patch3.whitespaceRegex_); var whitespace2 = nonAlphaNumeric2 && char2.match(diff_match_patch3.whitespaceRegex_); var lineBreak1 = whitespace1 && char1.match(diff_match_patch3.linebreakRegex_); var lineBreak2 = whitespace2 && char2.match(diff_match_patch3.linebreakRegex_); var blankLine1 = lineBreak1 && one.match(diff_match_patch3.blanklineEndRegex_); var blankLine2 = lineBreak2 && two.match(diff_match_patch3.blanklineStartRegex_); if (blankLine1 || blankLine2) { return 5; } else if (lineBreak1 || lineBreak2) { return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { return 3; } else if (whitespace1 || whitespace2) { return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { return 1; } return 0; } var pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL3 && diffs[pointer + 1][0] == DIFF_EQUAL3) { var equality1 = diffs[pointer - 1][1]; var edit = diffs[pointer][1]; var equality2 = diffs[pointer + 1][1]; var commonOffset = this.diff_commonSuffix(equality1, edit); if (commonOffset) { var commonString = edit.substring(edit.length - commonOffset); equality1 = equality1.substring(0, equality1.length - commonOffset); edit = commonString + edit.substring(0, edit.length - commonOffset); equality2 = commonString + equality2; } var bestEquality1 = equality1; var bestEdit = edit; var bestEquality2 = equality2; var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); while (edit.charAt(0) === equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (diffs[pointer - 1][1] != bestEquality1) { if (bestEquality1) { diffs[pointer - 1][1] = bestEquality1; } else { diffs.splice(pointer - 1, 1); pointer--; } diffs[pointer][1] = bestEdit; if (bestEquality2) { diffs[pointer + 1][1] = bestEquality2; } else { diffs.splice(pointer + 1, 1); pointer--; } } } pointer++; } }; diff_match_patch3.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; diff_match_patch3.whitespaceRegex_ = /\s/; diff_match_patch3.linebreakRegex_ = /[\r\n]/; diff_match_patch3.blanklineEndRegex_ = /\n\r?\n$/; diff_match_patch3.blanklineStartRegex_ = /^\r?\n\r?\n/; diff_match_patch3.prototype.diff_cleanupEfficiency = function(diffs) { var changes = false; var equalities = []; var equalitiesLength = 0; var lastEquality = null; var pointer = 0; var pre_ins = false; var pre_del = false; var post_ins = false; var post_del = false; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL3) { if (diffs[pointer][1].length < this.Diff_EditCost && (post_ins || post_del)) { equalities[equalitiesLength++] = pointer; pre_ins = post_ins; pre_del = post_del; lastEquality = diffs[pointer][1]; } else { equalitiesLength = 0; lastEquality = null; } post_ins = post_del = false; } else { if (diffs[pointer][0] == DIFF_DELETE3) { post_del = true; } else { post_ins = true; } if (lastEquality && (pre_ins && pre_del && post_ins && post_del || lastEquality.length < this.Diff_EditCost / 2 && pre_ins + pre_del + post_ins + post_del == 3)) { diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch3.Diff(DIFF_DELETE3, lastEquality)); diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT3; equalitiesLength--; lastEquality = null; if (pre_ins && pre_del) { post_ins = post_del = true; equalitiesLength = 0; } else { equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; post_ins = post_del = false; } changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } }; diff_match_patch3.prototype.diff_cleanupMerge = function(diffs) { diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, "")); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT3: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE3: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL3: if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { commonlength = this.diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL3) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, new diff_match_patch3.Diff(DIFF_EQUAL3, text_insert.substring(0, commonlength))); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } commonlength = this.diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } pointer -= count_delete + count_insert; diffs.splice(pointer, count_delete + count_insert); if (text_delete.length) { diffs.splice(pointer, 0, new diff_match_patch3.Diff(DIFF_DELETE3, text_delete)); pointer++; } if (text_insert.length) { diffs.splice(pointer, 0, new diff_match_patch3.Diff(DIFF_INSERT3, text_insert)); pointer++; } pointer++; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL3) { diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } } if (diffs[diffs.length - 1][1] === "") { diffs.pop(); } var changes = false; pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL3 && diffs[pointer + 1][0] == DIFF_EQUAL3) { if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } }; diff_match_patch3.prototype.diff_xIndex = function(diffs, loc) { var chars1 = 0; var chars2 = 0; var last_chars1 = 0; var last_chars2 = 0; var x; for (x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_INSERT3) { chars1 += diffs[x][1].length; } if (diffs[x][0] !== DIFF_DELETE3) { chars2 += diffs[x][1].length; } if (chars1 > loc) { break; } last_chars1 = chars1; last_chars2 = chars2; } if (diffs.length != x && diffs[x][0] === DIFF_DELETE3) { return last_chars2; } return last_chars2 + (loc - last_chars1); }; diff_match_patch3.prototype.diff_prettyHtml = function(diffs) { var html = []; var pattern_amp = /&/g; var pattern_lt = //g; var pattern_para = /\n/g; for (var x = 0; x < diffs.length; x++) { var op = diffs[x][0]; var data = diffs[x][1]; var text2 = data.replace(pattern_amp, "&").replace(pattern_lt, "<").replace(pattern_gt, ">").replace(pattern_para, "¶
"); switch (op) { case DIFF_INSERT3: html[x] = '' + text2 + ""; break; case DIFF_DELETE3: html[x] = '' + text2 + ""; break; case DIFF_EQUAL3: html[x] = "" + text2 + ""; break; } } return html.join(""); }; diff_match_patch3.prototype.diff_text1 = function(diffs) { var text2 = []; for (var x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_INSERT3) { text2[x] = diffs[x][1]; } } return text2.join(""); }; diff_match_patch3.prototype.diff_text2 = function(diffs) { var text2 = []; for (var x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_DELETE3) { text2[x] = diffs[x][1]; } } return text2.join(""); }; diff_match_patch3.prototype.diff_levenshtein = function(diffs) { var levenshtein = 0; var insertions = 0; var deletions = 0; for (var x = 0; x < diffs.length; x++) { var op = diffs[x][0]; var data = diffs[x][1]; switch (op) { case DIFF_INSERT3: insertions += data.length; break; case DIFF_DELETE3: deletions += data.length; break; case DIFF_EQUAL3: levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; }; diff_match_patch3.prototype.diff_toDelta = function(diffs) { var text2 = []; for (var x = 0; x < diffs.length; x++) { switch (diffs[x][0]) { case DIFF_INSERT3: text2[x] = "+" + encodeURI(diffs[x][1]); break; case DIFF_DELETE3: text2[x] = "-" + diffs[x][1].length; break; case DIFF_EQUAL3: text2[x] = "=" + diffs[x][1].length; break; } } return text2.join(" ").replace(/%20/g, " "); }; diff_match_patch3.prototype.diff_fromDelta = function(text1, delta) { var diffs = []; var diffsLength = 0; var pointer = 0; var tokens = delta.split(/\t/g); for (var x = 0; x < tokens.length; x++) { var param = tokens[x].substring(1); switch (tokens[x].charAt(0)) { case "+": try { diffs[diffsLength++] = new diff_match_patch3.Diff(DIFF_INSERT3, decodeURI(param)); } catch (ex) { throw new Error("Illegal escape in diff_fromDelta: " + param); } break; case "-": case "=": var n3 = parseInt(param, 10); if (isNaN(n3) || n3 < 0) { throw new Error("Invalid number in diff_fromDelta: " + param); } var text2 = text1.substring(pointer, pointer += n3); if (tokens[x].charAt(0) == "=") { diffs[diffsLength++] = new diff_match_patch3.Diff(DIFF_EQUAL3, text2); } else { diffs[diffsLength++] = new diff_match_patch3.Diff(DIFF_DELETE3, text2); } break; default: if (tokens[x]) { throw new Error("Invalid diff operation in diff_fromDelta: " + tokens[x]); } } } if (pointer != text1.length) { throw new Error("Delta length (" + pointer + ") does not equal source text length (" + text1.length + ")."); } return diffs; }; diff_match_patch3.prototype.match_main = function(text2, pattern, loc) { if (text2 == null || pattern == null || loc == null) { throw new Error("Null input. (match_main)"); } loc = Math.max(0, Math.min(loc, text2.length)); if (text2 == pattern) { return 0; } else if (!text2.length) { return -1; } else if (text2.substring(loc, loc + pattern.length) == pattern) { return loc; } else { return this.match_bitap_(text2, pattern, loc); } }; diff_match_patch3.prototype.match_bitap_ = function(text2, pattern, loc) { if (pattern.length > this.Match_MaxBits) { throw new Error("Pattern too long for this browser."); } var s = this.match_alphabet_(pattern); var dmp = this; function match_bitapScore_(e3, x) { var accuracy = e3 / pattern.length; var proximity = Math.abs(loc - x); if (!dmp.Match_Distance) { return proximity ? 1 : accuracy; } return accuracy + proximity / dmp.Match_Distance; } var score_threshold = this.Match_Threshold; var best_loc = text2.indexOf(pattern, loc); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); best_loc = text2.lastIndexOf(pattern, loc + pattern.length); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); } } var matchmask = 1 << pattern.length - 1; best_loc = -1; var bin_min, bin_mid; var bin_max = pattern.length + text2.length; var last_rd; for (var d = 0; d < pattern.length; d++) { bin_min = 0; bin_mid = bin_max; while (bin_min < bin_mid) { if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { bin_min = bin_mid; } else { bin_max = bin_mid; } bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); } bin_max = bin_mid; var start = Math.max(1, loc - bin_mid + 1); var finish = Math.min(loc + bin_mid, text2.length) + pattern.length; var rd = Array(finish + 2); rd[finish + 1] = (1 << d) - 1; for (var j = finish; j >= start; j--) { var charMatch = s[text2.charAt(j - 1)]; if (d === 0) { rd[j] = (rd[j + 1] << 1 | 1) & charMatch; } else { rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((last_rd[j + 1] | last_rd[j]) << 1 | 1) | last_rd[j + 1]; } if (rd[j] & matchmask) { var score = match_bitapScore_(d, j - 1); if (score <= score_threshold) { score_threshold = score; best_loc = j - 1; if (best_loc > loc) { start = Math.max(1, 2 * loc - best_loc); } else { break; } } } } if (match_bitapScore_(d + 1, loc) > score_threshold) { break; } last_rd = rd; } return best_loc; }; diff_match_patch3.prototype.match_alphabet_ = function(pattern) { var s = {}; for (var i2 = 0; i2 < pattern.length; i2++) { s[pattern.charAt(i2)] = 0; } for (var i2 = 0; i2 < pattern.length; i2++) { s[pattern.charAt(i2)] |= 1 << pattern.length - i2 - 1; } return s; }; diff_match_patch3.prototype.patch_addContext_ = function(patch, text2) { if (text2.length == 0) { return; } if (patch.start2 === null) { throw Error("patch not initialized"); } var pattern = text2.substring(patch.start2, patch.start2 + patch.length1); var padding = 0; while (text2.indexOf(pattern) != text2.lastIndexOf(pattern) && pattern.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin) { padding += this.Patch_Margin; pattern = text2.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding); } padding += this.Patch_Margin; var prefix = text2.substring(patch.start2 - padding, patch.start2); if (prefix) { patch.diffs.unshift(new diff_match_patch3.Diff(DIFF_EQUAL3, prefix)); } var suffix = text2.substring(patch.start2 + patch.length1, patch.start2 + patch.length1 + padding); if (suffix) { patch.diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, suffix)); } patch.start1 -= prefix.length; patch.start2 -= prefix.length; patch.length1 += prefix.length + suffix.length; patch.length2 += prefix.length + suffix.length; }; diff_match_patch3.prototype.patch_make = function(a, opt_b, opt_c) { var text1, diffs; if (typeof a == "string" && typeof opt_b == "string" && typeof opt_c == "undefined") { text1 = a; diffs = this.diff_main(text1, opt_b, true); if (diffs.length > 2) { this.diff_cleanupSemantic(diffs); this.diff_cleanupEfficiency(diffs); } } else if (a && typeof a == "object" && typeof opt_b == "undefined" && typeof opt_c == "undefined") { diffs = a; text1 = this.diff_text1(diffs); } else if (typeof a == "string" && opt_b && typeof opt_b == "object" && typeof opt_c == "undefined") { text1 = a; diffs = opt_b; } else if (typeof a == "string" && typeof opt_b == "string" && opt_c && typeof opt_c == "object") { text1 = a; diffs = opt_c; } else { throw new Error("Unknown call format to patch_make."); } if (diffs.length === 0) { return []; } var patches = []; var patch = new diff_match_patch3.patch_obj(); var patchDiffLength = 0; var char_count1 = 0; var char_count2 = 0; var prepatch_text = text1; var postpatch_text = text1; for (var x = 0; x < diffs.length; x++) { var diff_type = diffs[x][0]; var diff_text = diffs[x][1]; if (!patchDiffLength && diff_type !== DIFF_EQUAL3) { patch.start1 = char_count1; patch.start2 = char_count2; } switch (diff_type) { case DIFF_INSERT3: patch.diffs[patchDiffLength++] = diffs[x]; patch.length2 += diff_text.length; postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + postpatch_text.substring(char_count2); break; case DIFF_DELETE3: patch.length1 += diff_text.length; patch.diffs[patchDiffLength++] = diffs[x]; postpatch_text = postpatch_text.substring(0, char_count2) + postpatch_text.substring(char_count2 + diff_text.length); break; case DIFF_EQUAL3: if (diff_text.length <= 2 * this.Patch_Margin && patchDiffLength && diffs.length != x + 1) { patch.diffs[patchDiffLength++] = diffs[x]; patch.length1 += diff_text.length; patch.length2 += diff_text.length; } else if (diff_text.length >= 2 * this.Patch_Margin) { if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); patch = new diff_match_patch3.patch_obj(); patchDiffLength = 0; prepatch_text = postpatch_text; char_count1 = char_count2; } } break; } if (diff_type !== DIFF_INSERT3) { char_count1 += diff_text.length; } if (diff_type !== DIFF_DELETE3) { char_count2 += diff_text.length; } } if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); } return patches; }; diff_match_patch3.prototype.patch_deepCopy = function(patches) { var patchesCopy = []; for (var x = 0; x < patches.length; x++) { var patch = patches[x]; var patchCopy = new diff_match_patch3.patch_obj(); patchCopy.diffs = []; for (var y = 0; y < patch.diffs.length; y++) { patchCopy.diffs[y] = new diff_match_patch3.Diff(patch.diffs[y][0], patch.diffs[y][1]); } patchCopy.start1 = patch.start1; patchCopy.start2 = patch.start2; patchCopy.length1 = patch.length1; patchCopy.length2 = patch.length2; patchesCopy[x] = patchCopy; } return patchesCopy; }; diff_match_patch3.prototype.patch_apply = function(patches, text2) { if (patches.length == 0) { return [text2, []]; } patches = this.patch_deepCopy(patches); var nullPadding = this.patch_addPadding(patches); text2 = nullPadding + text2 + nullPadding; this.patch_splitMax(patches); var delta = 0; var results = []; for (var x = 0; x < patches.length; x++) { var expected_loc = patches[x].start2 + delta; var text1 = this.diff_text1(patches[x].diffs); var start_loc; var end_loc = -1; if (text1.length > this.Match_MaxBits) { start_loc = this.match_main(text2, text1.substring(0, this.Match_MaxBits), expected_loc); if (start_loc != -1) { end_loc = this.match_main(text2, text1.substring(text1.length - this.Match_MaxBits), expected_loc + text1.length - this.Match_MaxBits); if (end_loc == -1 || start_loc >= end_loc) { start_loc = -1; } } } else { start_loc = this.match_main(text2, text1, expected_loc); } if (start_loc == -1) { results[x] = false; delta -= patches[x].length2 - patches[x].length1; } else { results[x] = true; delta = start_loc - expected_loc; var text22; if (end_loc == -1) { text22 = text2.substring(start_loc, start_loc + text1.length); } else { text22 = text2.substring(start_loc, end_loc + this.Match_MaxBits); } if (text1 == text22) { text2 = text2.substring(0, start_loc) + this.diff_text2(patches[x].diffs) + text2.substring(start_loc + text1.length); } else { var diffs = this.diff_main(text1, text22, false); if (text1.length > this.Match_MaxBits && this.diff_levenshtein(diffs) / text1.length > this.Patch_DeleteThreshold) { results[x] = false; } else { this.diff_cleanupSemanticLossless(diffs); var index1 = 0; var index2; for (var y = 0; y < patches[x].diffs.length; y++) { var mod = patches[x].diffs[y]; if (mod[0] !== DIFF_EQUAL3) { index2 = this.diff_xIndex(diffs, index1); } if (mod[0] === DIFF_INSERT3) { text2 = text2.substring(0, start_loc + index2) + mod[1] + text2.substring(start_loc + index2); } else if (mod[0] === DIFF_DELETE3) { text2 = text2.substring(0, start_loc + index2) + text2.substring(start_loc + this.diff_xIndex(diffs, index1 + mod[1].length)); } if (mod[0] !== DIFF_DELETE3) { index1 += mod[1].length; } } } } } } text2 = text2.substring(nullPadding.length, text2.length - nullPadding.length); return [text2, results]; }; diff_match_patch3.prototype.patch_addPadding = function(patches) { var paddingLength = this.Patch_Margin; var nullPadding = ""; for (var x = 1; x <= paddingLength; x++) { nullPadding += String.fromCharCode(x); } for (var x = 0; x < patches.length; x++) { patches[x].start1 += paddingLength; patches[x].start2 += paddingLength; } var patch = patches[0]; var diffs = patch.diffs; if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL3) { diffs.unshift(new diff_match_patch3.Diff(DIFF_EQUAL3, nullPadding)); patch.start1 -= paddingLength; patch.start2 -= paddingLength; patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[0][1].length) { var extraLength = paddingLength - diffs[0][1].length; diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; patch.start1 -= extraLength; patch.start2 -= extraLength; patch.length1 += extraLength; patch.length2 += extraLength; } patch = patches[patches.length - 1]; diffs = patch.diffs; if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL3) { diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, nullPadding)); patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[diffs.length - 1][1].length) { var extraLength = paddingLength - diffs[diffs.length - 1][1].length; diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); patch.length1 += extraLength; patch.length2 += extraLength; } return nullPadding; }; diff_match_patch3.prototype.patch_splitMax = function(patches) { var patch_size = this.Match_MaxBits; for (var x = 0; x < patches.length; x++) { if (patches[x].length1 <= patch_size) { continue; } var bigpatch = patches[x]; patches.splice(x--, 1); var start1 = bigpatch.start1; var start2 = bigpatch.start2; var precontext = ""; while (bigpatch.diffs.length !== 0) { var patch = new diff_match_patch3.patch_obj(); var empty2 = true; patch.start1 = start1 - precontext.length; patch.start2 = start2 - precontext.length; if (precontext !== "") { patch.length1 = patch.length2 = precontext.length; patch.diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, precontext)); } while (bigpatch.diffs.length !== 0 && patch.length1 < patch_size - this.Patch_Margin) { var diff_type = bigpatch.diffs[0][0]; var diff_text = bigpatch.diffs[0][1]; if (diff_type === DIFF_INSERT3) { patch.length2 += diff_text.length; start2 += diff_text.length; patch.diffs.push(bigpatch.diffs.shift()); empty2 = false; } else if (diff_type === DIFF_DELETE3 && patch.diffs.length == 1 && patch.diffs[0][0] == DIFF_EQUAL3 && diff_text.length > 2 * patch_size) { patch.length1 += diff_text.length; start1 += diff_text.length; empty2 = false; patch.diffs.push(new diff_match_patch3.Diff(diff_type, diff_text)); bigpatch.diffs.shift(); } else { diff_text = diff_text.substring(0, patch_size - patch.length1 - this.Patch_Margin); patch.length1 += diff_text.length; start1 += diff_text.length; if (diff_type === DIFF_EQUAL3) { patch.length2 += diff_text.length; start2 += diff_text.length; } else { empty2 = false; } patch.diffs.push(new diff_match_patch3.Diff(diff_type, diff_text)); if (diff_text == bigpatch.diffs[0][1]) { bigpatch.diffs.shift(); } else { bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diff_text.length); } } } precontext = this.diff_text2(patch.diffs); precontext = precontext.substring(precontext.length - this.Patch_Margin); var postcontext = this.diff_text1(bigpatch.diffs).substring(0, this.Patch_Margin); if (postcontext !== "") { patch.length1 += postcontext.length; patch.length2 += postcontext.length; if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL3) { patch.diffs[patch.diffs.length - 1][1] += postcontext; } else { patch.diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, postcontext)); } } if (!empty2) { patches.splice(++x, 0, patch); } } } }; diff_match_patch3.prototype.patch_toText = function(patches) { var text2 = []; for (var x = 0; x < patches.length; x++) { text2[x] = patches[x]; } return text2.join(""); }; diff_match_patch3.prototype.patch_fromText = function(textline) { var patches = []; if (!textline) { return patches; } var text2 = textline.split("\n"); var textPointer = 0; var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; while (textPointer < text2.length) { var m = text2[textPointer].match(patchHeader); if (!m) { throw new Error("Invalid patch string: " + text2[textPointer]); } var patch = new diff_match_patch3.patch_obj(); patches.push(patch); patch.start1 = parseInt(m[1], 10); if (m[2] === "") { patch.start1--; patch.length1 = 1; } else if (m[2] == "0") { patch.length1 = 0; } else { patch.start1--; patch.length1 = parseInt(m[2], 10); } patch.start2 = parseInt(m[3], 10); if (m[4] === "") { patch.start2--; patch.length2 = 1; } else if (m[4] == "0") { patch.length2 = 0; } else { patch.start2--; patch.length2 = parseInt(m[4], 10); } textPointer++; while (textPointer < text2.length) { var sign = text2[textPointer].charAt(0); try { var line = decodeURI(text2[textPointer].substring(1)); } catch (ex) { throw new Error("Illegal escape in patch_fromText: " + line); } if (sign == "-") { patch.diffs.push(new diff_match_patch3.Diff(DIFF_DELETE3, line)); } else if (sign == "+") { patch.diffs.push(new diff_match_patch3.Diff(DIFF_INSERT3, line)); } else if (sign == " ") { patch.diffs.push(new diff_match_patch3.Diff(DIFF_EQUAL3, line)); } else if (sign == "@") { break; } else if (sign === "") { } else { throw new Error('Invalid patch mode "' + sign + '" in: ' + line); } textPointer++; } } return patches; }; diff_match_patch3.patch_obj = function() { this.diffs = []; this.start1 = null; this.start2 = null; this.length1 = 0; this.length2 = 0; }; diff_match_patch3.patch_obj.prototype.toString = function() { var coords1, coords2; if (this.length1 === 0) { coords1 = this.start1 + ",0"; } else if (this.length1 == 1) { coords1 = this.start1 + 1; } else { coords1 = this.start1 + 1 + "," + this.length1; } if (this.length2 === 0) { coords2 = this.start2 + ",0"; } else if (this.length2 == 1) { coords2 = this.start2 + 1; } else { coords2 = this.start2 + 1 + "," + this.length2; } var text2 = ["@@ -" + coords1 + " +" + coords2 + " @@\n"]; var op; for (var x = 0; x < this.diffs.length; x++) { switch (this.diffs[x][0]) { case DIFF_INSERT3: op = "+"; break; case DIFF_DELETE3: op = "-"; break; case DIFF_EQUAL3: op = " "; break; } text2[x + 1] = op + encodeURI(this.diffs[x][1]) + "\n"; } return text2.join("").replace(/%20/g, " "); }; module2.exports = diff_match_patch3; module2.exports["diff_match_patch"] = diff_match_patch3; module2.exports["DIFF_DELETE"] = DIFF_DELETE3; module2.exports["DIFF_INSERT"] = DIFF_INSERT3; module2.exports["DIFF_EQUAL"] = DIFF_EQUAL3; } }); // src/main.ts __export(exports, { default: () => ObsidianLiveSyncPlugin }); var import_obsidian8 = __toModule(require("obsidian")); var import_diff_match_patch3 = __toModule(require_diff_match_patch()); // src/lib/src/types.ts var MAX_DOC_SIZE = 1e3; var MAX_DOC_SIZE_BIN = 102400; var VER = 10; var LEAF_WAIT_TIMEOUT = 9e4; var LOG_LEVEL = { DEBUG: -1, VERBOSE: 1, INFO: 10, NOTICE: 100, URGENT: 1e3 }; var VERSIONINFO_DOCID = "obsydian_livesync_version"; var MILSTONE_DOCID = "_local/obsydian_livesync_milestone"; var NODEINFO_DOCID = "_local/obsydian_livesync_nodeinfo"; var 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: "", workingEncrypt: false, workingPassphrase: "", doNotDeleteFolder: false, resolveConflictsByNewerFile: false, batchSave: false, deviceAndVaultName: "", usePluginSettings: false, showOwnPlugins: false, showStatusOnEditor: false, usePluginSync: false, autoSweepPlugins: false, autoSweepPluginsPeriodic: false, notifyPluginOrSettingUpdated: false, checkIntegrityOnSave: false, batch_size: 250, batches_limit: 40, useHistory: false, disableRequestURI: false, skipOlderFilesOnSync: true, checkConflictOnlyOnOpen: true, 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 }; var FLAGMD_REDFLAG = "redflag.md"; var SYNCINFO_ID = "syncinfo"; // src/types.ts var PERIODIC_PLUGIN_SWEEP = 60; // src/lib/src/logger.ts var Logger = async (message, _) => { const timestamp = new Date().toLocaleString(); const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2); const newMessage = timestamp + "->" + messageContent; console.log(newMessage); }; function setLogger(loggerFun) { Logger = loggerFun; } // src/lib/src/e2ee_v2.ts var import_crypto = __toModule(require("crypto")); var webcrypto; if (typeof window !== "undefined" && window.crypto) { webcrypto = window.crypto; } else { const crypto2 = import_crypto.webcrypto; webcrypto = crypto2; } var KeyBuffs = new Map(); var decKeyBuffs = new Map(); var KEY_RECYCLE_COUNT = 100; var semiStaticFieldBuffer; var nonceBuffer = new Uint32Array(1); async function getKeyForEncrypt(passphrase) { const f = KeyBuffs.get(passphrase); if (f) { f.count--; if (f.count > 0) { return [f.key, f.salt]; } f.count--; } const passphraseBin = new TextEncoder().encode(passphrase); const digest = await webcrypto.subtle.digest({ name: "SHA-256" }, passphraseBin); const keyMaterial = await webcrypto.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]); const salt = webcrypto.getRandomValues(new Uint8Array(16)); const key = await webcrypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt"]); KeyBuffs.set(passphrase, { key, salt, count: KEY_RECYCLE_COUNT }); return [key, salt]; } var keyGCCount = KEY_RECYCLE_COUNT * 5; var decKeyIdx = 0; var decKeyMin = 0; async function getKeyForDecryption(passphrase, salt) { keyGCCount--; if (keyGCCount < 0) { keyGCCount = KEY_RECYCLE_COUNT; const threshold = (decKeyIdx - decKeyMin) / 2; for (const [key2, buff] of decKeyBuffs) { if (buff.count < threshold) { decKeyBuffs.delete(key2); } decKeyMin = decKeyIdx; } } decKeyIdx++; const bufKey = passphrase + uint8ArrayToHexString(salt); const f = decKeyBuffs.get(bufKey); if (f) { f.count = decKeyIdx; return [f.key, f.salt]; } const passphraseBin = new TextEncoder().encode(passphrase); const digest = await webcrypto.subtle.digest({ name: "SHA-256" }, passphraseBin); const keyMaterial = await webcrypto.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]); const key = await webcrypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["decrypt"]); decKeyBuffs.set(bufKey, { key, salt, count: 0 }); return [key, salt]; } function getSemiStaticField(reset) { if (semiStaticFieldBuffer != null && !reset) { return semiStaticFieldBuffer; } semiStaticFieldBuffer = webcrypto.getRandomValues(new Uint8Array(12)); return semiStaticFieldBuffer; } function getNonce() { nonceBuffer[0]++; if (nonceBuffer[0] > 1e4) { getSemiStaticField(true); } return nonceBuffer; } function btoa_node(src) { return Buffer.from(src, "binary").toString("base64"); } function atob_node(src) { return Buffer.from(src, "base64").toString("binary"); } var btoa2 = typeof window !== "undefined" ? window.btoa : btoa_node; var atob2 = typeof window !== "undefined" ? window.atob : atob_node; var revMap = {}; var numMap = {}; for (let i2 = 0; i2 < 256; i2++) { revMap[`00${i2.toString(16)}`.slice(-2)] = i2; numMap[i2] = `00${i2.toString(16)}`.slice(-2); } function hexStringToUint8Array(src) { const len = src.length / 2; const ret = new Uint8Array(len); for (let i2 = 0; i2 < len; i2++) { ret[i2] = revMap[src[i2 * 2] + src[i2 * 2 + 1]]; } return ret; } function uint8ArrayToHexString(src) { return [...src].map((e3) => numMap[e3]).join(""); } var QUANTUM = 32768; var writeString = (string) => { const buffer = new Uint8Array(string.length * 4); const length = string.length; let index = 0; let chr = 0; let idx = 0; while (idx < length) { chr = string.charCodeAt(idx++); if (chr < 128) { buffer[index++] = chr; } else if (chr < 2048) { buffer[index++] = 192 | chr >>> 6; buffer[index++] = 128 | chr & 63; } else if (chr < 55296 || chr > 57343) { buffer[index++] = 224 | chr >>> 12; buffer[index++] = 128 | chr >>> 6 & 63; buffer[index++] = 128 | chr & 63; } else { chr = (chr - 55296 << 10 | string.charCodeAt(idx++) - 56320) + 65536; buffer[index++] = 240 | chr >>> 18; buffer[index++] = 128 | chr >>> 12 & 63; buffer[index++] = 128 | chr >>> 6 & 63; buffer[index++] = 128 | chr & 63; } } return buffer.slice(0, index); }; var readString = (buffer) => { const length = buffer.length; let index = 0; const end = length; let string = ""; while (index < end) { const chunk = []; const cEnd = Math.min(index + QUANTUM, end); while (index < cEnd) { const chr = buffer[index++]; if (chr < 128) { chunk.push(chr); } else if ((chr & 224) === 192) { chunk.push((chr & 31) << 6 | buffer[index++] & 63); } else if ((chr & 240) === 224) { chunk.push((chr & 15) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63); } else if ((chr & 248) === 240) { let code = (chr & 7) << 18 | (buffer[index++] & 63) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63; if (code < 65536) { chunk.push(code); } else { code -= 65536; chunk.push((code >>> 10) + 55296, (code & 1023) + 56320); } } } string += String.fromCharCode(...chunk); } return string; }; function binaryToBinaryString(src) { const len = src.length; if (len < QUANTUM) return String.fromCharCode(...src); let ret = ""; for (let i2 = 0; i2 < len; i2 += QUANTUM) { ret += String.fromCharCode(...src.slice(i2, i2 + QUANTUM)); } return ret; } async function encrypt(input, passphrase) { const [key, salt] = await getKeyForEncrypt(passphrase); const fixedPart = getSemiStaticField(); const invocationPart = getNonce(); const iv = new Uint8Array([...fixedPart, ...new Uint8Array(invocationPart.buffer)]); const plainStringified = JSON.stringify(input); const plainStringBuffer = writeString(plainStringified); const encryptedDataArrayBuffer = await webcrypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plainStringBuffer); const encryptedData2 = btoa2(binaryToBinaryString(new Uint8Array(encryptedDataArrayBuffer))); const ret = `["${encryptedData2}","${uint8ArrayToHexString(iv)}","${uint8ArrayToHexString(salt)}"]`; return ret; } async function decrypt(encryptedResult, passphrase) { try { if (!encryptedResult.startsWith("[") || !encryptedResult.endsWith("]")) { throw new Error("Encrypted data corrupted!"); } const w = encryptedResult.substring(1, encryptedResult.length - 1).split(",").map((e3) => e3[0] == '"' ? e3.substring(1, e3.length - 1) : e3); const [encryptedData, ivString, salt] = w; const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt)); const iv = hexStringToUint8Array(ivString); const encryptedDataBin = atob2(encryptedData); const len = encryptedDataBin.length; const encryptedDataArrayBuffer = new Uint8Array(len); for (let i2 = 0; i2 < len; i2++) { encryptedDataArrayBuffer[i2] = encryptedDataBin.charCodeAt(i2); } const plainStringBuffer = await webcrypto.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer); const plainStringified = readString(new Uint8Array(plainStringBuffer)); const plain = JSON.parse(plainStringified); return plain; } catch (ex) { Logger("Couldn't decode! You should wrong the passphrases", LOG_LEVEL.VERBOSE); Logger(ex, LOG_LEVEL.VERBOSE); throw ex; } } async function testCrypt() { const src = "supercalifragilisticexpialidocious"; const encoded = await encrypt(src, "passwordTest"); const decrypted = await decrypt(encoded, "passwordTest"); if (src != decrypted) { Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.VERBOSE); return false; } else { Logger("CRYPT LOGIC OK", LOG_LEVEL.VERBOSE); return true; } } // src/lib/src/utils.ts function arrayBufferToBase64(buffer) { return new Promise((res) => { const blob = new Blob([buffer], { type: "application/octet-binary" }); const reader = new FileReader(); reader.onload = function(evt) { const dataURI = evt.target.result.toString(); res(dataURI.substr(dataURI.indexOf(",") + 1)); }; reader.readAsDataURL(blob); }); } function base64ToString(base64) { try { const binary_string = window.atob(base64); const len = binary_string.length; const bytes = new Uint8Array(len); for (let i2 = 0; i2 < len; i2++) { bytes[i2] = binary_string.charCodeAt(i2); } return new TextDecoder().decode(bytes); } catch (ex) { return base64; } } function base64ToArrayBuffer(base64) { try { const binary_string = window.atob(base64); const len = binary_string.length; const bytes = new Uint8Array(len); for (let i2 = 0; i2 < len; i2++) { bytes[i2] = binary_string.charCodeAt(i2); } return bytes.buffer; } catch (ex) { try { return new Uint16Array([].map.call(base64, function(c) { return c.charCodeAt(0); })).buffer; } catch (ex2) { return null; } } } var escapeStringToHTML = (str) => { if (!str) return ""; return str.replace(/[<>&"'`]/g, (match) => { const escape = { "<": "<", ">": ">", "&": "&", '"': """, "'": "'", "`": "`" }; return escape[match]; }); }; function resolveWithIgnoreKnownError(p, def) { return new Promise((res, rej) => { p.then(res).catch((ex) => ex.status && ex.status == 404 ? res(def) : rej(ex)); }); } function isValidPath(filename) { const regex = /[\u0000-\u001f]|[\\":?<>|*#]/g; let x = filename.replace(regex, "_"); const win = /(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi; const sx = x = x.replace(win, "/_"); return sx == filename; } function shouldBeIgnored(filename) { if (filename == FLAGMD_REDFLAG) { return true; } return false; } function versionNumberString2Number(version) { return version.split(".").reverse().map((e3, i2) => e3 / 1 * 1e3 ** i2).reduce((prev, current) => prev + current, 0); } var delay = (ms) => { return new Promise((res) => { setTimeout(() => { res(); }, ms); }); }; function path2id_base(filename) { let x = filename; if (x.startsWith("_")) x = "/" + x; return x; } function id2path_base(filename) { return filename; } var externalNotifier = () => { }; var notifyTimer = null; function setLockNotifier(fn) { externalNotifier = fn; } function notifyLock() { if (notifyTimer != null) { clearTimeout(notifyTimer); } notifyTimer = setTimeout(() => { externalNotifier(); }, 100); } function splitPieces2(data, pieceSize, plainSplit, minimumChunkSize, longLineThreshold) { return function* pieces() { if (plainSplit) { const leftData = data.split("\n"); let buffer = ""; let leftLen = 0; do { buffer += leftData.shift(); leftLen = leftData.length; if (leftLen > 0) buffer += "\n"; if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") { do { yield buffer.substring(0, pieceSize); buffer = buffer.substring(pieceSize); } while (buffer != ""); } } while (leftLen > 0); } else { let leftData = data; do { const piece = leftData.substring(0, pieceSize); leftData = leftData.substring(pieceSize); yield piece; } while (leftData != ""); } }; } var WrappedNotice = class { constructor(message, timeout) { let strMessage = ""; if (message instanceof DocumentFragment) { strMessage = message.textContent; } else { strMessage = message; } Logger(strMessage, LOG_LEVEL.NOTICE); } setMessage(message) { let strMessage = ""; if (message instanceof DocumentFragment) { strMessage = message.textContent; } else { strMessage = message; } Logger(strMessage, LOG_LEVEL.NOTICE); return this; } hide() { } }; var _notice = WrappedNotice; function setNoticeClass(notice) { _notice = notice; } function NewNotice(message, timeout) { return new _notice(message, timeout); } function isPlainText(filename) { if (filename.endsWith(".md")) return true; if (filename.endsWith(".txt")) return true; if (filename.endsWith(".svg")) return true; if (filename.endsWith(".html")) return true; if (filename.endsWith(".csv")) return true; if (filename.endsWith(".css")) return true; if (filename.endsWith(".js")) return true; if (filename.endsWith(".xml")) return true; return false; } function shouldSplitAsPlainText(filename) { if (filename.endsWith(".md")) return true; if (filename.endsWith(".txt")) return true; } var enableEncryption = (db, passphrase, migrationDecrypt) => { const decrypted = new Map(); db.transform({ incoming: async (doc) => { const saveDoc = { ...doc }; if (saveDoc._id.startsWith("h:+") || saveDoc._id == SYNCINFO_ID) { try { saveDoc.data = await encrypt(saveDoc.data, passphrase); } catch (ex) { Logger("Encryption failed.", LOG_LEVEL.NOTICE); Logger(ex); throw ex; } } return saveDoc; }, outgoing: async (doc) => { const loadDoc = { ...doc }; if (loadDoc._id.startsWith("h:+") || loadDoc._id == SYNCINFO_ID) { if (migrationDecrypt && decrypted.has(loadDoc._id)) { return loadDoc; } try { loadDoc.data = await decrypt(loadDoc.data, passphrase); if (migrationDecrypt) { decrypted.set(loadDoc._id, true); } } catch (ex) { if (migrationDecrypt && ex.name == "SyntaxError") { return loadDoc; } Logger("Decryption failed.", LOG_LEVEL.NOTICE); Logger(ex); throw ex; } } return loadDoc; } }); }; function makeUniqueString() { const randomStrSrc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const temp = [...Array(30)].map(() => Math.floor(Math.random() * randomStrSrc.length)).map((e3) => randomStrSrc[e3]).join(""); return `${Date.now()}-${temp}`; } function Semaphore(limit, onRelease) { const _limit = limit; let currentProcesses = 0; let queue = []; function execProcess() { queue = queue.filter((e3) => e3.state != "DONE"); for (const queueItem of queue) { if (queueItem.state != "NONE") continue; if (queueItem.quantity + currentProcesses > _limit) { break; } queueItem.state = "RUNNING"; currentProcesses += queueItem.quantity; if (queueItem == null ? void 0 : queueItem.timer) { clearTimeout(queueItem.timer); } queueItem.notify(true); } } function release(key) { const finishedTask = queue.find((e3) => e3.key == key); if (!finishedTask) { throw new Error("Missing locked semaphore!"); } if (finishedTask.state == "RUNNING") { currentProcesses -= finishedTask.quantity; } finishedTask.state = "DONE"; if (onRelease) onRelease(queue.filter((e3) => e3.state != "DONE")); execProcess(); } return { _acquire(quantity, memo, timeout) { const key = makeUniqueString(); if (_limit < quantity) { throw Error("Too big quantity"); } let notify = (_) => { }; const semaphoreStopper = new Promise((res) => { notify = (result) => { if (result) { res(() => { release(key); }); } else { res(false); } }; }); const notifier = { key, notify, semaphoreStopper, quantity, memo, state: "NONE" }; if (timeout) notifier.timer = setTimeout(() => { release(key); notify(false); }, timeout); queue.push(notifier); execProcess(); return semaphoreStopper; }, acquire(quantity = 1, memo) { return this._acquire(quantity, memo != null ? memo : "", 0); }, tryAcquire(quantity = 1, timeout, memo) { return this._acquire(quantity, memo != null ? memo : "", timeout); }, peekQueues() { return queue; } }; } var Mutexes = {}; function getLocks() { const allLocks = [...Object.values(Mutexes).map((e3) => e3.peekQueues())].flat(); return { pending: allLocks.filter((e3) => e3.state == "NONE").map((e3) => e3.memo), running: allLocks.filter((e3) => e3.state == "RUNNING").map((e3) => e3.memo) }; } function getProcessingCounts() { return [...Object.values(Mutexes).map((e3) => e3.peekQueues())].flat().length; } var semaphoreReleasedCount = 0; async function runWithLock(key, ignoreWhenRunning, proc) { if (semaphoreReleasedCount > 200) { const deleteKeys = []; for (const key2 in Mutexes) { if (Mutexes[key2].peekQueues().length == 0) { deleteKeys.push(key2); } } for (const key2 of deleteKeys) { delete Mutexes[key2]; } semaphoreReleasedCount = 0; } if (!(key in Mutexes)) { Mutexes[key] = Semaphore(1, (queue) => { if (queue.length == 0) semaphoreReleasedCount++; }); } const timeout = ignoreWhenRunning ? 1 : 0; const releaser = await Mutexes[key].tryAcquire(1, timeout, key); if (!releaser) return null; try { return await proc(); } finally { releaser(); notifyLock(); } } // src/LocalPouchDB.ts var import_obsidian2 = __toModule(require("obsidian")); // node_modules/idb/build/wrap-idb-value.js var instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); var idbProxyableTypes; var cursorAdvanceMethods; function getIdbProxyableTypes() { return idbProxyableTypes || (idbProxyableTypes = [ IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction ]); } function getCursorAdvanceMethods() { return cursorAdvanceMethods || (cursorAdvanceMethods = [ IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey ]); } var cursorRequestMap = new WeakMap(); var transactionDoneMap = new WeakMap(); var transactionStoreNamesMap = new WeakMap(); var transformCache = new WeakMap(); var reverseTransformCache = new WeakMap(); function promisifyRequest(request) { const promise = new Promise((resolve, reject) => { const unlisten = () => { request.removeEventListener("success", success); request.removeEventListener("error", error); }; const success = () => { resolve(wrap(request.result)); unlisten(); }; const error = () => { reject(request.error); unlisten(); }; request.addEventListener("success", success); request.addEventListener("error", error); }); promise.then((value) => { if (value instanceof IDBCursor) { cursorRequestMap.set(value, request); } }).catch(() => { }); reverseTransformCache.set(promise, request); return promise; } function cacheDonePromiseForTransaction(tx) { if (transactionDoneMap.has(tx)) return; const done = new Promise((resolve, reject) => { const unlisten = () => { tx.removeEventListener("complete", complete); tx.removeEventListener("error", error); tx.removeEventListener("abort", error); }; const complete = () => { resolve(); unlisten(); }; const error = () => { reject(tx.error || new DOMException("AbortError", "AbortError")); unlisten(); }; tx.addEventListener("complete", complete); tx.addEventListener("error", error); tx.addEventListener("abort", error); }); transactionDoneMap.set(tx, done); } var idbProxyTraps = { get(target, prop, receiver) { if (target instanceof IDBTransaction) { if (prop === "done") return transactionDoneMap.get(target); if (prop === "objectStoreNames") { return target.objectStoreNames || transactionStoreNamesMap.get(target); } if (prop === "store") { return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]); } } return wrap(target[prop]); }, set(target, prop, value) { target[prop] = value; return true; }, has(target, prop) { if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) { return true; } return prop in target; } }; function replaceTraps(callback) { idbProxyTraps = callback(idbProxyTraps); } function wrapFunction(func) { if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) { return function(storeNames, ...args) { const tx = func.call(unwrap(this), storeNames, ...args); transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); return wrap(tx); }; } if (getCursorAdvanceMethods().includes(func)) { return function(...args) { func.apply(unwrap(this), args); return wrap(cursorRequestMap.get(this)); }; } return function(...args) { return wrap(func.apply(unwrap(this), args)); }; } function transformCachableValue(value) { if (typeof value === "function") return wrapFunction(value); if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); return value; } function wrap(value) { if (value instanceof IDBRequest) return promisifyRequest(value); if (transformCache.has(value)) return transformCache.get(value); const newValue = transformCachableValue(value); if (newValue !== value) { transformCache.set(value, newValue); reverseTransformCache.set(newValue, value); } return newValue; } var unwrap = (value) => reverseTransformCache.get(value); // node_modules/idb/build/index.js function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { const request = indexedDB.open(name, version); const openPromise = wrap(request); if (upgrade) { request.addEventListener("upgradeneeded", (event) => { upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); }); } if (blocked) request.addEventListener("blocked", () => blocked()); openPromise.then((db) => { if (terminated) db.addEventListener("close", () => terminated()); if (blocking) db.addEventListener("versionchange", () => blocking()); }).catch(() => { }); return openPromise; } function deleteDB(name, { blocked } = {}) { const request = indexedDB.deleteDatabase(name); if (blocked) request.addEventListener("blocked", () => blocked()); return wrap(request).then(() => void 0); } var readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; var writeMethods = ["put", "add", "delete", "clear"]; var cachedMethods = new Map(); function getMethod(target, prop) { if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) { return; } if (cachedMethods.get(prop)) return cachedMethods.get(prop); const targetFuncName = prop.replace(/FromIndex$/, ""); const useIndex = prop !== targetFuncName; const isWrite = writeMethods.includes(targetFuncName); if (!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) { return; } const method = async function(storeName, ...args) { const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly"); let target2 = tx.store; if (useIndex) target2 = target2.index(args.shift()); return (await Promise.all([ target2[targetFuncName](...args), isWrite && tx.done ]))[0]; }; cachedMethods.set(prop, method); return method; } replaceTraps((oldTraps) => ({ ...oldTraps, get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) })); // src/KeyValueDB.ts var databaseCache = {}; var OpenKeyValueDatabase = async (dbKey) => { if (dbKey in databaseCache) { databaseCache[dbKey].close(); delete databaseCache[dbKey]; } const storeKey = dbKey; const dbPromise = openDB(dbKey, 1, { upgrade(db2) { db2.createObjectStore(storeKey); } }); let db = null; db = await dbPromise; databaseCache[dbKey] = db; return { get(key) { return db.get(storeKey, key); }, set(key, value) { return db.put(storeKey, value, key); }, del(key) { return db.delete(storeKey, key); }, clear() { return db.clear(storeKey); }, keys(query, count) { return db.getAllKeys(storeKey, query, count); }, close() { delete databaseCache[dbKey]; return db.close(); }, async destroy() { delete databaseCache[dbKey]; db.close(); await deleteDB(dbKey); } }; }; // node_modules/xxhash-wasm/esm/xxhash-wasm.js var 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]); var e; function n(t3, e3, n3) { if (e3.buffer.byteLength < t3.byteLength + n3) { const i2 = Math.ceil((t3.byteLength + n3 - e3.buffer.byteLength) / 65536); e3.grow(i2); } new Uint8Array(e3.buffer, n3).set(t3); } async function xxhash_wasm_default() { const { instance: { exports: { mem: i2, xxh32: o, xxh64: r2 } } } = await WebAssembly.instantiate(t); function h(t3) { let e3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; return n(t3, i2, 0), o(0, t3.byteLength, e3) >>> 0; } function c(t3) { let e3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, o2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; n(t3, i2, 8); const h2 = new DataView(i2.buffer); return h2.setUint32(0, e3, true), h2.setUint32(4, o2, true), r2(0, t3.byteLength), h2; } return { h32: function(t3) { let n3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; e || (e = new TextEncoder()); const i3 = e.encode(t3); return h(i3, n3).toString(16); }, h32Raw: h, h64: function(t3) { let n3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, i3 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; e || (e = new TextEncoder()); const o2 = e.encode(t3), r3 = c(o2, n3, i3), h2 = r3.getUint32(0, true).toString(16) + r3.getUint32(4, true).toString(16); return h2; }, h64Raw: function(t3) { let e3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, n3 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; return new Uint8Array(c(t3, e3, n3).buffer, 0, 8); } }; } // src/lib/src/utils_couchdb.ts var isValidRemoteCouchDBURI = (uri) => { if (uri.startsWith("https://")) return true; if (uri.startsWith("http://")) return true; return false; }; function isCloudantURI(uri) { if (uri.indexOf(".cloudantnosqldb.") !== -1 || uri.indexOf(".cloudant.com") !== -1) return true; return false; } var checkRemoteVersion = async (db, migrate, barrier = VER) => { try { const versionInfo = await db.get(VERSIONINFO_DOCID); if (versionInfo.type != "versioninfo") { return false; } const version = versionInfo.version; if (version < barrier) { const versionUpResult = await migrate(version, barrier); if (versionUpResult) { await bumpRemoteVersion(db); return true; } } if (version == barrier) return true; return false; } catch (ex) { if (ex.status && ex.status == 404) { if (await bumpRemoteVersion(db)) { return true; } return false; } throw ex; } }; var bumpRemoteVersion = async (db, barrier = VER) => { const vi = { _id: VERSIONINFO_DOCID, version: barrier, type: "versioninfo" }; const versionInfo = await resolveWithIgnoreKnownError(db.get(VERSIONINFO_DOCID), vi); if (versionInfo.type != "versioninfo") { return false; } vi._rev = versionInfo._rev; await db.put(vi); return true; }; var checkSyncInfo = async (db) => { try { const syncinfo = await db.get(SYNCINFO_ID); console.log(syncinfo); return true; } catch (ex) { if (ex.status && ex.status == 404) { const randomStrSrc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const temp = [...Array(30)].map((e3) => Math.floor(Math.random() * randomStrSrc.length)).map((e3) => randomStrSrc[e3]).join(""); const newSyncInfo = { _id: SYNCINFO_ID, type: "syncinfo", data: temp }; if (await db.put(newSyncInfo)) { return true; } return false; } else { console.dir(ex); return false; } } }; async function putDesignDocuments(db) { const design = { "_id": "_design/replicate", "_rev": void 0, "ver": 2, "filters": { "default": function(doc, req) { return !("remote" in doc && doc.remote); }.toString(), "push": function(doc, req) { return true; }.toString(), "pull": function(doc, req) { return !(doc.type && doc.type == "leaf"); }.toString() } }; try { const w = await db.get(design._id); if (w.ver < design.ver) { design._rev = w._rev; await db.put(design); return true; } } catch (ex) { if (ex.status && ex.status == 404) { delete design._rev; await db.put(design); return true; } else { Logger("Could not make design documents", LOG_LEVEL.INFO); } } return false; } // src/lib/src/LRUCache.ts var LRUCache = class { constructor() { this.cache = new Map([]); this.revCache = new Map([]); this.maxCache = 100; } get(key) { const v = this.cache.get(key); if (v) { this.cache.delete(key); this.revCache.delete(v); this.cache.set(key, v); this.revCache.set(v, key); } return v; } revGet(value) { const key = this.revCache.get(value); if (value) { this.cache.delete(key); this.revCache.delete(value); this.cache.set(key, value); this.revCache.set(value, key); } return key; } set(key, value) { this.cache.set(key, value); this.revCache.set(value, key); if (this.cache.size > this.maxCache) { for (const kv of this.cache) { this.revCache.delete(kv[1]); this.cache.delete(kv[0]); if (this.cache.size <= this.maxCache) break; } } } }; // src/lib/src/LocalPouchDBBase.ts var currentVersionRange = { min: 0, max: 2, current: 2 }; var LocalPouchDBBase = class { constructor(settings, dbname, isMobile) { this.nodeid = ""; this.isReady = false; this.hashCaches = new LRUCache(); this.corruptedEntries = {}; this.remoteLocked = false; this.remoteLockedAndDeviceNotAccepted = false; this.changeHandler = null; this.syncHandler = null; this.leafArrivedCallbacks = {}; this.syncStatus = "NOT_CONNECTED"; this.docArrived = 0; this.docSent = 0; this.docSeq = ""; this.isMobile = false; this.chunkVersion = -1; this.maxChunkVersion = -1; this.minChunkVersion = -1; this.needScanning = false; this.updateInfo = () => { console.log("Update Info default implement"); }; this.originalSetting = null; this.collectThrottleTimeout = null; this.collectThrottleQueuedIds = []; this.chunkCollectedCallbacks = {}; this.auth = { username: "", password: "" }; this.dbname = dbname; this.settings = settings; this.cancelHandler = this.cancelHandler.bind(this); this.isMobile = isMobile; } cancelHandler(handler) { if (handler != null) { handler.removeAllListeners(); handler.cancel(); handler = null; } return null; } onunload() { this.beforeOnUnload(); this.leafArrivedCallbacks; this.changeHandler = this.cancelHandler(this.changeHandler); this.syncHandler = this.cancelHandler(this.syncHandler); this.localDatabase.removeAllListeners(); } close() { Logger("Database closed (by close)"); this.isReady = false; this.changeHandler = this.cancelHandler(this.changeHandler); if (this.localDatabase != null) { this.localDatabase.close(); } this.onClose(); } async isOldDatabaseExists() { const db = this.CreatePouchDBInstance(this.dbname + "-livesync", { auto_compaction: this.settings.useHistory ? false : true, revs_limit: 20, deterministic_revs: true, skip_setup: true }); try { const info = await db.info(); Logger(info, LOG_LEVEL.VERBOSE); return db; } catch (ex) { return false; } } async initializeDatabase() { await this.prepareHashFunctions(); if (this.localDatabase != null) this.localDatabase.close(); this.changeHandler = this.cancelHandler(this.changeHandler); this.localDatabase = null; this.localDatabase = this.CreatePouchDBInstance(this.dbname + "-livesync-v2", { auto_compaction: this.settings.useHistory ? false : true, revs_limit: 100, deterministic_revs: true }); await this.onInitializeDatabase(); Logger("Database info", LOG_LEVEL.VERBOSE); Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE); Logger("Open Database..."); const nextSeq = async () => { Logger("Database Info"); Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE); const nodeinfo = await resolveWithIgnoreKnownError(this.localDatabase.get(NODEINFO_DOCID), { _id: NODEINFO_DOCID, type: "nodeinfo", nodeid: "", v20220607: true }); if (nodeinfo.nodeid == "") { nodeinfo.nodeid = Math.random().toString(36).slice(-10); await this.localDatabase.put(nodeinfo); } this.localDatabase.on("close", () => { Logger("Database closed."); this.isReady = false; this.localDatabase.removeAllListeners(); }); this.nodeid = nodeinfo.nodeid; await putDesignDocuments(this.localDatabase); const changes = this.localDatabase.changes({ since: "now", live: true, filter: (doc) => doc.type == "leaf" }).on("change", (e3) => { if (e3.deleted) return; this.leafArrived(e3.id); this.docSeq = `${e3.seq}`; }); this.changeHandler = changes; this.isReady = true; Logger("Database is now ready."); return true; }; Logger("Checking old database", LOG_LEVEL.VERBOSE); const old = await this.isOldDatabaseExists(); if (old) { const oi = await old.info(); if (oi.doc_count == 0) { Logger("Old database is empty, proceed to next step", LOG_LEVEL.VERBOSE); return nextSeq(); } Logger("We have to upgrade database..", LOG_LEVEL.NOTICE, "conv"); try { const newDbStatus = await this.localDatabase.info(); Logger("New database is initialized"); Logger(newDbStatus); if (this.settings.encrypt) { enableEncryption(old, this.settings.passphrase, true); } const rep = old.replicate.to(this.localDatabase, { batch_size: 25, batches_limit: 10 }); rep.on("change", (e3) => { Logger(`Converting ${e3.docs_written} docs...`, LOG_LEVEL.NOTICE, "conv"); }); const w = await rep; if (w.ok) { Logger("Conversion completed!", LOG_LEVEL.NOTICE, "conv"); old.destroy(); this.isReady = true; return await nextSeq(); } else { throw new Error("Conversion failed!"); } } catch (ex) { Logger("Conversion failed!, If you are fully synchronized, please drop the old database in the Hatch pane in setting dialog. or please make an issue on Github.", LOG_LEVEL.NOTICE, "conv"); Logger(ex); this.isReady = false; return false; } } else { return await nextSeq(); } } async prepareHashFunctions() { if (this.h32 != null) return; const { h32, h32Raw } = await xxhash_wasm_default(); this.h32 = h32; this.h32Raw = h32Raw; } leafArrived(id) { if (typeof this.leafArrivedCallbacks[id] !== "undefined") { for (const func of this.leafArrivedCallbacks[id]) { func(); } delete this.leafArrivedCallbacks[id]; } } waitForLeafReady(id) { return new Promise((res, rej) => { const timer = setTimeout(() => rej(new Error(`Chunk reading timed out:${id}`)), LEAF_WAIT_TIMEOUT); if (typeof this.leafArrivedCallbacks[id] == "undefined") { this.leafArrivedCallbacks[id] = []; } this.leafArrivedCallbacks[id].push(() => { clearTimeout(timer); res(true); }); }); } async getDBLeaf(id, waitForReady) { const leaf = this.hashCaches.revGet(id); if (leaf) { return leaf; } try { const w = await this.localDatabase.get(id); if (w.type == "leaf") { this.hashCaches.set(id, w.data); return w.data; } throw new Error(`Corrupted chunk detected: ${id}`); } catch (ex) { if (ex.status && ex.status == 404) { if (waitForReady) { if (await this.waitForLeafReady(id) === false) { throw new Error(`time out (waiting chunk)`); } return this.getDBLeaf(id, false); } else { throw new Error(`Chunk was not found: ${id}`); } } else { Logger(`Something went wrong while retrieving chunks`); throw ex; } } } async getDBEntryMeta(path, opt, includeDeleted = false) { if (!this.isTargetFile(path)) { return false; } const id = this.path2id(path); try { let obj = null; if (opt) { obj = await this.localDatabase.get(id, opt); } else { obj = await this.localDatabase.get(id); } const deleted = "deleted" in obj ? obj.deleted : void 0; if (!includeDeleted && deleted) return false; if (obj.type && obj.type == "leaf") { return false; } if (!obj.type || obj.type && obj.type == "notes" || obj.type == "newnote" || obj.type == "plain") { const note = obj; let children2 = []; let type = "plain"; if (obj.type == "newnote" || obj.type == "plain") { children2 = obj.children; type = obj.type; } const doc = { data: "", _id: note._id, ctime: note.ctime, mtime: note.mtime, size: note.size, _rev: obj._rev, _conflicts: obj._conflicts, children: children2, datatype: type, deleted, type }; return doc; } } catch (ex) { if (ex.status && ex.status == 404) { return false; } throw ex; } return false; } async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) { if (!this.isTargetFile(path)) { return false; } const id = this.path2id(path); try { let obj = null; if (opt) { obj = await this.localDatabase.get(id, opt); } else { obj = await this.localDatabase.get(id); } const deleted = "deleted" in obj ? obj.deleted : void 0; if (!includeDeleted && deleted) return false; if (obj.type && obj.type == "leaf") { return false; } if (!obj.type || obj.type && obj.type == "notes") { const note = obj; const doc = { data: note.data, _id: note._id, ctime: note.ctime, mtime: note.mtime, size: note.size, _rev: obj._rev, _conflicts: obj._conflicts, children: [], datatype: "newnote", deleted, type: "newnote" }; if (typeof this.corruptedEntries[doc._id] != "undefined") { delete this.corruptedEntries[doc._id]; } if (dump) { Logger(`Simple doc`); Logger(doc); } return doc; } if (obj.type == "newnote" || obj.type == "plain") { try { if (dump) { Logger(`Enhanced doc`); Logger(obj); } let children2 = []; if (this.settings.readChunksOnline) { const items = await this.CollectChunks(obj.children); if (items) { for (const v of items) { if (v && v.type == "leaf") { children2.push(v.data); } else { if (!opt) { Logger(`Chunks of ${obj._id} are not valid.`, LOG_LEVEL.NOTICE); this.needScanning = true; this.corruptedEntries[obj._id] = obj; } return false; } } } else { if (opt) { Logger(`Could not retrieve chunks of ${obj._id}. we have to `, LOG_LEVEL.NOTICE); this.needScanning = true; } return false; } } else { try { children2 = await Promise.all(obj.children.map((e3) => this.getDBLeaf(e3, waitForReady))); if (dump) { Logger(`Chunks:`); Logger(children2); } } catch (ex) { Logger(`Something went wrong on reading chunks of ${obj._id} from database, see verbose info for detail.`, LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.VERBOSE); this.corruptedEntries[obj._id] = obj; return false; } } const data = children2.join(""); const doc = { data, _id: obj._id, ctime: obj.ctime, mtime: obj.mtime, size: obj.size, _rev: obj._rev, children: obj.children, datatype: obj.type, _conflicts: obj._conflicts, deleted, type: obj.type }; if (dump) { Logger(`therefore:`); Logger(doc); } if (typeof this.corruptedEntries[doc._id] != "undefined") { delete this.corruptedEntries[doc._id]; } return doc; } catch (ex) { if (ex.status && ex.status == 404) { Logger(`Missing document content!, could not read ${obj._id} from database.`, LOG_LEVEL.NOTICE); return false; } Logger(`Something went wrong on reading ${obj._id} from database:`, LOG_LEVEL.NOTICE); Logger(ex); } } } catch (ex) { if (ex.status && ex.status == 404) { return false; } throw ex; } return false; } async deleteDBEntry(path, opt) { if (!this.isTargetFile(path)) { return false; } const id = this.path2id(path); try { let obj = null; return await runWithLock("file:" + id, false, async () => { if (opt) { obj = await this.localDatabase.get(id, opt); } else { obj = await this.localDatabase.get(id); } const revDeletion = opt && ("rev" in opt ? opt.rev : "") != ""; if (obj.type && obj.type == "leaf") { return false; } if (!obj.type || obj.type && obj.type == "notes") { obj._deleted = true; const r2 = await this.localDatabase.put(obj); Logger(`entry removed:${obj._id}-${r2.rev}`); if (typeof this.corruptedEntries[obj._id] != "undefined") { delete this.corruptedEntries[obj._id]; } return true; } if (obj.type == "newnote" || obj.type == "plain") { if (revDeletion) { obj._deleted = true; } else { obj.deleted = true; obj.mtime = Date.now(); if (this.settings.deleteMetadataOfDeletedFiles) { obj._deleted = true; } } const r2 = await this.localDatabase.put(obj); Logger(`entry removed:${obj._id}-${r2.rev}`); if (typeof this.corruptedEntries[obj._id] != "undefined") { delete this.corruptedEntries[obj._id]; } return true; } else { return false; } }); } catch (ex) { if (ex.status && ex.status == 404) { return false; } throw ex; } } async deleteDBEntryPrefix(prefixSrc) { let c = 0; let readCount = 0; const delDocs = []; const prefix = this.path2id(prefixSrc); do { const result = await this.localDatabase.allDocs({ include_docs: false, skip: c, limit: 100, conflicts: true }); readCount = result.rows.length; if (readCount > 0) { for (const v of result.rows) { if (v.id.startsWith(prefix) || v.id.startsWith("/" + prefix)) { if (this.isTargetFile(this.id2path(v.id))) delDocs.push(v.id); } else { if (!v.id.startsWith("h:")) { } } } } c += readCount; } while (readCount != 0); let deleteCount = 0; let notfound = 0; for (const v of delDocs) { try { await runWithLock("file:" + v, false, async () => { const item = await this.localDatabase.get(v); if (item.type == "newnote" || item.type == "plain") { item.deleted = true; if (this.settings.deleteMetadataOfDeletedFiles) { item._deleted = true; } item.mtime = Date.now(); } else { item._deleted = true; } await this.localDatabase.put(item); }); deleteCount++; } catch (ex) { if (ex.status && ex.status == 404) { notfound++; } else { throw ex; } } } Logger(`deleteDBEntryPrefix:deleted ${deleteCount} items, skipped ${notfound}`); return true; } async putDBEntry(note, saveAsBigChunk) { if (!this.isTargetFile(this.id2path(note._id))) { return; } const savedNotes = []; let processed = 0; let made = 0; let skipped = 0; const maxChunkSize = MAX_DOC_SIZE_BIN * Math.max(this.settings.customChunkSize, 1); let pieceSize = maxChunkSize; let plainSplit = false; let cacheUsed = 0; const userPasswordHash = this.h32Raw(new TextEncoder().encode(this.settings.passphrase)); const minimumChunkSize = this.settings.minimumChunkSize; if (!saveAsBigChunk && shouldSplitAsPlainText(note._id)) { pieceSize = MAX_DOC_SIZE; plainSplit = true; } const newLeafs = []; const pieces = splitPieces2(note.data, pieceSize, plainSplit, minimumChunkSize, 0); for (const piece of pieces()) { processed++; let leafId = ""; let hashedPiece = ""; let hashQ = 0; let tryNextHash = false; let needMake = true; const cache = this.hashCaches.get(piece); if (cache) { hashedPiece = ""; leafId = cache; needMake = false; skipped++; cacheUsed++; } else { if (this.settings.encrypt) { hashedPiece = "+" + (this.h32Raw(new TextEncoder().encode(piece)) ^ userPasswordHash).toString(16); } else { hashedPiece = this.h32(piece); } leafId = "h:" + hashedPiece; do { let newLeafId = leafId; try { newLeafId = `${leafId}${hashQ}`; const pieceData = await this.localDatabase.get(newLeafId); if (pieceData.type == "leaf" && pieceData.data == piece) { leafId = newLeafId; needMake = false; tryNextHash = false; this.hashCaches.set(piece, leafId); } else if (pieceData.type == "leaf") { Logger("hash:collision!!"); hashQ++; tryNextHash = true; } else { leafId = newLeafId; tryNextHash = false; } } catch (ex) { if (ex.status && ex.status == 404) { leafId = newLeafId; needMake = true; tryNextHash = false; } else { needMake = false; tryNextHash = false; throw ex; } } } while (tryNextHash); if (needMake) { const savePiece = piece; const d = { _id: leafId, data: savePiece, type: "leaf" }; newLeafs.push(d); this.hashCaches.set(piece, leafId); made++; } else { skipped++; } } savedNotes.push(leafId); } let saved = true; if (newLeafs.length > 0) { try { const result = await this.localDatabase.bulkDocs(newLeafs); for (const item of result) { if (!item.ok) { if (item.status && item.status == 409) { } else { Logger(`Save failed:id:${item.id} rev:${item.rev}`, LOG_LEVEL.NOTICE); Logger(item); saved = false; } } } } catch (ex) { Logger("Chunk save failed:", LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.NOTICE); saved = false; } } if (saved) { Logger(`Content saved:${note._id} ,pieces:${processed} (new:${made}, skip:${skipped}, cache:${cacheUsed})`); const newDoc = { children: savedNotes, _id: note._id, ctime: note.ctime, mtime: note.mtime, size: note.size, type: note.datatype }; await runWithLock("file:" + newDoc._id, false, async () => { try { const old = await this.localDatabase.get(newDoc._id); if (!old.type || old.type == "notes" || old.type == "newnote" || old.type == "plain") { newDoc._rev = old._rev; } } catch (ex) { if (ex.status && ex.status == 404) { } else { throw ex; } } const r2 = await this.localDatabase.put(newDoc, { force: true }); if (typeof this.corruptedEntries[note._id] != "undefined") { delete this.corruptedEntries[note._id]; } }); } else { Logger(`note could not saved:${note._id}`); } } async migrate(from, to) { Logger(`Database updated from ${from} to ${to}`, LOG_LEVEL.NOTICE); return true; } replicateAllToServer(setting, showingNotice) { return new Promise((res, rej) => { this.openOneshotReplication(setting, showingNotice, async (e3) => { }, false, (e3) => { if (e3 === true) res(e3); rej(e3); }, "pushOnly"); }); } async checkReplicationConnectivity(setting, keepAlive, skipCheck, showResult) { if (!this.isReady) { Logger("Database is not ready."); return false; } if (setting.versionUpFlash != "") { Logger("Open settings and check message, please.", LOG_LEVEL.NOTICE); return false; } const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); if (this.syncHandler != null) { Logger("Another replication running."); return false; } const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbRet === "string") { Logger(`could not connect to ${uri}: ${dbRet}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); return false; } if (!skipCheck) { await putDesignDocuments(dbRet.db); if (!await checkRemoteVersion(dbRet.db, this.migrate.bind(this), VER)) { Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE); return false; } const defMilestonePoint = { _id: MILSTONE_DOCID, type: "milestoneinfo", created: new Date() / 1, locked: false, accepted_nodes: [this.nodeid], node_chunk_info: { [this.nodeid]: currentVersionRange } }; const remoteMilestone = { ...defMilestonePoint, ...await resolveWithIgnoreKnownError(dbRet.db.get(MILSTONE_DOCID), defMilestonePoint) }; remoteMilestone.node_chunk_info = { ...defMilestonePoint.node_chunk_info, ...remoteMilestone.node_chunk_info }; this.remoteLocked = remoteMilestone.locked; this.remoteLockedAndDeviceNotAccepted = remoteMilestone.locked && remoteMilestone.accepted_nodes.indexOf(this.nodeid) == -1; const writeMilestone = remoteMilestone.node_chunk_info[this.nodeid].min != currentVersionRange.min || remoteMilestone.node_chunk_info[this.nodeid].max != currentVersionRange.max || typeof remoteMilestone._rev == "undefined"; if (writeMilestone) { remoteMilestone.node_chunk_info[this.nodeid].min = currentVersionRange.min; remoteMilestone.node_chunk_info[this.nodeid].max = currentVersionRange.max; await dbRet.db.put(remoteMilestone); } let globalMin = currentVersionRange.min; let globalMax = currentVersionRange.max; for (const nodeid of remoteMilestone.accepted_nodes) { if (nodeid == this.nodeid) continue; if (nodeid in remoteMilestone.node_chunk_info) { const nodeinfo = remoteMilestone.node_chunk_info[nodeid]; globalMin = Math.max(nodeinfo.min, globalMin); globalMax = Math.min(nodeinfo.max, globalMax); } else { globalMin = 0; globalMax = 0; } } this.maxChunkVersion = globalMax; this.minChunkVersion = globalMin; if (this.chunkVersion >= 0 && (globalMin > this.chunkVersion || globalMax < this.chunkVersion)) { if (!setting.ignoreVersionCheck) { Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", LOG_LEVEL.NOTICE); return false; } } if (remoteMilestone.locked && remoteMilestone.accepted_nodes.indexOf(this.nodeid) == -1) { Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB or explicit unlocking is required. See the settings dialog.", LOG_LEVEL.NOTICE); return false; } } const syncOptionBase = { batches_limit: setting.batches_limit, batch_size: setting.batch_size }; if (setting.readChunksOnline) { syncOptionBase.push = { filter: "replicate/push" }; syncOptionBase.pull = { filter: "replicate/pull" }; } const syncOption = keepAlive ? { live: true, retry: true, heartbeat: 3e4, ...syncOptionBase } : { ...syncOptionBase }; return { db: dbRet.db, info: dbRet.info, syncOptionBase, syncOption }; } openReplication(setting, keepAlive, showResult, callback) { if (keepAlive) { this.openContinuousReplication(setting, showResult, callback, false); } else { this.openOneshotReplication(setting, showResult, callback, false, null, "sync"); } } replicationActivated(showResult) { this.syncStatus = "CONNECTED"; this.updateInfo(); Logger("Replication activated", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); } async replicationChangeDetected(e3, showResult, docSentOnStart, docArrivedOnStart, callback) { try { if (e3.direction == "pull") { await callback(e3.change.docs); this.docArrived += e3.change.docs.length; } else { this.docSent += e3.change.docs.length; } if (showResult) { Logger(`\u2191${this.docSent - docSentOnStart} \u2193${this.docArrived - docArrivedOnStart}`, LOG_LEVEL.NOTICE, "sync"); } this.updateInfo(); } catch (ex) { Logger("Replication callback error", LOG_LEVEL.NOTICE, "sync"); Logger(ex, LOG_LEVEL.NOTICE); } } replicationCompleted(showResult) { this.syncStatus = "COMPLETED"; this.updateInfo(); Logger("Replication completed", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, showResult ? "sync" : ""); this.syncHandler = this.cancelHandler(this.syncHandler); } replicationDenied(e3) { this.syncStatus = "ERRORED"; this.updateInfo(); this.syncHandler = this.cancelHandler(this.syncHandler); Logger("Replication denied", LOG_LEVEL.NOTICE, "sync"); Logger(e3); } replicationErrored(e3) { this.syncStatus = "ERRORED"; this.syncHandler = this.cancelHandler(this.syncHandler); this.updateInfo(); Logger("Replication error", LOG_LEVEL.NOTICE, "sync"); Logger(e3); } replicationPaused() { this.syncStatus = "PAUSED"; this.updateInfo(); Logger("replication paused", LOG_LEVEL.VERBOSE, "sync"); } async openOneshotReplication(setting, showResult, callback, retrying, callbackDone, syncMode) { if (this.syncHandler != null) { Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); return; } Logger(`Oneshot Sync begin... (${syncMode})`); let thisCallback = callbackDone; const ret = await this.checkReplicationConnectivity(setting, true, retrying, showResult); if (ret === false) { Logger("Could not connect to server.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); return; } if (showResult) { Logger("Looking for the point last synchronized point.", LOG_LEVEL.NOTICE, "sync"); } const { db, syncOptionBase } = ret; this.syncStatus = "STARTED"; this.updateInfo(); const docArrivedOnStart = this.docArrived; const docSentOnStart = this.docSent; if (!retrying) { this.originalSetting = setting; } this.syncHandler = this.cancelHandler(this.syncHandler); if (syncMode == "sync") { this.syncHandler = this.localDatabase.sync(db, { checkpoint: "target", ...syncOptionBase }); this.syncHandler.on("change", async (e3) => { await this.replicationChangeDetected(e3, showResult, docSentOnStart, docArrivedOnStart, callback); if (retrying) { if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) { Logger("Back into original settings once."); this.syncHandler = this.cancelHandler(this.syncHandler); this.openOneshotReplication(this.originalSetting, showResult, callback, false, callbackDone, syncMode); } } }).on("complete", (e3) => { this.replicationCompleted(showResult); if (thisCallback != null) { thisCallback(true); } }); } else if (syncMode == "pullOnly") { this.syncHandler = this.localDatabase.replicate.from(db, { checkpoint: "target", ...syncOptionBase, ...this.settings.readChunksOnline ? { filter: "replicate/pull" } : {} }); this.syncHandler.on("change", async (e3) => { await this.replicationChangeDetected({ direction: "pull", change: e3 }, showResult, docSentOnStart, docArrivedOnStart, callback); if (retrying) { if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) { Logger("Back into original settings once."); this.syncHandler = this.cancelHandler(this.syncHandler); this.openOneshotReplication(this.originalSetting, showResult, callback, false, callbackDone, syncMode); } } }).on("complete", (e3) => { this.replicationCompleted(showResult); if (thisCallback != null) { thisCallback(true); } }); } else if (syncMode == "pushOnly") { this.syncHandler = this.localDatabase.replicate.to(db, { checkpoint: "target", ...syncOptionBase, ...this.settings.readChunksOnline ? { filter: "replicate/push" } : {} }); this.syncHandler.on("change", async (e3) => { await this.replicationChangeDetected({ direction: "push", change: e3 }, showResult, docSentOnStart, docArrivedOnStart, callback); if (retrying) { if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) { Logger("Back into original settings once."); this.syncHandler = this.cancelHandler(this.syncHandler); this.openOneshotReplication(this.originalSetting, showResult, callback, false, callbackDone, syncMode); } } }); this.syncHandler.on("complete", (e3) => { this.replicationCompleted(showResult); if (thisCallback != null) { thisCallback(true); } }); } this.syncHandler.on("active", () => this.replicationActivated(showResult)).on("denied", (e3) => { this.replicationDenied(e3); if (thisCallback != null) { thisCallback(e3); } }).on("error", (e3) => { this.replicationErrored(e3); Logger("Replication stopped.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); if (this.getLastPostFailedBySize()) { if ("status" in e3 && e3.status == 413) { Logger(`Self-hosted LiveSync has detected some remote-database-incompatible chunks that exist in the local database. It means synchronization with the server had been no longer possible. The problem may be caused by chunks that were created with the faulty version or by switching platforms of the database. To solve the circumstance, configure the remote database correctly or we have to rebuild both local and remote databases.`, LOG_LEVEL.NOTICE); return; } const tempSetting = JSON.parse(JSON.stringify(setting)); tempSetting.batch_size = Math.ceil(tempSetting.batch_size / 2) + 2; tempSetting.batches_limit = Math.ceil(tempSetting.batches_limit / 2) + 2; if (tempSetting.batch_size <= 5 && tempSetting.batches_limit <= 5) { Logger("We can't replicate more lower value.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); } else { Logger(`Retry with lower batch size:${tempSetting.batch_size}/${tempSetting.batches_limit}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); thisCallback = null; this.openOneshotReplication(tempSetting, showResult, callback, true, callbackDone, syncMode); } } else { Logger("Replication error", LOG_LEVEL.NOTICE, "sync"); Logger(e3); } if (thisCallback != null) { thisCallback(e3); } }).on("paused", (e3) => this.replicationPaused()); await this.syncHandler; } openContinuousReplication(setting, showResult, callback, retrying) { if (this.syncHandler != null) { Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); return; } Logger("Before LiveSync, start OneShot once..."); this.openOneshotReplication(setting, showResult, callback, false, async () => { Logger("LiveSync begin..."); const ret = await this.checkReplicationConnectivity(setting, true, true, showResult); if (ret === false) { Logger("Could not connect to server.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); return; } if (showResult) { Logger("Looking for the point last synchronized point.", LOG_LEVEL.NOTICE, "sync"); } const { db, syncOption } = ret; this.syncStatus = "STARTED"; this.updateInfo(); const docArrivedOnStart = this.docArrived; const docSentOnStart = this.docSent; if (!retrying) { this.originalSetting = setting; } this.syncHandler = this.cancelHandler(this.syncHandler); this.syncHandler = this.localDatabase.sync(db, { ...syncOption, pull: { checkpoint: "target" }, push: { checkpoint: "source" } }); this.syncHandler.on("active", () => this.replicationActivated(showResult)).on("change", async (e3) => { await this.replicationChangeDetected(e3, showResult, docSentOnStart, docArrivedOnStart, callback); if (retrying) { if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) { Logger("Back into original settings once."); this.syncHandler = this.cancelHandler(this.syncHandler); this.openContinuousReplication(this.originalSetting, showResult, callback, false); } } }).on("complete", (e3) => this.replicationCompleted(showResult)).on("denied", (e3) => this.replicationDenied(e3)).on("error", (e3) => { this.replicationErrored(e3); Logger("Replication stopped.", LOG_LEVEL.NOTICE, "sync"); }).on("paused", (e3) => this.replicationPaused()); }, "pullOnly"); } closeReplication() { this.syncStatus = "CLOSED"; this.updateInfo(); this.syncHandler = this.cancelHandler(this.syncHandler); Logger("Replication closed"); } async resetLocalOldDatabase() { const oldDB = await this.isOldDatabaseExists(); if (oldDB) { oldDB.destroy(); Logger("Deleted!", LOG_LEVEL.NOTICE); } else { Logger("Old database is not exist.", LOG_LEVEL.NOTICE); } } async resetDatabase() { this.changeHandler = this.cancelHandler(this.changeHandler); this.closeReplication(); Logger("Database closed for reset Database."); this.isReady = false; await this.localDatabase.destroy(); this.onResetDatabase(); this.localDatabase = null; await this.initializeDatabase(); Logger("Local Database Reset", LOG_LEVEL.NOTICE); } async tryResetRemoteDatabase(setting) { this.closeReplication(); const con = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof con == "string") return; try { await con.db.destroy(); Logger("Remote Database Destroyed", LOG_LEVEL.NOTICE); await this.tryCreateRemoteDatabase(setting); } catch (ex) { Logger("Something happened on Remote Database Destroy:", LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.NOTICE); } } async tryCreateRemoteDatabase(setting) { this.closeReplication(); const con2 = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof con2 === "string") return; Logger("Remote Database Created or Connected", LOG_LEVEL.NOTICE); } async markRemoteLocked(setting, locked) { const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbRet === "string") { Logger(`could not connect to ${uri}:${dbRet}`, LOG_LEVEL.NOTICE); return; } if (!await checkRemoteVersion(dbRet.db, this.migrate.bind(this), VER)) { Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE); return; } const defInitPoint = { _id: MILSTONE_DOCID, type: "milestoneinfo", created: new Date() / 1, locked, accepted_nodes: [this.nodeid], node_chunk_info: { [this.nodeid]: currentVersionRange } }; const remoteMilestone = { ...defInitPoint, ...await resolveWithIgnoreKnownError(dbRet.db.get(MILSTONE_DOCID), defInitPoint) }; remoteMilestone.node_chunk_info = { ...defInitPoint.node_chunk_info, ...remoteMilestone.node_chunk_info }; remoteMilestone.accepted_nodes = [this.nodeid]; remoteMilestone.locked = locked; if (locked) { Logger("Lock remote database to prevent data corruption", LOG_LEVEL.NOTICE); } else { Logger("Unlock remote database to prevent data corruption", LOG_LEVEL.NOTICE); } await dbRet.db.put(remoteMilestone); } async markRemoteResolved(setting) { const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbRet === "string") { Logger(`could not connect to ${uri}:${dbRet}`, LOG_LEVEL.NOTICE); return; } if (!await checkRemoteVersion(dbRet.db, this.migrate.bind(this), VER)) { Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE); return; } const defInitPoint = { _id: MILSTONE_DOCID, type: "milestoneinfo", created: new Date() / 1, locked: false, accepted_nodes: [this.nodeid], node_chunk_info: { [this.nodeid]: currentVersionRange } }; const remoteMilestone = { ...defInitPoint, ...await resolveWithIgnoreKnownError(dbRet.db.get(MILSTONE_DOCID), defInitPoint) }; remoteMilestone.node_chunk_info = { ...defInitPoint.node_chunk_info, ...remoteMilestone.node_chunk_info }; remoteMilestone.accepted_nodes = Array.from(new Set([...remoteMilestone.accepted_nodes, this.nodeid])); Logger("Mark this device as 'resolved'.", LOG_LEVEL.NOTICE); await dbRet.db.put(remoteMilestone); } async sanCheck(entry) { if (entry.type == "plain" || entry.type == "newnote") { const children2 = entry.children; Logger(`sancheck:checking:${entry._id} : ${children2.length}`, LOG_LEVEL.VERBOSE); try { const dc = await this.localDatabase.allDocs({ keys: [...children2] }); if (dc.rows.some((e3) => "error" in e3)) { this.corruptedEntries[entry._id] = entry; Logger(`sancheck:corrupted:${entry._id} : ${children2.length}`, LOG_LEVEL.VERBOSE); return false; } return true; } catch (ex) { Logger(ex); } } return false; } isVersionUpgradable(ver) { if (this.maxChunkVersion < 0) return false; if (this.minChunkVersion < 0) return false; if (this.maxChunkVersion > 0 && this.maxChunkVersion < ver) return false; if (this.minChunkVersion > 0 && this.minChunkVersion > ver) return false; return true; } isTargetFile(file) { if (file.includes(":")) return true; if (this.settings.syncOnlyRegEx) { const syncOnly = new RegExp(this.settings.syncOnlyRegEx); if (!file.match(syncOnly)) return false; } if (this.settings.syncIgnoreRegEx) { const syncIgnore = new RegExp(this.settings.syncIgnoreRegEx); if (file.match(syncIgnore)) return false; } return true; } chunkCollected(chunk) { const id = chunk._id; if (typeof this.chunkCollectedCallbacks[id] !== "undefined") { for (const func of this.chunkCollectedCallbacks[id]) { func(chunk); } delete this.chunkCollectedCallbacks[id]; } else { Logger(`Collected handler of ${id} is missing, it might be error but perhaps it already timed out.`, LOG_LEVEL.VERBOSE); } } async CollectChunks(ids, showResult = false) { const timeoutLimit = 333; if (this.collectThrottleTimeout == null) { this.collectThrottleTimeout = setTimeout(async () => { this.collectThrottleTimeout = null; await this.execCollect(); }, timeoutLimit); return this.CollectChunksInternal(ids, showResult); } this.collectThrottleQueuedIds = [...new Set([...this.collectThrottleQueuedIds, ...ids])]; if (this.collectThrottleQueuedIds.length > 50) { clearTimeout(this.collectThrottleTimeout); this.collectThrottleTimeout = setTimeout(async () => { this.collectThrottleTimeout = null; await this.execCollect(); }, timeoutLimit); } const promises = ids.map((id) => new Promise((res2, rej) => { const timer = setTimeout(() => rej(new Error(`Chunk reading timed out on batch:${id}`)), LEAF_WAIT_TIMEOUT); if (typeof this.chunkCollectedCallbacks[id] == "undefined") { this.chunkCollectedCallbacks[id] = []; } this.chunkCollectedCallbacks[id].push((chunk) => { clearTimeout(timer); res2(chunk); }); })); const res = await Promise.all(promises); return res; } async execCollect() { const requesting = [...this.collectThrottleQueuedIds]; this.collectThrottleQueuedIds = []; const chunks = await this.CollectChunksInternal(requesting, false); if (!chunks) { Logger(`Could not retrieve chunks`, LOG_LEVEL.NOTICE); return; } for (const chunk of chunks) { this.chunkCollected(chunk); } } async CollectChunksInternal(ids, showResult = false) { const localChunks = await this.localDatabase.allDocs({ keys: ids, include_docs: true }); const missingChunks = localChunks.rows.filter((e3) => "error" in e3).map((e3) => e3.key); if (missingChunks.length == 0) { return localChunks.rows.map((e3) => e3.doc); } const ret = await this.connectRemoteCouchDBWithSetting(this.settings, this.isMobile); if (typeof ret === "string") { Logger(`Could not connect to server.${ret} `, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "fetch"); return false; } const remoteChunks = await ret.db.allDocs({ keys: missingChunks, include_docs: true }); if (remoteChunks.rows.some((e3) => "error" in e3)) { return false; } const remoteChunkItems = remoteChunks.rows.map((e3) => e3.doc); const max = remoteChunkItems.length; let last = 0; function findChunk(key) { const offset = last; for (let i2 = 0; i2 < max; i2++) { const idx = (offset + i2) % max; last = i2; if (remoteChunkItems[idx]._id == key) return remoteChunkItems[idx]; } throw Error("Chunk collecting error"); } return localChunks.rows.map((e3) => "error" in e3 ? findChunk(e3.key) : e3.doc); } connectRemoteCouchDBWithSetting(settings, isMobile) { return this.connectRemoteCouchDB(settings.couchDB_URI + (settings.couchDB_DBNAME == "" ? "" : "/" + settings.couchDB_DBNAME), { username: settings.couchDB_USER, password: settings.couchDB_PASSWORD }, settings.disableRequestURI || isMobile, settings.encrypt ? settings.passphrase : settings.encrypt); } }; // src/lib/pouchdb-browser-webpack/dist/pouchdb-browser.js var e2 = { 105: (e3) => { e3.exports = function(e4) { return function() { var t3 = arguments.length; if (t3) { for (var n3 = [], r2 = -1; ++r2 < t3; ) n3[r2] = arguments[r2]; return e4.call(this, n3); } return e4.call(this, []); }; }; }, 187: (e3) => { var t3, n3 = typeof Reflect == "object" ? Reflect : null, r2 = n3 && typeof n3.apply == "function" ? n3.apply : function(e4, t4, n4) { return Function.prototype.apply.call(e4, t4, n4); }; t3 = n3 && typeof n3.ownKeys == "function" ? n3.ownKeys : Object.getOwnPropertySymbols ? function(e4) { return Object.getOwnPropertyNames(e4).concat(Object.getOwnPropertySymbols(e4)); } : function(e4) { return Object.getOwnPropertyNames(e4); }; var i2 = Number.isNaN || function(e4) { return e4 != e4; }; function o() { o.init.call(this); } e3.exports = o, e3.exports.once = function(e4, t4) { return new Promise(function(n4, r3) { function i3(n5) { e4.removeListener(t4, o2), r3(n5); } function o2() { typeof e4.removeListener == "function" && e4.removeListener("error", i3), n4([].slice.call(arguments)); } v(e4, t4, o2, { once: true }), t4 !== "error" && function(e5, t5, n5) { typeof e5.on == "function" && v(e5, "error", t5, { once: true }); }(e4, i3); }); }, o.EventEmitter = o, o.prototype._events = void 0, o.prototype._eventsCount = 0, o.prototype._maxListeners = void 0; var s = 10; function a(e4) { if (typeof e4 != "function") throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e4); } function u(e4) { return e4._maxListeners === void 0 ? o.defaultMaxListeners : e4._maxListeners; } function c(e4, t4, n4, r3) { var i3, o2, s2, c2; if (a(n4), (o2 = e4._events) === void 0 ? (o2 = e4._events = Object.create(null), e4._eventsCount = 0) : (o2.newListener !== void 0 && (e4.emit("newListener", t4, n4.listener ? n4.listener : n4), o2 = e4._events), s2 = o2[t4]), s2 === void 0) s2 = o2[t4] = n4, ++e4._eventsCount; else if (typeof s2 == "function" ? s2 = o2[t4] = r3 ? [n4, s2] : [s2, n4] : r3 ? s2.unshift(n4) : s2.push(n4), (i3 = u(e4)) > 0 && s2.length > i3 && !s2.warned) { s2.warned = true; var f2 = new Error("Possible EventEmitter memory leak detected. " + s2.length + " " + String(t4) + " listeners added. Use emitter.setMaxListeners() to increase limit"); f2.name = "MaxListenersExceededWarning", f2.emitter = e4, f2.type = t4, f2.count = s2.length, c2 = f2, console && console.warn && console.warn(c2); } return e4; } function f() { if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), this.fired = true, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); } function l(e4, t4, n4) { var r3 = { fired: false, wrapFn: void 0, target: e4, type: t4, listener: n4 }, i3 = f.bind(r3); return i3.listener = n4, r3.wrapFn = i3, i3; } function d(e4, t4, n4) { var r3 = e4._events; if (r3 === void 0) return []; var i3 = r3[t4]; return i3 === void 0 ? [] : typeof i3 == "function" ? n4 ? [i3.listener || i3] : [i3] : n4 ? function(e5) { for (var t5 = new Array(e5.length), n5 = 0; n5 < t5.length; ++n5) t5[n5] = e5[n5].listener || e5[n5]; return t5; }(i3) : p(i3, i3.length); } function h(e4) { var t4 = this._events; if (t4 !== void 0) { var n4 = t4[e4]; if (typeof n4 == "function") return 1; if (n4 !== void 0) return n4.length; } return 0; } function p(e4, t4) { for (var n4 = new Array(t4), r3 = 0; r3 < t4; ++r3) n4[r3] = e4[r3]; return n4; } function v(e4, t4, n4, r3) { if (typeof e4.on == "function") r3.once ? e4.once(t4, n4) : e4.on(t4, n4); else { if (typeof e4.addEventListener != "function") throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e4); e4.addEventListener(t4, function i3(o2) { r3.once && e4.removeEventListener(t4, i3), n4(o2); }); } } Object.defineProperty(o, "defaultMaxListeners", { enumerable: true, get: function() { return s; }, set: function(e4) { if (typeof e4 != "number" || e4 < 0 || i2(e4)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e4 + "."); s = e4; } }), o.init = function() { this._events !== void 0 && this._events !== Object.getPrototypeOf(this)._events || (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0; }, o.prototype.setMaxListeners = function(e4) { if (typeof e4 != "number" || e4 < 0 || i2(e4)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e4 + "."); return this._maxListeners = e4, this; }, o.prototype.getMaxListeners = function() { return u(this); }, o.prototype.emit = function(e4) { for (var t4 = [], n4 = 1; n4 < arguments.length; n4++) t4.push(arguments[n4]); var i3 = e4 === "error", o2 = this._events; if (o2 !== void 0) i3 = i3 && o2.error === void 0; else if (!i3) return false; if (i3) { var s2; if (t4.length > 0 && (s2 = t4[0]), s2 instanceof Error) throw s2; var a2 = new Error("Unhandled error." + (s2 ? " (" + s2.message + ")" : "")); throw a2.context = s2, a2; } var u2 = o2[e4]; if (u2 === void 0) return false; if (typeof u2 == "function") r2(u2, this, t4); else { var c2 = u2.length, f2 = p(u2, c2); for (n4 = 0; n4 < c2; ++n4) r2(f2[n4], this, t4); } return true; }, o.prototype.addListener = function(e4, t4) { return c(this, e4, t4, false); }, o.prototype.on = o.prototype.addListener, o.prototype.prependListener = function(e4, t4) { return c(this, e4, t4, true); }, o.prototype.once = function(e4, t4) { return a(t4), this.on(e4, l(this, e4, t4)), this; }, o.prototype.prependOnceListener = function(e4, t4) { return a(t4), this.prependListener(e4, l(this, e4, t4)), this; }, o.prototype.removeListener = function(e4, t4) { var n4, r3, i3, o2, s2; if (a(t4), (r3 = this._events) === void 0) return this; if ((n4 = r3[e4]) === void 0) return this; if (n4 === t4 || n4.listener === t4) --this._eventsCount == 0 ? this._events = Object.create(null) : (delete r3[e4], r3.removeListener && this.emit("removeListener", e4, n4.listener || t4)); else if (typeof n4 != "function") { for (i3 = -1, o2 = n4.length - 1; o2 >= 0; o2--) if (n4[o2] === t4 || n4[o2].listener === t4) { s2 = n4[o2].listener, i3 = o2; break; } if (i3 < 0) return this; i3 === 0 ? n4.shift() : function(e5, t5) { for (; t5 + 1 < e5.length; t5++) e5[t5] = e5[t5 + 1]; e5.pop(); }(n4, i3), n4.length === 1 && (r3[e4] = n4[0]), r3.removeListener !== void 0 && this.emit("removeListener", e4, s2 || t4); } return this; }, o.prototype.off = o.prototype.removeListener, o.prototype.removeAllListeners = function(e4) { var t4, n4, r3; if ((n4 = this._events) === void 0) return this; if (n4.removeListener === void 0) return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : n4[e4] !== void 0 && (--this._eventsCount == 0 ? this._events = Object.create(null) : delete n4[e4]), this; if (arguments.length === 0) { var i3, o2 = Object.keys(n4); for (r3 = 0; r3 < o2.length; ++r3) (i3 = o2[r3]) !== "removeListener" && this.removeAllListeners(i3); return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this; } if (typeof (t4 = n4[e4]) == "function") this.removeListener(e4, t4); else if (t4 !== void 0) for (r3 = t4.length - 1; r3 >= 0; r3--) this.removeListener(e4, t4[r3]); return this; }, o.prototype.listeners = function(e4) { return d(this, e4, true); }, o.prototype.rawListeners = function(e4) { return d(this, e4, false); }, o.listenerCount = function(e4, t4) { return typeof e4.listenerCount == "function" ? e4.listenerCount(t4) : h.call(e4, t4); }, o.prototype.listenerCount = h, o.prototype.eventNames = function() { return this._eventsCount > 0 ? t3(this._events) : []; }; }, 624: (e3, t3, n3) => { var r2, i2, o, s = [n3(525), n3(785), n3(291), n3(709), n3(506), n3(176)], a = -1, u = [], c = false; function f() { r2 && i2 && (r2 = false, i2.length ? u = i2.concat(u) : a = -1, u.length && l()); } function l() { if (!r2) { c = false, r2 = true; for (var e4 = u.length, t4 = setTimeout(f); e4; ) { for (i2 = u, u = []; i2 && ++a < e4; ) i2[a].run(); a = -1, e4 = u.length; } i2 = null, a = -1, r2 = false, clearTimeout(t4); } } for (var d = -1, h = s.length; ++d < h; ) if (s[d] && s[d].test && s[d].test()) { o = s[d].install(l); break; } function p(e4, t4) { this.fun = e4, this.array = t4; } p.prototype.run = function() { var e4 = this.fun, t4 = this.array; switch (t4.length) { case 0: return e4(); case 1: return e4(t4[0]); case 2: return e4(t4[0], t4[1]); case 3: return e4(t4[0], t4[1], t4[2]); default: return e4.apply(null, t4); } }, e3.exports = function(e4) { var t4 = new Array(arguments.length - 1); if (arguments.length > 1) for (var n4 = 1; n4 < arguments.length; n4++) t4[n4 - 1] = arguments[n4]; u.push(new p(e4, t4)), c || r2 || (c = true, o()); }; }, 709: (e3, t3, n3) => { t3.test = function() { return !n3.g.setImmediate && n3.g.MessageChannel !== void 0; }, t3.install = function(e4) { var t4 = new n3.g.MessageChannel(); return t4.port1.onmessage = e4, function() { t4.port2.postMessage(0); }; }; }, 291: (e3, t3, n3) => { var r2 = n3.g.MutationObserver || n3.g.WebKitMutationObserver; t3.test = function() { return r2; }, t3.install = function(e4) { var t4 = 0, i2 = new r2(e4), o = n3.g.document.createTextNode(""); return i2.observe(o, { characterData: true }), function() { o.data = t4 = ++t4 % 2; }; }; }, 785: (e3, t3, n3) => { t3.test = function() { return typeof n3.g.queueMicrotask == "function"; }, t3.install = function(e4) { return function() { n3.g.queueMicrotask(e4); }; }; }, 506: (e3, t3, n3) => { t3.test = function() { return "document" in n3.g && "onreadystatechange" in n3.g.document.createElement("script"); }, t3.install = function(e4) { return function() { var t4 = n3.g.document.createElement("script"); return t4.onreadystatechange = function() { e4(), t4.onreadystatechange = null, t4.parentNode.removeChild(t4), t4 = null; }, n3.g.document.documentElement.appendChild(t4), e4; }; }; }, 176: (e3, t3) => { t3.test = function() { return true; }, t3.install = function(e4) { return function() { setTimeout(e4, 0); }; }; }, 717: (e3) => { typeof Object.create == "function" ? e3.exports = function(e4, t3) { t3 && (e4.super_ = t3, e4.prototype = Object.create(t3.prototype, { constructor: { value: e4, enumerable: false, writable: true, configurable: true } })); } : e3.exports = function(e4, t3) { if (t3) { e4.super_ = t3; var n3 = function() { }; n3.prototype = t3.prototype, e4.prototype = new n3(), e4.prototype.constructor = e4; } }; }, 198: (e3, t3, n3) => { n3.d(t3, { Z: () => fr }); var r2, i2, o = n3(624), s = n3.n(o), a = n3(586), u = n3(322), c = n3.n(u), f = n3(684), l = n3(105), d = n3.n(l), h = n3(717), p = n3.n(h), v = n3(187), y = n3.n(v); function g(e4) { return "$" + e4; } function _(e4) { return e4.substring(1); } function m() { this._store = {}; } function b(e4) { if (this._store = new m(), e4 && Array.isArray(e4)) for (var t4 = 0, n4 = e4.length; t4 < n4; t4++) this.add(e4[t4]); } m.prototype.get = function(e4) { var t4 = g(e4); return this._store[t4]; }, m.prototype.set = function(e4, t4) { var n4 = g(e4); return this._store[n4] = t4, true; }, m.prototype.has = function(e4) { return g(e4) in this._store; }, m.prototype.keys = function() { return Object.keys(this._store).map((e4) => _(e4)); }, m.prototype.delete = function(e4) { var t4 = g(e4), n4 = t4 in this._store; return delete this._store[t4], n4; }, m.prototype.forEach = function(e4) { for (var t4 = Object.keys(this._store), n4 = 0, r3 = t4.length; n4 < r3; n4++) { var i3 = t4[n4]; e4(this._store[i3], i3 = _(i3)); } }, Object.defineProperty(m.prototype, "size", { get: function() { return Object.keys(this._store).length; } }), b.prototype.add = function(e4) { return this._store.set(e4, true); }, b.prototype.has = function(e4) { return this._store.has(e4); }, b.prototype.forEach = function(e4) { this._store.forEach(function(t4, n4) { e4(n4); }); }, Object.defineProperty(b.prototype, "size", { get: function() { return this._store.size; } }), function() { if (typeof Symbol == "undefined" || typeof Map == "undefined" || typeof Set == "undefined") return false; var e4 = Object.getOwnPropertyDescriptor(Map, Symbol.species); return e4 && "get" in e4 && Map[Symbol.species] === Map; }() ? (r2 = Set, i2 = Map) : (r2 = b, i2 = m); var w, k = Function.prototype.toString, j = k.call(Object); function O(e4) { var t4, n4, r3; if (!e4 || typeof e4 != "object") return e4; if (Array.isArray(e4)) { for (t4 = [], n4 = 0, r3 = e4.length; n4 < r3; n4++) t4[n4] = O(e4[n4]); return t4; } if (e4 instanceof Date && isFinite(e4)) return e4.toISOString(); if (function(e5) { return typeof ArrayBuffer != "undefined" && e5 instanceof ArrayBuffer || typeof Blob != "undefined" && e5 instanceof Blob; }(e4)) return function(e5) { if (e5 instanceof ArrayBuffer) return function(e6) { if (typeof e6.slice == "function") return e6.slice(0); var t6 = new ArrayBuffer(e6.byteLength), n6 = new Uint8Array(t6), r4 = new Uint8Array(e6); return n6.set(r4), t6; }(e5); var t5 = e5.size, n5 = e5.type; return typeof e5.slice == "function" ? e5.slice(0, t5, n5) : e5.webkitSlice(0, t5, n5); }(e4); if (!function(e5) { var t5 = Object.getPrototypeOf(e5); if (t5 === null) return true; var n5 = t5.constructor; return typeof n5 == "function" && n5 instanceof n5 && k.call(n5) == j; }(e4)) return e4; for (n4 in t4 = {}, e4) if (Object.prototype.hasOwnProperty.call(e4, n4)) { var i3 = O(e4[n4]); i3 !== void 0 && (t4[n4] = i3); } return t4; } function $(e4) { var t4 = false; return d()(function(n4) { if (t4) throw new Error("once called more than once"); t4 = true, e4.apply(this, n4); }); } function x(e4) { return d()(function(t4) { t4 = O(t4); var n4 = this, r3 = typeof t4[t4.length - 1] == "function" && t4.pop(), i3 = new Promise(function(r4, i4) { var o2; try { var s2 = $(function(e5, t5) { e5 ? i4(e5) : r4(t5); }); t4.push(s2), (o2 = e4.apply(n4, t4)) && typeof o2.then == "function" && r4(o2); } catch (e5) { i4(e5); } }); return r3 && i3.then(function(e5) { r3(null, e5); }, r3), i3; }); } function q(e4, t4) { return x(d()(function(n4) { if (this._closed) return Promise.reject(new Error("database is closed")); if (this._destroyed) return Promise.reject(new Error("database is destroyed")); var r3 = this; return function(e5, t5, n5) { if (e5.constructor.listeners("debug").length) { for (var r4 = ["api", e5.name, t5], i3 = 0; i3 < n5.length - 1; i3++) r4.push(n5[i3]); e5.constructor.emit("debug", r4); var o2 = n5[n5.length - 1]; n5[n5.length - 1] = function(n6, r5) { var i4 = ["api", e5.name, t5]; i4 = i4.concat(n6 ? ["error", n6] : ["success", r5]), e5.constructor.emit("debug", i4), o2(n6, r5); }; } }(r3, e4, n4), this.taskqueue.isReady ? t4.apply(this, n4) : new Promise(function(t5, i3) { r3.taskqueue.addTask(function(o2) { o2 ? i3(o2) : t5(r3[e4].apply(r3, n4)); }); }); })); } function A(e4, t4) { for (var n4 = {}, r3 = 0, i3 = t4.length; r3 < i3; r3++) { var o2 = t4[r3]; o2 in e4 && (n4[o2] = e4[o2]); } return n4; } function S(e4) { return e4; } function E(e4) { return [{ ok: e4 }]; } function P(e4, t4, n4) { var r3 = t4.docs, o2 = new i2(); r3.forEach(function(e5) { o2.has(e5.id) ? o2.get(e5.id).push(e5) : o2.set(e5.id, [e5]); }); var s2 = o2.size, a2 = 0, u2 = new Array(s2); var c2 = []; o2.forEach(function(e5, t5) { c2.push(t5); }); var f2 = 0; !function r4() { if (!(f2 >= c2.length)) { var i3 = Math.min(f2 + 6, c2.length), l2 = c2.slice(f2, i3); !function(i4, c3) { i4.forEach(function(i5, f3) { var l3 = c3 + f3, d2 = o2.get(i5), h2 = A(d2[0], ["atts_since", "attachments"]); h2.open_revs = d2.map(function(e5) { return e5.rev; }), h2.open_revs = h2.open_revs.filter(S); var p2 = S; h2.open_revs.length === 0 && (delete h2.open_revs, p2 = E), ["revs", "attachments", "binary", "ajax", "latest"].forEach(function(e5) { e5 in t4 && (h2[e5] = t4[e5]); }), e4.get(i5, h2, function(e5, t5) { var o3, c4, f4, d3; o3 = e5 ? [{ error: e5 }] : p2(t5), c4 = i5, f4 = o3, u2[l3] = { id: c4, docs: f4 }, ++a2 === s2 && (d3 = [], u2.forEach(function(e6) { e6.docs.forEach(function(t6) { d3.push({ id: e6.id, docs: [t6] }); }); }), n4(null, { results: d3 })), r4(); }); }); }(l2, f2), f2 += l2.length; } }(); } try { localStorage.setItem("_pouch_check_localstorage", 1), w = !!localStorage.getItem("_pouch_check_localstorage"); } catch (e4) { w = false; } function C() { return w; } function D() { y().call(this), this._listeners = {}, function(e4) { C() && addEventListener("storage", function(t4) { e4.emit(t4.key); }); }(this); } function L(e4) { if (typeof console != "undefined" && typeof console[e4] == "function") { var t4 = Array.prototype.slice.call(arguments, 1); console[e4].apply(console, t4); } } function B(e4) { var t4 = 0; return e4 || (t4 = 2e3), function(e5, t5) { var n4 = 6e5; return e5 = parseInt(e5, 10) || 0, (t5 = parseInt(t5, 10)) != t5 || t5 <= e5 ? t5 = (e5 || 1) << 1 : t5 += 1, t5 > n4 && (e5 = 3e5, t5 = n4), ~~((t5 - e5) * Math.random() + e5); }(e4, t4); } function I(e4, t4) { L("info", "The above " + e4 + " is totally normal. " + t4); } p()(D, y()), D.prototype.addListener = function(e4, t4, n4, r3) { if (!this._listeners[t4]) { var i3 = this, o2 = false; this._listeners[t4] = a2, this.on(e4, a2); } function a2() { if (i3._listeners[t4]) if (o2) o2 = "waiting"; else { o2 = true; var e5 = A(r3, ["style", "include_docs", "attachments", "conflicts", "filter", "doc_ids", "view", "since", "query_params", "binary", "return_docs"]); n4.changes(e5).on("change", function(e6) { e6.seq > r3.since && !r3.cancelled && (r3.since = e6.seq, r3.onChange(e6)); }).on("complete", function() { o2 === "waiting" && s()(a2), o2 = false; }).on("error", function() { o2 = false; }); } } }, D.prototype.removeListener = function(e4, t4) { t4 in this._listeners && (y().prototype.removeListener.call(this, e4, this._listeners[t4]), delete this._listeners[t4]); }, D.prototype.notifyLocalWindows = function(e4) { C() && (localStorage[e4] = localStorage[e4] === "a" ? "b" : "a"); }, D.prototype.notify = function(e4) { this.emit(e4), this.notifyLocalWindows(e4); }; var T = typeof Object.assign == "function" ? Object.assign : function(e4) { for (var t4 = Object(e4), n4 = 1; n4 < arguments.length; n4++) { var r3 = arguments[n4]; if (r3 != null) for (var i3 in r3) Object.prototype.hasOwnProperty.call(r3, i3) && (t4[i3] = r3[i3]); } return t4; }; function M(e4, t4, n4) { Error.call(this, n4), this.status = e4, this.name = t4, this.message = n4, this.error = true; } p()(M, Error), M.prototype.toString = function() { return JSON.stringify({ status: this.status, name: this.name, message: this.message, reason: this.reason }); }, new M(401, "unauthorized", "Name or password is incorrect."); var N = new M(400, "bad_request", "Missing JSON list of 'docs'"), R = new M(404, "not_found", "missing"), F = new M(409, "conflict", "Document update conflict"), U = new M(400, "bad_request", "_id field must contain a string"), z = new M(412, "missing_id", "_id is required for puts"), J = new M(400, "bad_request", "Only reserved document ids may start with underscore."), K = (new M(412, "precondition_failed", "Database not open"), new M(500, "unknown_error", "Database encountered an unknown error")), V = new M(500, "badarg", "Some query argument is invalid"), Q = (new M(400, "invalid_request", "Request was invalid"), new M(400, "query_parse_error", "Some query parameter is invalid")), G = new M(500, "doc_validation", "Bad special document member"), W = new M(400, "bad_request", "Something wrong with the request"), Z = new M(400, "bad_request", "Document must be a JSON object"), X = (new M(404, "not_found", "Database not found"), new M(500, "indexed_db_went_bad", "unknown")), Y = (new M(500, "web_sql_went_bad", "unknown"), new M(500, "levelDB_went_went_bad", "unknown"), new M(403, "forbidden", "Forbidden by design doc validate_doc_update function"), new M(400, "bad_request", "Invalid rev format")), H = (new M(412, "file_exists", "The database could not be created, the file already exists."), new M(412, "missing_stub", "A pre-existing attachment stub wasn't found")); function ee(e4, t4) { function n4(t5) { for (var n5 = Object.getOwnPropertyNames(e4), r3 = 0, i3 = n5.length; r3 < i3; r3++) typeof e4[n5[r3]] != "function" && (this[n5[r3]] = e4[n5[r3]]); this.stack === void 0 && (this.stack = new Error().stack), t5 !== void 0 && (this.reason = t5); } return n4.prototype = M.prototype, new n4(t4); } function te(e4) { if (typeof e4 != "object") { var t4 = e4; (e4 = K).data = t4; } return "error" in e4 && e4.error === "conflict" && (e4.name = "conflict", e4.status = 409), "name" in e4 || (e4.name = e4.error || "unknown"), "status" in e4 || (e4.status = 500), "message" in e4 || (e4.message = e4.message || e4.reason), "stack" in e4 || (e4.stack = new Error().stack), e4; } function ne(e4) { var t4 = {}, n4 = e4.filter && typeof e4.filter == "function"; return t4.query = e4.query_params, function(r3) { r3.doc || (r3.doc = {}); var i3 = n4 && function(e5, t5, n5) { try { return !e5(t5, n5); } catch (e6) { var r4 = "Filter function threw: " + e6.toString(); return ee(W, r4); } }(e4.filter, r3.doc, t4); if (typeof i3 == "object") return i3; if (i3) return false; if (e4.include_docs) { if (!e4.attachments) for (var o2 in r3.doc._attachments) Object.prototype.hasOwnProperty.call(r3.doc._attachments, o2) && (r3.doc._attachments[o2].stub = true); } else delete r3.doc; return true; }; } function re(e4) { for (var t4 = [], n4 = 0, r3 = e4.length; n4 < r3; n4++) t4 = t4.concat(e4[n4]); return t4; } function ie(e4) { var t4; if (e4 ? typeof e4 != "string" ? t4 = ee(U) : /^_/.test(e4) && !/^_(design|local)/.test(e4) && (t4 = ee(J)) : t4 = ee(z), t4) throw t4; } function oe(e4) { return typeof e4._remote == "boolean" ? e4._remote : typeof e4.type == "function" && (L("warn", "db.type() is deprecated and will be removed in a future version of PouchDB"), e4.type() === "http"); } function se(e4) { if (!e4) return null; var t4 = e4.split("/"); return t4.length === 2 ? t4 : t4.length === 1 ? [e4, e4] : null; } function ae(e4) { var t4 = se(e4); return t4 ? t4.join("/") : null; } new M(413, "invalid_url", "Provided URL is invalid"); var ue = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], ce = "queryKey", fe = /(?:^|&)([^&=]*)=?([^&]*)/g, le = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; function de(e4) { for (var t4 = le.exec(e4), n4 = {}, r3 = 14; r3--; ) { var i3 = ue[r3], o2 = t4[r3] || "", s2 = ["user", "password"].indexOf(i3) !== -1; n4[i3] = s2 ? decodeURIComponent(o2) : o2; } return n4[ce] = {}, n4[ue[12]].replace(fe, function(e5, t5, r4) { t5 && (n4[ce][t5] = r4); }), n4; } function he(e4, t4) { var n4 = [], r3 = []; for (var i3 in t4) Object.prototype.hasOwnProperty.call(t4, i3) && (n4.push(i3), r3.push(t4[i3])); return n4.push(e4), Function.apply(null, n4).apply(null, r3); } function pe(e4, t4, n4) { return e4.get(t4).catch(function(e5) { if (e5.status !== 404) throw e5; return {}; }).then(function(r3) { var i3 = r3._rev, o2 = n4(r3); return o2 ? (o2._id = t4, o2._rev = i3, function(e5, t5, n5) { return e5.put(t5).then(function(e6) { return { updated: true, rev: e6.rev }; }, function(r4) { if (r4.status !== 409) throw r4; return pe(e5, t5._id, n5); }); }(e4, o2, n4)) : { updated: false, rev: i3 }; }); } var ve = function(e4) { return atob(e4); }, ye = function(e4) { return btoa(e4); }; function ge(e4, t4) { e4 = e4 || [], t4 = t4 || {}; try { return new Blob(e4, t4); } catch (i3) { if (i3.name !== "TypeError") throw i3; for (var n4 = new (typeof BlobBuilder != "undefined" ? BlobBuilder : typeof MSBlobBuilder != "undefined" ? MSBlobBuilder : typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : WebKitBlobBuilder)(), r3 = 0; r3 < e4.length; r3 += 1) n4.append(e4[r3]); return n4.getBlob(t4.type); } } function _e(e4) { for (var t4 = e4.length, n4 = new ArrayBuffer(t4), r3 = new Uint8Array(n4), i3 = 0; i3 < t4; i3++) r3[i3] = e4.charCodeAt(i3); return n4; } function me(e4, t4) { return ge([_e(e4)], { type: t4 }); } function be(e4, t4) { return me(ve(e4), t4); } function we(e4, t4) { var n4 = new FileReader(), r3 = typeof n4.readAsBinaryString == "function"; n4.onloadend = function(e5) { var n5 = e5.target.result || ""; if (r3) return t4(n5); t4(function(e6) { for (var t5 = "", n6 = new Uint8Array(e6), r4 = n6.byteLength, i3 = 0; i3 < r4; i3++) t5 += String.fromCharCode(n6[i3]); return t5; }(n5)); }, r3 ? n4.readAsBinaryString(e4) : n4.readAsArrayBuffer(e4); } function ke(e4, t4) { we(e4, function(e5) { t4(e5); }); } function je(e4, t4) { ke(e4, function(e5) { t4(ye(e5)); }); } var Oe = self.setImmediate || self.setTimeout; function $e(e4, t4, n4, r3, i3) { (n4 > 0 || r3 < t4.size) && (t4 = function(e5, t5, n5) { return e5.webkitSlice ? e5.webkitSlice(t5, n5) : e5.slice(t5, n5); }(t4, n4, r3)), function(e5, t5) { var n5 = new FileReader(); n5.onloadend = function(e6) { var n6 = e6.target.result || new ArrayBuffer(0); t5(n6); }, n5.readAsArrayBuffer(e5); }(t4, function(t5) { e4.append(t5), i3(); }); } function xe(e4, t4, n4, r3, i3) { (n4 > 0 || r3 < t4.length) && (t4 = t4.substring(n4, r3)), e4.appendBinary(t4), i3(); } function qe(e4, t4) { var n4 = typeof e4 == "string", r3 = n4 ? e4.length : e4.size, i3 = Math.min(32768, r3), o2 = Math.ceil(r3 / i3), s2 = 0, a2 = n4 ? new (c())() : new (c()).ArrayBuffer(), u2 = n4 ? xe : $e; function f2() { Oe(d2); } function l2() { var e5, n5 = (e5 = a2.end(true), ye(e5)); t4(n5), a2.destroy(); } function d2() { var t5 = s2 * i3; s2++, u2(a2, e4, t5, t5 + i3, s2 < o2 ? f2 : l2); } d2(); } function Ae(e4) { return c().hash(e4); } function Se(e4, t4) { if (!t4) return (0, a.Z)().replace(/-/g, "").toLowerCase(); var n4 = T({}, e4); return delete n4._rev_tree, Ae(JSON.stringify(n4)); } var Ee = a.Z; function Pe(e4) { for (var t4, n4, r3, i3, o2 = e4.rev_tree.slice(); i3 = o2.pop(); ) { var s2 = i3.ids, a2 = s2[2], u2 = i3.pos; if (a2.length) for (var c2 = 0, f2 = a2.length; c2 < f2; c2++) o2.push({ pos: u2 + 1, ids: a2[c2] }); else { var l2 = !!s2[1].deleted, d2 = s2[0]; t4 && !(r3 !== l2 ? r3 : n4 !== u2 ? n4 < u2 : t4 < d2) || (t4 = d2, n4 = u2, r3 = l2); } } return n4 + "-" + t4; } function Ce(e4, t4) { for (var n4, r3 = e4.slice(); n4 = r3.pop(); ) for (var i3 = n4.pos, o2 = n4.ids, s2 = o2[2], a2 = t4(s2.length === 0, i3, o2[0], n4.ctx, o2[1]), u2 = 0, c2 = s2.length; u2 < c2; u2++) r3.push({ pos: i3 + 1, ids: s2[u2], ctx: a2 }); } function De(e4, t4) { return e4.pos - t4.pos; } function Le(e4) { var t4 = []; Ce(e4, function(e5, n5, r4, i3, o2) { e5 && t4.push({ rev: n5 + "-" + r4, pos: n5, opts: o2 }); }), t4.sort(De).reverse(); for (var n4 = 0, r3 = t4.length; n4 < r3; n4++) delete t4[n4].pos; return t4; } function Be(e4) { for (var t4 = Pe(e4), n4 = Le(e4.rev_tree), r3 = [], i3 = 0, o2 = n4.length; i3 < o2; i3++) { var s2 = n4[i3]; s2.rev === t4 || s2.opts.deleted || r3.push(s2.rev); } return r3; } function Ie(e4) { for (var t4, n4 = [], r3 = e4.slice(); t4 = r3.pop(); ) { var i3 = t4.pos, o2 = t4.ids, s2 = o2[0], a2 = o2[1], u2 = o2[2], c2 = u2.length === 0, f2 = t4.history ? t4.history.slice() : []; f2.push({ id: s2, opts: a2 }), c2 && n4.push({ pos: i3 + 1 - f2.length, ids: f2 }); for (var l2 = 0, d2 = u2.length; l2 < d2; l2++) r3.push({ pos: i3 + 1, ids: u2[l2], history: f2 }); } return n4.reverse(); } function Te(e4, t4) { return e4.pos - t4.pos; } function Me(e4, t4, n4) { var r3 = function(e5, t5, n5) { for (var r4, i3 = 0, o2 = e5.length; i3 < o2; ) n5(e5[r4 = i3 + o2 >>> 1], t5) < 0 ? i3 = r4 + 1 : o2 = r4; return i3; }(e4, t4, n4); e4.splice(r3, 0, t4); } function Ne(e4, t4) { for (var n4, r3, i3 = t4, o2 = e4.length; i3 < o2; i3++) { var s2 = e4[i3], a2 = [s2.id, s2.opts, []]; r3 ? (r3[2].push(a2), r3 = a2) : n4 = r3 = a2; } return n4; } function Re(e4, t4) { return e4[0] < t4[0] ? -1 : 1; } function Fe(e4, t4) { for (var n4 = [{ tree1: e4, tree2: t4 }], r3 = false; n4.length > 0; ) { var i3 = n4.pop(), o2 = i3.tree1, s2 = i3.tree2; (o2[1].status || s2[1].status) && (o2[1].status = o2[1].status === "available" || s2[1].status === "available" ? "available" : "missing"); for (var a2 = 0; a2 < s2[2].length; a2++) if (o2[2][0]) { for (var u2 = false, c2 = 0; c2 < o2[2].length; c2++) o2[2][c2][0] === s2[2][a2][0] && (n4.push({ tree1: o2[2][c2], tree2: s2[2][a2] }), u2 = true); u2 || (r3 = "new_branch", Me(o2[2], s2[2][a2], Re)); } else r3 = "new_leaf", o2[2][0] = s2[2][a2]; } return { conflicts: r3, tree: e4 }; } function Ue(e4, t4, n4) { var r3, i3 = [], o2 = false, s2 = false; if (!e4.length) return { tree: [t4], conflicts: "new_leaf" }; for (var a2 = 0, u2 = e4.length; a2 < u2; a2++) { var c2 = e4[a2]; if (c2.pos === t4.pos && c2.ids[0] === t4.ids[0]) r3 = Fe(c2.ids, t4.ids), i3.push({ pos: c2.pos, ids: r3.tree }), o2 = o2 || r3.conflicts, s2 = true; else if (n4 !== true) { var f2 = c2.pos < t4.pos ? c2 : t4, l2 = c2.pos < t4.pos ? t4 : c2, d2 = l2.pos - f2.pos, h2 = [], p2 = []; for (p2.push({ ids: f2.ids, diff: d2, parent: null, parentIdx: null }); p2.length > 0; ) { var v2 = p2.pop(); if (v2.diff !== 0) for (var y2 = v2.ids[2], g2 = 0, _2 = y2.length; g2 < _2; g2++) p2.push({ ids: y2[g2], diff: v2.diff - 1, parent: v2.ids, parentIdx: g2 }); else v2.ids[0] === l2.ids[0] && h2.push(v2); } var m2 = h2[0]; m2 ? (r3 = Fe(m2.ids, l2.ids), m2.parent[2][m2.parentIdx] = r3.tree, i3.push({ pos: f2.pos, ids: f2.ids }), o2 = o2 || r3.conflicts, s2 = true) : i3.push(c2); } else i3.push(c2); } return s2 || i3.push(t4), i3.sort(Te), { tree: i3, conflicts: o2 || "internal_node" }; } function ze(e4, t4, n4) { var r3 = Ue(e4, t4), i3 = function(e5, t5) { for (var n5, r4, i4 = Ie(e5), o2 = 0, s2 = i4.length; o2 < s2; o2++) { var a2, u2 = i4[o2], c2 = u2.ids; if (c2.length > t5) { n5 || (n5 = {}); var f2 = c2.length - t5; a2 = { pos: u2.pos + f2, ids: Ne(c2, f2) }; for (var l2 = 0; l2 < f2; l2++) { var d2 = u2.pos + l2 + "-" + c2[l2].id; n5[d2] = true; } } else a2 = { pos: u2.pos, ids: Ne(c2, 0) }; r4 = r4 ? Ue(r4, a2, true).tree : [a2]; } return n5 && Ce(r4, function(e6, t6, r5) { delete n5[t6 + "-" + r5]; }), { tree: r4, revs: n5 ? Object.keys(n5) : [] }; }(r3.tree, n4); return { tree: i3.tree, stemmedRevs: i3.revs, conflicts: r3.conflicts }; } function Je(e4) { return e4.ids; } function Ke(e4, t4) { t4 || (t4 = Pe(e4)); for (var n4, r3 = t4.substring(t4.indexOf("-") + 1), i3 = e4.rev_tree.map(Je); n4 = i3.pop(); ) { if (n4[0] === r3) return !!n4[1].deleted; i3 = i3.concat(n4[2]); } } function Ve(e4) { return /^_local/.test(e4); } function Qe(e4, t4, n4) { y().call(this); var r3 = this; this.db = e4; var i3 = (t4 = t4 ? O(t4) : {}).complete = $(function(t5, n5) { var i4, s3; t5 ? (s3 = "error", ("listenerCount" in (i4 = r3) ? i4.listenerCount(s3) : y().listenerCount(i4, s3)) > 0 && r3.emit("error", t5)) : r3.emit("complete", n5), r3.removeAllListeners(), e4.removeListener("destroyed", o2); }); function o2() { r3.cancel(); } n4 && (r3.on("complete", function(e5) { n4(null, e5); }), r3.on("error", n4)), e4.once("destroyed", o2), t4.onChange = function(e5, t5, n5) { r3.isCancelled || function(e6, t6, n6, r4) { try { e6.emit("change", t6, n6, r4); } catch (e7) { L("error", 'Error in .on("change", function):', e7); } }(r3, e5, t5, n5); }; var s2 = new Promise(function(e5, n5) { t4.complete = function(t5, r4) { t5 ? n5(t5) : e5(r4); }; }); r3.once("cancel", function() { e4.removeListener("destroyed", o2), t4.complete(null, { status: "cancelled" }); }), this.then = s2.then.bind(s2), this.catch = s2.catch.bind(s2), this.then(function(e5) { i3(null, e5); }, i3), e4.taskqueue.isReady ? r3.validateChanges(t4) : e4.taskqueue.addTask(function(e5) { e5 ? t4.complete(e5) : r3.isCancelled ? r3.emit("cancel") : r3.validateChanges(t4); }); } function Ge(e4, t4, n4) { var r3 = [{ rev: e4._rev }]; n4.style === "all_docs" && (r3 = Le(t4.rev_tree).map(function(e5) { return { rev: e5.rev }; })); var i3 = { id: t4.id, changes: r3, doc: e4 }; return Ke(t4, e4._rev) && (i3.deleted = true), n4.conflicts && (i3.doc._conflicts = Be(t4), i3.doc._conflicts.length || delete i3.doc._conflicts), i3; } function We(e4, t4) { return e4 < t4 ? -1 : e4 > t4 ? 1 : 0; } function Ze(e4, t4) { return function(n4, r3) { n4 || r3[0] && r3[0].error ? ((n4 = n4 || r3[0]).docId = t4, e4(n4)) : e4(null, r3.length ? r3[0] : r3); }; } function Xe(e4, t4) { var n4 = We(e4._id, t4._id); return n4 !== 0 ? n4 : We(e4._revisions ? e4._revisions.start : 0, t4._revisions ? t4._revisions.start : 0); } function Ye(e4) { var t4 = e4._compactionQueue[0], n4 = t4.opts, r3 = t4.callback; e4.get("_local/compaction").catch(function() { return false; }).then(function(t5) { t5 && t5.last_seq && (n4.last_seq = t5.last_seq), e4._compact(n4, function(t6, n5) { t6 ? r3(t6) : r3(null, n5), s()(function() { e4._compactionQueue.shift(), e4._compactionQueue.length && Ye(e4); }); }); }); } function He() { for (var e4 in y().call(this), He.prototype) typeof this[e4] == "function" && (this[e4] = this[e4].bind(this)); } function et() { this.isReady = false, this.failed = false, this.queue = []; } function tt(e4, t4) { if (!(this instanceof tt)) return new tt(e4, t4); var n4 = this; if (t4 = t4 || {}, e4 && typeof e4 == "object" && (e4 = (t4 = e4).name, delete t4.name), t4.deterministic_revs === void 0 && (t4.deterministic_revs = true), this.__opts = t4 = O(t4), n4.auto_compaction = t4.auto_compaction, n4.prefix = tt.prefix, typeof e4 != "string") throw new Error("Missing/invalid DB name"); var r3 = function(e5, t5) { var n5 = e5.match(/([a-z-]*):\/\/(.*)/); if (n5) return { name: /https?/.test(n5[1]) ? n5[1] + "://" + n5[2] : n5[2], adapter: n5[1] }; var r4 = tt.adapters, i3 = tt.preferredAdapters, o2 = tt.prefix, s2 = t5.adapter; if (!s2) for (var a2 = 0; a2 < i3.length && (s2 = i3[a2]) === "idb" && "websql" in r4 && C() && localStorage["_pouch__websqldb_" + o2 + e5]; ++a2) L("log", 'PouchDB is downgrading "' + e5 + '" to WebSQL to avoid data loss, because it was already opened with WebSQL.'); var u2 = r4[s2]; return { name: u2 && "use_prefix" in u2 && !u2.use_prefix ? e5 : o2 + e5, adapter: s2 }; }((t4.prefix || "") + e4, t4); if (t4.name = r3.name, t4.adapter = t4.adapter || r3.adapter, n4.name = e4, n4._adapter = t4.adapter, tt.emit("debug", ["adapter", "Picked adapter: ", t4.adapter]), !tt.adapters[t4.adapter] || !tt.adapters[t4.adapter].valid()) throw new Error("Invalid Adapter: " + t4.adapter); if (t4.view_adapter && (!tt.adapters[t4.view_adapter] || !tt.adapters[t4.view_adapter].valid())) throw new Error("Invalid View Adapter: " + t4.view_adapter); He.call(n4), n4.taskqueue = new et(), n4.adapter = t4.adapter, tt.adapters[t4.adapter].call(n4, t4, function(e5) { if (e5) return n4.taskqueue.fail(e5); !function(e6) { function t5(t6) { e6.removeListener("closed", n5), t6 || e6.constructor.emit("destroyed", e6.name); } function n5() { e6.removeListener("destroyed", t5), e6.constructor.emit("unref", e6); } e6.once("destroyed", t5), e6.once("closed", n5), e6.constructor.emit("ref", e6); }(n4), n4.emit("created", n4), tt.emit("created", n4.name), n4.taskqueue.ready(n4); }); } p()(Qe, y()), Qe.prototype.cancel = function() { this.isCancelled = true, this.db.taskqueue.isReady && this.emit("cancel"); }, Qe.prototype.validateChanges = function(e4) { var t4 = e4.complete, n4 = this; tt._changesFilterPlugin ? tt._changesFilterPlugin.validate(e4, function(r3) { if (r3) return t4(r3); n4.doChanges(e4); }) : n4.doChanges(e4); }, Qe.prototype.doChanges = function(e4) { var t4 = this, n4 = e4.complete; if ("live" in (e4 = O(e4)) && !("continuous" in e4) && (e4.continuous = e4.live), e4.processChange = Ge, e4.since === "latest" && (e4.since = "now"), e4.since || (e4.since = 0), e4.since !== "now") { if (tt._changesFilterPlugin) { if (tt._changesFilterPlugin.normalize(e4), tt._changesFilterPlugin.shouldFilter(this, e4)) return tt._changesFilterPlugin.filter(this, e4); } else ["doc_ids", "filter", "selector", "view"].forEach(function(t5) { t5 in e4 && L("warn", 'The "' + t5 + '" 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.'); }); "descending" in e4 || (e4.descending = false), e4.limit = e4.limit === 0 ? 1 : e4.limit, e4.complete = n4; var r3 = this.db._changes(e4); if (r3 && typeof r3.cancel == "function") { var i3 = t4.cancel; t4.cancel = d()(function(e5) { r3.cancel(), i3.apply(this, e5); }); } } else this.db.info().then(function(r4) { t4.isCancelled ? n4(null, { status: "cancelled" }) : (e4.since = r4.update_seq, t4.doChanges(e4)); }, n4); }, p()(He, y()), He.prototype.post = q("post", function(e4, t4, n4) { if (typeof t4 == "function" && (n4 = t4, t4 = {}), typeof e4 != "object" || Array.isArray(e4)) return n4(ee(Z)); this.bulkDocs({ docs: [e4] }, t4, Ze(n4, e4._id)); }), He.prototype.put = q("put", function(e4, t4, n4) { if (typeof t4 == "function" && (n4 = t4, t4 = {}), typeof e4 != "object" || Array.isArray(e4)) return n4(ee(Z)); if (ie(e4._id), Ve(e4._id) && typeof this._putLocal == "function") return e4._deleted ? this._removeLocal(e4, n4) : this._putLocal(e4, n4); var r3, i3, o2, s2, a2 = this; function u2(n5) { typeof a2._put == "function" && t4.new_edits !== false ? a2._put(e4, t4, n5) : a2.bulkDocs({ docs: [e4] }, t4, Ze(n5, e4._id)); } t4.force && e4._rev ? (i3 = (r3 = e4._rev.split("-"))[1], o2 = parseInt(r3[0], 10) + 1, s2 = Se(), e4._revisions = { start: o2, ids: [s2, i3] }, e4._rev = o2 + "-" + s2, t4.new_edits = false, u2(function(t5) { var r4 = t5 ? null : { ok: true, id: e4._id, rev: e4._rev }; n4(t5, r4); })) : u2(n4); }), He.prototype.putAttachment = q("putAttachment", function(e4, t4, n4, r3, i3) { var o2 = this; function s2(e5) { var n5 = "_rev" in e5 ? parseInt(e5._rev, 10) : 0; return e5._attachments = e5._attachments || {}, e5._attachments[t4] = { content_type: i3, data: r3, revpos: ++n5 }, o2.put(e5); } return typeof i3 == "function" && (i3 = r3, r3 = n4, n4 = null), i3 === void 0 && (i3 = r3, r3 = n4, n4 = null), i3 || L("warn", "Attachment", t4, "on document", e4, "is missing content_type"), o2.get(e4).then(function(e5) { if (e5._rev !== n4) throw ee(F); return s2(e5); }, function(t5) { if (t5.reason === R.message) return s2({ _id: e4 }); throw t5; }); }), He.prototype.removeAttachment = q("removeAttachment", function(e4, t4, n4, r3) { var i3 = this; i3.get(e4, function(e5, o2) { if (e5) r3(e5); else if (o2._rev === n4) { if (!o2._attachments) return r3(); delete o2._attachments[t4], Object.keys(o2._attachments).length === 0 && delete o2._attachments, i3.put(o2, r3); } else r3(ee(F)); }); }), He.prototype.remove = q("remove", function(e4, t4, n4, r3) { var i3; typeof t4 == "string" ? (i3 = { _id: e4, _rev: t4 }, typeof n4 == "function" && (r3 = n4, n4 = {})) : (i3 = e4, typeof t4 == "function" ? (r3 = t4, n4 = {}) : (r3 = n4, n4 = t4)), (n4 = n4 || {}).was_delete = true; var o2 = { _id: i3._id, _rev: i3._rev || n4.rev, _deleted: true }; if (Ve(o2._id) && typeof this._removeLocal == "function") return this._removeLocal(i3, r3); this.bulkDocs({ docs: [o2] }, n4, Ze(r3, o2._id)); }), He.prototype.revsDiff = q("revsDiff", function(e4, t4, n4) { typeof t4 == "function" && (n4 = t4, t4 = {}); var r3 = Object.keys(e4); if (!r3.length) return n4(null, {}); var o2 = 0, s2 = new i2(); function a2(e5, t5) { s2.has(e5) || s2.set(e5, { missing: [] }), s2.get(e5).missing.push(t5); } r3.map(function(t5) { this._getRevisionTree(t5, function(i3, u2) { if (i3 && i3.status === 404 && i3.message === "missing") s2.set(t5, { missing: e4[t5] }); else { if (i3) return n4(i3); !function(t6, n5) { var r4 = e4[t6].slice(0); Ce(n5, function(e5, n6, i4, o3, s3) { var u3 = n6 + "-" + i4, c3 = r4.indexOf(u3); c3 !== -1 && (r4.splice(c3, 1), s3.status !== "available" && a2(t6, u3)); }), r4.forEach(function(e5) { a2(t6, e5); }); }(t5, u2); } if (++o2 === r3.length) { var c2 = {}; return s2.forEach(function(e5, t6) { c2[t6] = e5; }), n4(null, c2); } }); }, this); }), He.prototype.bulkGet = q("bulkGet", function(e4, t4) { P(this, e4, t4); }), He.prototype.compactDocument = q("compactDocument", function(e4, t4, n4) { var r3 = this; this._getRevisionTree(e4, function(i3, o2) { if (i3) return n4(i3); var s2 = function(e5) { var t5 = {}, n5 = []; return Ce(e5, function(e6, r4, i4, o3) { var s3 = r4 + "-" + i4; return e6 && (t5[s3] = 0), o3 !== void 0 && n5.push({ from: o3, to: s3 }), s3; }), n5.reverse(), n5.forEach(function(e6) { t5[e6.from] === void 0 ? t5[e6.from] = 1 + t5[e6.to] : t5[e6.from] = Math.min(t5[e6.from], 1 + t5[e6.to]); }), t5; }(o2), a2 = [], u2 = []; Object.keys(s2).forEach(function(e5) { s2[e5] > t4 && a2.push(e5); }), Ce(o2, function(e5, t5, n5, r4, i4) { var o3 = t5 + "-" + n5; i4.status === "available" && a2.indexOf(o3) !== -1 && u2.push(o3); }), r3._doCompaction(e4, u2, n4); }); }), He.prototype.compact = q("compact", function(e4, t4) { typeof e4 == "function" && (t4 = e4, e4 = {}); var n4 = this; e4 = e4 || {}, n4._compactionQueue = n4._compactionQueue || [], n4._compactionQueue.push({ opts: e4, callback: t4 }), n4._compactionQueue.length === 1 && Ye(n4); }), He.prototype._compact = function(e4, t4) { var n4 = this, r3 = { return_docs: false, last_seq: e4.last_seq || 0 }, i3 = []; n4.changes(r3).on("change", function(e5) { i3.push(n4.compactDocument(e5.id, 0)); }).on("complete", function(e5) { var r4 = e5.last_seq; Promise.all(i3).then(function() { return pe(n4, "_local/compaction", function(e6) { return (!e6.last_seq || e6.last_seq < r4) && (e6.last_seq = r4, e6); }); }).then(function() { t4(null, { ok: true }); }).catch(t4); }).on("error", t4); }, He.prototype.get = q("get", function(e4, t4, n4) { if (typeof t4 == "function" && (n4 = t4, t4 = {}), typeof e4 != "string") return n4(ee(U)); if (Ve(e4) && typeof this._getLocal == "function") return this._getLocal(e4, n4); var r3 = [], i3 = this; function o2() { var o3 = [], s3 = r3.length; if (!s3) return n4(null, o3); r3.forEach(function(r4) { i3.get(e4, { rev: r4, revs: t4.revs, latest: t4.latest, attachments: t4.attachments, binary: t4.binary }, function(e5, t5) { if (e5) o3.push({ missing: r4 }); else { for (var i4, a3 = 0, u2 = o3.length; a3 < u2; a3++) if (o3[a3].ok && o3[a3].ok._rev === t5._rev) { i4 = true; break; } i4 || o3.push({ ok: t5 }); } --s3 || n4(null, o3); }); }); } if (!t4.open_revs) return this._get(e4, t4, function(r4, o3) { if (r4) return r4.docId = e4, n4(r4); var s3 = o3.doc, a3 = o3.metadata, u2 = o3.ctx; if (t4.conflicts) { var c2 = Be(a3); c2.length && (s3._conflicts = c2); } if (Ke(a3, s3._rev) && (s3._deleted = true), t4.revs || t4.revs_info) { for (var f2 = s3._rev.split("-"), l2 = parseInt(f2[0], 10), d2 = f2[1], h2 = Ie(a3.rev_tree), p2 = null, v2 = 0; v2 < h2.length; v2++) { var y2 = h2[v2], g2 = y2.ids.map(function(e5) { return e5.id; }).indexOf(d2); (g2 === l2 - 1 || !p2 && g2 !== -1) && (p2 = y2); } if (!p2) return (r4 = new Error("invalid rev tree")).docId = e4, n4(r4); var _2 = p2.ids.map(function(e5) { return e5.id; }).indexOf(s3._rev.split("-")[1]) + 1, m2 = p2.ids.length - _2; if (p2.ids.splice(_2, m2), p2.ids.reverse(), t4.revs && (s3._revisions = { start: p2.pos + p2.ids.length - 1, ids: p2.ids.map(function(e5) { return e5.id; }) }), t4.revs_info) { var b2 = p2.pos + p2.ids.length; s3._revs_info = p2.ids.map(function(e5) { return { rev: --b2 + "-" + e5.id, status: e5.opts.status }; }); } } if (t4.attachments && s3._attachments) { var w2 = s3._attachments, k2 = Object.keys(w2).length; if (k2 === 0) return n4(null, s3); Object.keys(w2).forEach(function(e5) { this._getAttachment(s3._id, e5, w2[e5], { rev: s3._rev, binary: t4.binary, ctx: u2 }, function(t5, r5) { var i4 = s3._attachments[e5]; i4.data = r5, delete i4.stub, delete i4.length, --k2 || n4(null, s3); }); }, i3); } else { if (s3._attachments) for (var j2 in s3._attachments) Object.prototype.hasOwnProperty.call(s3._attachments, j2) && (s3._attachments[j2].stub = true); n4(null, s3); } }); if (t4.open_revs === "all") this._getRevisionTree(e4, function(e5, t5) { if (e5) return n4(e5); r3 = Le(t5).map(function(e6) { return e6.rev; }), o2(); }); else { if (!Array.isArray(t4.open_revs)) return n4(ee(K, "function_clause")); r3 = t4.open_revs; for (var s2 = 0; s2 < r3.length; s2++) { var a2 = r3[s2]; if (typeof a2 != "string" || !/^\d+-/.test(a2)) return n4(ee(Y)); } o2(); } }), He.prototype.getAttachment = q("getAttachment", function(e4, t4, n4, r3) { var i3 = this; n4 instanceof Function && (r3 = n4, n4 = {}), this._get(e4, n4, function(o2, s2) { return o2 ? r3(o2) : s2.doc._attachments && s2.doc._attachments[t4] ? (n4.ctx = s2.ctx, n4.binary = true, void i3._getAttachment(e4, t4, s2.doc._attachments[t4], n4, r3)) : r3(ee(R)); }); }), He.prototype.allDocs = q("allDocs", function(e4, t4) { if (typeof e4 == "function" && (t4 = e4, e4 = {}), e4.skip = e4.skip !== void 0 ? e4.skip : 0, e4.start_key && (e4.startkey = e4.start_key), e4.end_key && (e4.endkey = e4.end_key), "keys" in e4) { if (!Array.isArray(e4.keys)) return t4(new TypeError("options.keys must be an array")); var n4 = ["startkey", "endkey", "key"].filter(function(t5) { return t5 in e4; })[0]; if (n4) return void t4(ee(Q, "Query parameter `" + n4 + "` is not compatible with multi-get")); if (!oe(this) && (function(e5) { var t5 = "limit" in e5 ? e5.keys.slice(e5.skip, e5.limit + e5.skip) : e5.skip > 0 ? e5.keys.slice(e5.skip) : e5.keys; e5.keys = t5, e5.skip = 0, delete e5.limit, e5.descending && (t5.reverse(), e5.descending = false); }(e4), e4.keys.length === 0)) return this._allDocs({ limit: 0 }, t4); } return this._allDocs(e4, t4); }), He.prototype.changes = function(e4, t4) { return typeof e4 == "function" && (t4 = e4, e4 = {}), (e4 = e4 || {}).return_docs = "return_docs" in e4 ? e4.return_docs : !e4.live, new Qe(this, e4, t4); }, He.prototype.close = q("close", function(e4) { return this._closed = true, this.emit("closed"), this._close(e4); }), He.prototype.info = q("info", function(e4) { var t4 = this; this._info(function(n4, r3) { if (n4) return e4(n4); r3.db_name = r3.db_name || t4.name, r3.auto_compaction = !(!t4.auto_compaction || oe(t4)), r3.adapter = t4.adapter, e4(null, r3); }); }), He.prototype.id = q("id", function(e4) { return this._id(e4); }), He.prototype.type = function() { return typeof this._type == "function" ? this._type() : this.adapter; }, He.prototype.bulkDocs = q("bulkDocs", function(e4, t4, n4) { if (typeof t4 == "function" && (n4 = t4, t4 = {}), t4 = t4 || {}, Array.isArray(e4) && (e4 = { docs: e4 }), !e4 || !e4.docs || !Array.isArray(e4.docs)) return n4(ee(N)); for (var r3 = 0; r3 < e4.docs.length; ++r3) if (typeof e4.docs[r3] != "object" || Array.isArray(e4.docs[r3])) return n4(ee(Z)); var i3; if (e4.docs.forEach(function(e5) { e5._attachments && Object.keys(e5._attachments).forEach(function(t5) { i3 = i3 || function(e6) { return e6.charAt(0) === "_" && e6 + " is not a valid attachment name, attachment names cannot start with '_'"; }(t5), e5._attachments[t5].content_type || L("warn", "Attachment", t5, "on document", e5._id, "is missing content_type"); }); }), i3) return n4(ee(W, i3)); "new_edits" in t4 || (t4.new_edits = !("new_edits" in e4) || e4.new_edits); var o2 = this; t4.new_edits || oe(o2) || e4.docs.sort(Xe), function(e5) { for (var t5 = 0; t5 < e5.length; t5++) { var n5 = e5[t5]; if (n5._deleted) delete n5._attachments; else if (n5._attachments) for (var r4 = Object.keys(n5._attachments), i4 = 0; i4 < r4.length; i4++) { var o3 = r4[i4]; n5._attachments[o3] = A(n5._attachments[o3], ["data", "digest", "content_type", "length", "revpos", "stub"]); } } }(e4.docs); var s2 = e4.docs.map(function(e5) { return e5._id; }); return this._bulkDocs(e4, t4, function(e5, r4) { if (e5) return n4(e5); if (t4.new_edits || (r4 = r4.filter(function(e6) { return e6.error; })), !oe(o2)) for (var i4 = 0, a2 = r4.length; i4 < a2; i4++) r4[i4].id = r4[i4].id || s2[i4]; n4(null, r4); }); }), He.prototype.registerDependentDatabase = q("registerDependentDatabase", function(e4, t4) { var n4 = O(this.__opts); this.__opts.view_adapter && (n4.adapter = this.__opts.view_adapter); var r3 = new this.constructor(e4, n4); pe(this, "_local/_pouch_dependentDbs", function(t5) { return t5.dependentDbs = t5.dependentDbs || {}, !t5.dependentDbs[e4] && (t5.dependentDbs[e4] = true, t5); }).then(function() { t4(null, { db: r3 }); }).catch(t4); }), He.prototype.destroy = q("destroy", function(e4, t4) { typeof e4 == "function" && (t4 = e4, e4 = {}); var n4 = this, r3 = !("use_prefix" in n4) || n4.use_prefix; function i3() { n4._destroy(e4, function(e5, r4) { if (e5) return t4(e5); n4._destroyed = true, n4.emit("destroyed"), t4(null, r4 || { ok: true }); }); } if (oe(n4)) return i3(); n4.get("_local/_pouch_dependentDbs", function(e5, o2) { if (e5) return e5.status !== 404 ? t4(e5) : i3(); var s2 = o2.dependentDbs, a2 = n4.constructor, u2 = Object.keys(s2).map(function(e6) { var t5 = r3 ? e6.replace(new RegExp("^" + a2.prefix), "") : e6; return new a2(t5, n4.__opts).destroy(); }); Promise.all(u2).then(i3, t4); }); }), et.prototype.execute = function() { var e4; if (this.failed) for (; e4 = this.queue.shift(); ) e4(this.failed); else for (; e4 = this.queue.shift(); ) e4(); }, et.prototype.fail = function(e4) { this.failed = e4, this.execute(); }, et.prototype.ready = function(e4) { this.isReady = true, this.db = e4, this.execute(); }, et.prototype.addTask = function(e4) { this.queue.push(e4), this.failed && this.execute(); }, p()(tt, He); var nt = typeof AbortController != "undefined" ? AbortController : function() { return { abort: function() { } }; }, rt = fetch, it = Headers; tt.adapters = {}, tt.preferredAdapters = [], tt.prefix = "_pouch_"; var ot = new (y())(); function st(e4, t4) { for (var n4 = e4, r3 = 0, i3 = t4.length; r3 < i3 && (n4 = n4[t4[r3]]); r3++) ; return n4; } function at(e4) { for (var t4 = [], n4 = "", r3 = 0, i3 = e4.length; r3 < i3; r3++) { var o2 = e4[r3]; r3 > 0 && e4[r3 - 1] === "\\" && (o2 === "$" || o2 === ".") ? n4 = n4.substring(0, n4.length - 1) + o2 : o2 === "." ? (t4.push(n4), n4 = "") : n4 += o2; } return t4.push(n4), t4; } !function(e4) { Object.keys(y().prototype).forEach(function(t5) { typeof y().prototype[t5] == "function" && (e4[t5] = ot[t5].bind(ot)); }); var t4 = e4._destructionListeners = new i2(); e4.on("ref", function(e5) { t4.has(e5.name) || t4.set(e5.name, []), t4.get(e5.name).push(e5); }), e4.on("unref", function(e5) { if (t4.has(e5.name)) { var n4 = t4.get(e5.name), r3 = n4.indexOf(e5); r3 < 0 || (n4.splice(r3, 1), n4.length > 1 ? t4.set(e5.name, n4) : t4.delete(e5.name)); } }), e4.on("destroyed", function(e5) { if (t4.has(e5)) { var n4 = t4.get(e5); t4.delete(e5), n4.forEach(function(e6) { e6.emit("destroyed", true); }); } }); }(tt), tt.adapter = function(e4, t4, n4) { t4.valid() && (tt.adapters[e4] = t4, n4 && tt.preferredAdapters.push(e4)); }, tt.plugin = function(e4) { if (typeof e4 == "function") e4(tt); else { if (typeof e4 != "object" || Object.keys(e4).length === 0) throw new Error('Invalid plugin: got "' + e4 + '", expected an object or a function'); Object.keys(e4).forEach(function(t4) { tt.prototype[t4] = e4[t4]; }); } return this.__defaults && (tt.__defaults = T({}, this.__defaults)), tt; }, tt.defaults = function(e4) { function t4(e5, n4) { if (!(this instanceof t4)) return new t4(e5, n4); n4 = n4 || {}, e5 && typeof e5 == "object" && (e5 = (n4 = e5).name, delete n4.name), n4 = T({}, t4.__defaults, n4), tt.call(this, e5, n4); } return p()(t4, tt), t4.preferredAdapters = tt.preferredAdapters.slice(), Object.keys(tt).forEach(function(e5) { e5 in t4 || (t4[e5] = tt[e5]); }), t4.__defaults = T({}, this.__defaults, e4), t4; }, tt.fetch = function(e4, t4) { return rt(e4, t4); }; var ut = ["$or", "$nor", "$not"]; function ct(e4) { return ut.indexOf(e4) > -1; } function ft(e4) { return Object.keys(e4)[0]; } function lt(e4) { var t4 = {}, n4 = { $or: true, $nor: true }; return e4.forEach(function(e5) { Object.keys(e5).forEach(function(r3) { var i3 = e5[r3]; if (typeof i3 != "object" && (i3 = { $eq: i3 }), ct(r3)) if (i3 instanceof Array) { if (n4[r3]) return n4[r3] = false, void (t4[r3] = i3); var o2 = []; t4[r3].forEach(function(e6) { Object.keys(i3).forEach(function(t5) { var n5 = i3[t5], r4 = Math.max(Object.keys(e6).length, Object.keys(n5).length), s3 = lt([e6, n5]); Object.keys(s3).length <= r4 || o2.push(s3); }); }), t4[r3] = o2; } else t4[r3] = lt([i3]); else { var s2 = t4[r3] = t4[r3] || {}; Object.keys(i3).forEach(function(e6) { var t5 = i3[e6]; return e6 === "$gt" || e6 === "$gte" ? function(e7, t6, n5) { n5.$eq === void 0 && (n5.$gte !== void 0 ? e7 === "$gte" ? t6 > n5.$gte && (n5.$gte = t6) : t6 >= n5.$gte && (delete n5.$gte, n5.$gt = t6) : n5.$gt !== void 0 ? e7 === "$gte" ? t6 > n5.$gt && (delete n5.$gt, n5.$gte = t6) : t6 > n5.$gt && (n5.$gt = t6) : n5[e7] = t6); }(e6, t5, s2) : e6 === "$lt" || e6 === "$lte" ? function(e7, t6, n5) { n5.$eq === void 0 && (n5.$lte !== void 0 ? e7 === "$lte" ? t6 < n5.$lte && (n5.$lte = t6) : t6 <= n5.$lte && (delete n5.$lte, n5.$lt = t6) : n5.$lt !== void 0 ? e7 === "$lte" ? t6 < n5.$lt && (delete n5.$lt, n5.$lte = t6) : t6 < n5.$lt && (n5.$lt = t6) : n5[e7] = t6); }(e6, t5, s2) : e6 === "$ne" ? function(e7, t6) { "$ne" in t6 ? t6.$ne.push(e7) : t6.$ne = [e7]; }(t5, s2) : e6 === "$eq" ? function(e7, t6) { delete t6.$gt, delete t6.$gte, delete t6.$lt, delete t6.$lte, delete t6.$ne, t6.$eq = e7; }(t5, s2) : e6 === "$regex" ? function(e7, t6) { "$regex" in t6 ? t6.$regex.push(e7) : t6.$regex = [e7]; }(t5, s2) : void (s2[e6] = t5); }); } }); }), t4; } function dt(e4) { for (var t4 in e4) { if (Array.isArray(e4)) for (var n4 in e4) e4[n4].$and && (e4[n4] = lt(e4[n4].$and)); var r3 = e4[t4]; typeof r3 == "object" && dt(r3); } return e4; } function ht(e4, t4) { for (var n4 in e4) { n4 === "$and" && (t4 = true); var r3 = e4[n4]; typeof r3 == "object" && (t4 = ht(r3, t4)); } return t4; } function pt(e4) { var t4 = O(e4), n4 = false; ht(t4, false) && ("$and" in (t4 = dt(t4)) && (t4 = lt(t4.$and)), n4 = true), ["$or", "$nor"].forEach(function(e5) { e5 in t4 && t4[e5].forEach(function(e6) { for (var t5 = Object.keys(e6), n5 = 0; n5 < t5.length; n5++) { var r4 = t5[n5], i4 = e6[r4]; typeof i4 == "object" && i4 !== null || (e6[r4] = { $eq: i4 }); } }); }), "$not" in t4 && (t4.$not = lt([t4.$not])); for (var r3 = Object.keys(t4), i3 = 0; i3 < r3.length; i3++) { var o2 = r3[i3], s2 = t4[o2]; typeof s2 != "object" || s2 === null ? s2 = { $eq: s2 } : n4 || ("$ne" in s2 && (s2.$ne = [s2.$ne]), "$regex" in s2 && (s2.$regex = [s2.$regex])), t4[o2] = s2; } return t4; } function vt(e4, t4) { if (e4 === t4) return 0; e4 = yt(e4), t4 = yt(t4); var n4 = bt(e4), r3 = bt(t4); if (n4 - r3 != 0) return n4 - r3; switch (typeof e4) { case "number": return e4 - t4; case "boolean": return e4 < t4 ? -1 : 1; case "string": return function(e5, t5) { return e5 === t5 ? 0 : e5 > t5 ? 1 : -1; }(e4, t4); } return Array.isArray(e4) ? function(e5, t5) { for (var n5 = Math.min(e5.length, t5.length), r4 = 0; r4 < n5; r4++) { var i3 = vt(e5[r4], t5[r4]); if (i3 !== 0) return i3; } return e5.length === t5.length ? 0 : e5.length > t5.length ? 1 : -1; }(e4, t4) : function(e5, t5) { for (var n5 = Object.keys(e5), r4 = Object.keys(t5), i3 = Math.min(n5.length, r4.length), o2 = 0; o2 < i3; o2++) { var s2 = vt(n5[o2], r4[o2]); if (s2 !== 0) return s2; if ((s2 = vt(e5[n5[o2]], t5[r4[o2]])) !== 0) return s2; } return n5.length === r4.length ? 0 : n5.length > r4.length ? 1 : -1; }(e4, t4); } function yt(e4) { switch (typeof e4) { case "undefined": return null; case "number": return e4 === 1 / 0 || e4 === -1 / 0 || isNaN(e4) ? null : e4; case "object": var t4 = e4; if (Array.isArray(e4)) { var n4 = e4.length; e4 = new Array(n4); for (var r3 = 0; r3 < n4; r3++) e4[r3] = yt(t4[r3]); } else { if (e4 instanceof Date) return e4.toJSON(); if (e4 !== null) { for (var i3 in e4 = {}, t4) if (Object.prototype.hasOwnProperty.call(t4, i3)) { var o2 = t4[i3]; o2 !== void 0 && (e4[i3] = yt(o2)); } } } } return e4; } function gt(e4) { return bt(e4 = yt(e4)) + "" + function(e5) { if (e5 !== null) switch (typeof e5) { case "boolean": return e5 ? 1 : 0; case "number": return function(e6) { if (e6 === 0) return "1"; var t5, n5 = e6.toExponential().split(/e\+?/), r4 = parseInt(n5[1], 10), i4 = e6 < 0, o3 = i4 ? "0" : "2"; o3 += "" + (function(e7, t6, n6) { for (var r5 = "", i5 = 3 - e7.length; r5.length < i5; ) r5 += "0"; return r5; }(t5 = ((i4 ? -r4 : r4) - -324).toString()) + t5); var s3 = Math.abs(parseFloat(n5[0])); i4 && (s3 = 10 - s3); var a2 = s3.toFixed(20); return o3 + "" + a2.replace(/\.?0+$/, ""); }(e5); case "string": return e5.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, ""); case "object": var t4 = Array.isArray(e5), n4 = t4 ? e5 : Object.keys(e5), r3 = -1, i3 = n4.length, o2 = ""; if (t4) for (; ++r3 < i3; ) o2 += gt(n4[r3]); else for (; ++r3 < i3; ) { var s2 = n4[r3]; o2 += gt(s2) + gt(e5[s2]); } return o2; } return ""; }(e4) + "\0"; } function _t(e4, t4) { var n4, r3 = t4; if (e4[t4] === "1") n4 = 0, t4++; else { var i3 = e4[t4] === "0"; t4++; var o2 = "", s2 = e4.substring(t4, t4 + 3), a2 = parseInt(s2, 10) + -324; for (i3 && (a2 = -a2), t4 += 3; ; ) { var u2 = e4[t4]; if (u2 === "\0") break; o2 += u2, t4++; } n4 = (o2 = o2.split(".")).length === 1 ? parseInt(o2, 10) : parseFloat(o2[0] + "." + o2[1]), i3 && (n4 -= 10), a2 !== 0 && (n4 = parseFloat(n4 + "e" + a2)); } return { num: n4, length: t4 - r3 }; } function mt(e4, t4) { var n4 = e4.pop(); if (t4.length) { var r3 = t4[t4.length - 1]; n4 === r3.element && (t4.pop(), r3 = t4[t4.length - 1]); var i3 = r3.element, o2 = r3.index; Array.isArray(i3) ? i3.push(n4) : o2 === e4.length - 2 ? i3[e4.pop()] = n4 : e4.push(n4); } } function bt(e4) { var t4 = ["boolean", "number", "string", "object"].indexOf(typeof e4); return ~t4 ? e4 === null ? 1 : Array.isArray(e4) ? 5 : t4 < 3 ? t4 + 2 : t4 + 3 : Array.isArray(e4) ? 5 : void 0; } function wt(e4, t4, n4) { return n4.every(function(n5) { var r3 = t4[n5], i3 = at(n5), o2 = st(e4, i3); return ct(n5) ? function(e5, t5, n6) { return e5 === "$or" ? t5.some(function(e6) { return wt(n6, e6, Object.keys(e6)); }) : e5 === "$not" ? !wt(n6, t5, Object.keys(t5)) : !t5.find(function(e6) { return wt(n6, e6, Object.keys(e6)); }); }(n5, r3, e4) : kt(r3, e4, i3, o2); }); } function kt(e4, t4, n4, r3) { return !e4 || (typeof e4 == "object" ? Object.keys(e4).every(function(i3) { var o2 = e4[i3]; if (i3.indexOf("$") === 0) return jt(i3, t4, o2, n4, r3); var s2 = at(i3); if (r3 === void 0 && typeof o2 != "object" && s2.length > 0) return false; var a2 = st(r3, s2); return typeof o2 == "object" ? kt(o2, t4, n4, a2) : jt("$eq", t4, o2, s2, a2); }) : e4 === r3); } function jt(e4, t4, n4, r3, i3) { if (!qt[e4]) throw new Error('unknown operator "' + e4 + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all'); return qt[e4](t4, n4, r3, i3); } function Ot(e4) { return e4 != null; } function $t(e4) { return e4 !== void 0; } function xt(e4, t4) { return t4.some(function(t5) { return e4 instanceof Array ? e4.some(function(e5) { return vt(t5, e5) === 0; }) : vt(t5, e4) === 0; }); } var qt = { $elemMatch: function(e4, t4, n4, r3) { return !!Array.isArray(r3) && r3.length !== 0 && (typeof r3[0] == "object" ? r3.some(function(e5) { return wt(e5, t4, Object.keys(t4)); }) : r3.some(function(r4) { return kt(t4, e4, n4, r4); })); }, $allMatch: function(e4, t4, n4, r3) { return !!Array.isArray(r3) && r3.length !== 0 && (typeof r3[0] == "object" ? r3.every(function(e5) { return wt(e5, t4, Object.keys(t4)); }) : r3.every(function(r4) { return kt(t4, e4, n4, r4); })); }, $eq: function(e4, t4, n4, r3) { return $t(r3) && vt(r3, t4) === 0; }, $gte: function(e4, t4, n4, r3) { return $t(r3) && vt(r3, t4) >= 0; }, $gt: function(e4, t4, n4, r3) { return $t(r3) && vt(r3, t4) > 0; }, $lte: function(e4, t4, n4, r3) { return $t(r3) && vt(r3, t4) <= 0; }, $lt: function(e4, t4, n4, r3) { return $t(r3) && vt(r3, t4) < 0; }, $exists: function(e4, t4, n4, r3) { return t4 ? $t(r3) : !$t(r3); }, $mod: function(e4, t4, n4, r3) { return Ot(r3) && function(e5, t5) { return typeof e5 == "number" && parseInt(e5, 10) === e5 && e5 % t5[0] === t5[1]; }(r3, t4); }, $ne: function(e4, t4, n4, r3) { return t4.every(function(e5) { return vt(r3, e5) !== 0; }); }, $in: function(e4, t4, n4, r3) { return Ot(r3) && xt(r3, t4); }, $nin: function(e4, t4, n4, r3) { return Ot(r3) && !xt(r3, t4); }, $size: function(e4, t4, n4, r3) { return Ot(r3) && Array.isArray(r3) && function(e5, t5) { return e5.length === t5; }(r3, t4); }, $all: function(e4, t4, n4, r3) { return Array.isArray(r3) && function(e5, t5) { return t5.every(function(t6) { return e5.some(function(e6) { return vt(t6, e6) === 0; }); }); }(r3, t4); }, $regex: function(e4, t4, n4, r3) { return Ot(r3) && typeof r3 == "string" && t4.every(function(e5) { return function(e6, t5) { return new RegExp(t5).test(e6); }(r3, e5); }); }, $type: function(e4, t4, n4, r3) { return function(e5, t5) { switch (t5) { case "null": return e5 === null; case "boolean": return typeof e5 == "boolean"; case "number": return typeof e5 == "number"; case "string": return typeof e5 == "string"; case "array": return e5 instanceof Array; case "object": return {}.toString.call(e5) === "[object Object]"; } }(r3, t4); } }; function At(e4, t4) { if (e4.selector && e4.filter && e4.filter !== "_selector") { var n4 = typeof e4.filter == "string" ? e4.filter : "function"; return t4(new Error('selector invalid for filter "' + n4 + '"')); } t4(); } function St(e4) { e4.view && !e4.filter && (e4.filter = "_view"), e4.selector && !e4.filter && (e4.filter = "_selector"), e4.filter && typeof e4.filter == "string" && (e4.filter === "_view" ? e4.view = ae(e4.view) : e4.filter = ae(e4.filter)); } function Et(e4, t4) { return t4.filter && typeof t4.filter == "string" && !t4.doc_ids && !oe(e4.db); } function Pt(e4, t4) { var n4 = t4.complete; if (t4.filter === "_view") { if (!t4.view || typeof t4.view != "string") { var r3 = ee(W, "`view` filter parameter not found or invalid."); return n4(r3); } var i3 = se(t4.view); e4.db.get("_design/" + i3[0], function(r4, o3) { if (e4.isCancelled) return n4(null, { status: "cancelled" }); if (r4) return n4(te(r4)); var s2 = o3 && o3.views && o3.views[i3[1]] && o3.views[i3[1]].map; if (!s2) return n4(ee(R, o3.views ? "missing json key: " + i3[1] : "missing json key: views")); t4.filter = he(["return function(doc) {", ' "use strict";', " var emitted = false;", " var emit = function (a, b) {", " emitted = true;", " };", " var view = " + s2 + ";", " view(doc);", " if (emitted) {", " return true;", " }", "};"].join("\n"), {}), e4.doChanges(t4); }); } else if (t4.selector) t4.filter = function(e5) { return function(e6, t5) { if (typeof t5 != "object") throw new Error("Selector error: expected a JSON object"); var n5 = function(e7, t6, n6) { if (e7 = e7.filter(function(e8) { return wt(e8.doc, t6.selector, n6); }), t6.sort) { var r4 = function(e8) { function t7(t8) { return e8.map(function(e9) { var n7 = at(ft(e9)); return st(t8, n7); }); } return function(e9, n7) { var r5, i5, o4 = vt(t7(e9.doc), t7(n7.doc)); return o4 !== 0 ? o4 : (r5 = e9.doc._id) < (i5 = n7.doc._id) ? -1 : r5 > i5 ? 1 : 0; }; }(t6.sort); e7 = e7.sort(r4), typeof t6.sort[0] != "string" && (i4 = t6.sort[0])[ft(i4)] === "desc" && (e7 = e7.reverse()); } var i4; if ("limit" in t6 || "skip" in t6) { var o3 = t6.skip || 0, s2 = ("limit" in t6 ? t6.limit : e7.length) + o3; e7 = e7.slice(o3, s2); } return e7; }([{ doc: e6 }], { selector: t5 = pt(t5) }, Object.keys(t5)); return n5 && n5.length === 1; }(e5, t4.selector); }, e4.doChanges(t4); else { var o2 = se(t4.filter); e4.db.get("_design/" + o2[0], function(r4, i4) { if (e4.isCancelled) return n4(null, { status: "cancelled" }); if (r4) return n4(te(r4)); var s2 = i4 && i4.filters && i4.filters[o2[1]]; if (!s2) return n4(ee(R, i4 && i4.filters ? "missing json key: " + o2[1] : "missing json key: filters")); t4.filter = he('"use strict";\nreturn ' + s2 + ";", {}), e4.doChanges(t4); }); } } function Ct(e4) { return e4.reduce(function(e5, t4) { return e5[t4] = true, e5; }, {}); } tt.plugin(function(e4) { e4._changesFilterPlugin = { validate: At, normalize: St, shouldFilter: Et, filter: Pt }; }), tt.version = "7.3.0"; var Dt = Ct(["_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"]), Lt = Ct(["_access", "_attachments", "_replication_id", "_replication_state", "_replication_state_time", "_replication_state_reason", "_replication_stats"]); function Bt(e4) { if (!/^\d+-/.test(e4)) return ee(Y); var t4 = e4.indexOf("-"), n4 = e4.substring(0, t4), r3 = e4.substring(t4 + 1); return { prefix: parseInt(n4, 10), id: r3 }; } function It(e4, t4, n4) { var r3, i3, o2; n4 || (n4 = { deterministic_revs: true }); var s2 = { status: "available" }; if (e4._deleted && (s2.deleted = true), t4) if (e4._id || (e4._id = Ee()), i3 = Se(e4, n4.deterministic_revs), e4._rev) { if ((o2 = Bt(e4._rev)).error) return o2; e4._rev_tree = [{ pos: o2.prefix, ids: [o2.id, { status: "missing" }, [[i3, s2, []]]] }], r3 = o2.prefix + 1; } else e4._rev_tree = [{ pos: 1, ids: [i3, s2, []] }], r3 = 1; else if (e4._revisions && (e4._rev_tree = function(e5, t5) { for (var n5 = e5.start - e5.ids.length + 1, r4 = e5.ids, i4 = [r4[0], t5, []], o3 = 1, s3 = r4.length; o3 < s3; o3++) i4 = [r4[o3], { status: "missing" }, [i4]]; return [{ pos: n5, ids: i4 }]; }(e4._revisions, s2), r3 = e4._revisions.start, i3 = e4._revisions.ids[0]), !e4._rev_tree) { if ((o2 = Bt(e4._rev)).error) return o2; r3 = o2.prefix, i3 = o2.id, e4._rev_tree = [{ pos: r3, ids: [i3, s2, []] }]; } ie(e4._id), e4._rev = r3 + "-" + i3; var a2 = { metadata: {}, data: {} }; for (var u2 in e4) if (Object.prototype.hasOwnProperty.call(e4, u2)) { var c2 = u2[0] === "_"; if (c2 && !Dt[u2]) { var f2 = ee(G, u2); throw f2.message = G.message + ": " + u2, f2; } c2 && !Lt[u2] ? a2.metadata[u2.slice(1)] = e4[u2] : a2.data[u2] = e4[u2]; } return a2; } function Tt(e4, t4, n4) { if (e4.stub) return n4(); typeof e4.data == "string" ? function(e5, t5, n5) { var r3 = function(e6) { try { return ve(e6); } catch (e7) { return { error: ee(V, "Attachment is not a valid base64 string") }; } }(e5.data); if (r3.error) return n5(r3.error); e5.length = r3.length, e5.data = t5 === "blob" ? me(r3, e5.content_type) : t5 === "base64" ? ye(r3) : r3, qe(r3, function(t6) { e5.digest = "md5-" + t6, n5(); }); }(e4, t4, n4) : function(e5, t5, n5) { qe(e5.data, function(r3) { e5.digest = "md5-" + r3, e5.length = e5.data.size || e5.data.length || 0, t5 === "binary" ? ke(e5.data, function(t6) { e5.data = t6, n5(); }) : t5 === "base64" ? je(e5.data, function(t6) { e5.data = t6, n5(); }) : n5(); }); }(e4, t4, n4); } function Mt(e4, t4, n4, r3, o2, s2, a2, u2, c2) { e4 = e4 || 1e3; var f2 = u2.new_edits, l2 = new i2(), d2 = 0, h2 = t4.length; function p2() { ++d2 === h2 && c2 && c2(); } t4.forEach(function(e5, t5) { if (e5._id && Ve(e5._id)) { var r4 = e5._deleted ? "_removeLocal" : "_putLocal"; n4[r4](e5, { ctx: o2 }, function(e6, n5) { s2[t5] = e6 || n5, p2(); }); } else { var i3 = e5.metadata.id; l2.has(i3) ? (h2--, l2.get(i3).push([e5, t5])) : l2.set(i3, [[e5, t5]]); } }), l2.forEach(function(t5, n5) { var i3 = 0; function o3() { ++i3 < t5.length ? c3() : p2(); } function c3() { var c4 = t5[i3], l3 = c4[0], d3 = c4[1]; if (r3.has(n5)) !function(e5, t6, n6, r4, i4, o4, s3, a3) { if (function(e6, t7) { for (var n7, r5 = e6.slice(), i5 = t7.split("-"), o5 = parseInt(i5[0], 10), s4 = i5[1]; n7 = r5.pop(); ) { if (n7.pos === o5 && n7.ids[0] === s4) return true; for (var a4 = n7.ids[2], u4 = 0, c6 = a4.length; u4 < c6; u4++) r5.push({ pos: n7.pos + 1, ids: a4[u4] }); } return false; }(t6.rev_tree, n6.metadata.rev) && !a3) return r4[i4] = n6, o4(); var u3 = t6.winningRev || Pe(t6), c5 = "deleted" in t6 ? t6.deleted : Ke(t6, u3), f3 = "deleted" in n6.metadata ? n6.metadata.deleted : Ke(n6.metadata), l4 = /^1-/.test(n6.metadata.rev); if (c5 && !f3 && a3 && l4) { var d4 = n6.data; d4._rev = u3, d4._id = n6.metadata.id, n6 = It(d4, a3); } var h4 = ze(t6.rev_tree, n6.metadata.rev_tree[0], e5); if (a3 && (c5 && f3 && h4.conflicts !== "new_leaf" || !c5 && h4.conflicts !== "new_leaf" || c5 && !f3 && h4.conflicts === "new_branch")) { var p3 = ee(F); return r4[i4] = p3, o4(); } var v2 = n6.metadata.rev; n6.metadata.rev_tree = h4.tree, n6.stemmedRevs = h4.stemmedRevs || [], t6.rev_map && (n6.metadata.rev_map = t6.rev_map); var y2 = Pe(n6.metadata), g2 = Ke(n6.metadata, y2), _2 = c5 === g2 ? 0 : c5 < g2 ? -1 : 1; s3(n6, y2, g2, v2 === y2 ? g2 : Ke(n6.metadata, v2), true, _2, i4, o4); }(e4, r3.get(n5), l3, s2, d3, o3, a2, f2); else { var h3 = ze([], l3.metadata.rev_tree[0], e4); l3.metadata.rev_tree = h3.tree, l3.stemmedRevs = h3.stemmedRevs || [], function(e5, t6, n6) { var r4 = Pe(e5.metadata), i4 = Ke(e5.metadata, r4); if ("was_delete" in u2 && i4) return s2[t6] = ee(R, "deleted"), n6(); var o4 = f2 && function(e6) { return e6.metadata.rev_tree[0].ids[1].status === "missing"; }(e5); if (o4) { var c5 = ee(F); return s2[t6] = c5, n6(); } a2(e5, r4, i4, i4, false, i4 ? 0 : 1, t6, n6); }(l3, d3, o3); } } c3(); }); } var Nt = "document-store", Rt = "by-sequence", Ft = "attach-store", Ut = "attach-seq-store", zt = "meta-store", Jt = "local-store", Kt = "detect-blob-support"; function Vt(e4) { try { return JSON.stringify(e4); } catch (t4) { return f.stringify(e4); } } function Qt(e4) { return function(t4) { var n4 = "unknown_error"; t4.target && t4.target.error && (n4 = t4.target.error.name || t4.target.error.message), e4(ee(X, n4, t4.type)); }; } function Gt(e4, t4, n4) { return { data: Vt(e4), winningRev: t4, deletedOrLocal: n4 ? "1" : "0", seq: e4.seq, id: e4.id }; } function Wt(e4) { if (!e4) return null; var t4 = function(e5) { try { return JSON.parse(e5); } catch (t5) { return f.parse(e5); } }(e4.data); return t4.winningRev = e4.winningRev, t4.deleted = e4.deletedOrLocal === "1", t4.seq = e4.seq, t4; } function Zt(e4) { if (!e4) return e4; var t4 = e4._doc_id_rev.lastIndexOf(":"); return e4._id = e4._doc_id_rev.substring(0, t4 - 1), e4._rev = e4._doc_id_rev.substring(t4 + 1), delete e4._doc_id_rev, e4; } function Xt(e4, t4, n4, r3) { n4 ? r3(e4 ? typeof e4 != "string" ? e4 : be(e4, t4) : ge([""], { type: t4 })) : e4 ? typeof e4 != "string" ? we(e4, function(e5) { r3(ye(e5)); }) : r3(e4) : r3(""); } function Yt(e4, t4, n4, r3) { var i3 = Object.keys(e4._attachments || {}); if (!i3.length) return r3 && r3(); var o2 = 0; function s2() { ++o2 === i3.length && r3 && r3(); } i3.forEach(function(r4) { t4.attachments && t4.include_docs ? function(e5, t5) { var r5 = e5._attachments[t5], i4 = r5.digest; n4.objectStore(Ft).get(i4).onsuccess = function(e6) { r5.body = e6.target.result.body, s2(); }; }(e4, r4) : (e4._attachments[r4].stub = true, s2()); }); } function Ht(e4, t4) { return Promise.all(e4.map(function(e5) { if (e5.doc && e5.doc._attachments) { var n4 = Object.keys(e5.doc._attachments); return Promise.all(n4.map(function(n5) { var r3 = e5.doc._attachments[n5]; if ("body" in r3) { var i3 = r3.body, o2 = r3.content_type; return new Promise(function(s2) { Xt(i3, o2, t4, function(t5) { e5.doc._attachments[n5] = T(A(r3, ["digest", "content_type"]), { data: t5 }), s2(); }); }); } })); } })); } function en(e4, t4, n4) { var r3 = [], i3 = n4.objectStore(Rt), o2 = n4.objectStore(Ft), s2 = n4.objectStore(Ut), a2 = e4.length; function u2() { --a2 || r3.length && r3.forEach(function(e5) { s2.index("digestSeq").count(IDBKeyRange.bound(e5 + "::", e5 + "::\uFFFF", false, false)).onsuccess = function(t5) { t5.target.result || o2.delete(e5); }; }); } e4.forEach(function(e5) { var n5 = i3.index("_doc_id_rev"), o3 = t4 + "::" + e5; n5.getKey(o3).onsuccess = function(e6) { var t5 = e6.target.result; if (typeof t5 != "number") return u2(); i3.delete(t5), s2.index("seq").openCursor(IDBKeyRange.only(t5)).onsuccess = function(e7) { var t6 = e7.target.result; if (t6) { var n6 = t6.value.digestSeq.split("::")[0]; r3.push(n6), s2.delete(t6.primaryKey), t6.continue(); } else u2(); }; }; }); } function tn(e4, t4, n4) { try { return { txn: e4.transaction(t4, n4) }; } catch (e5) { return { error: e5 }; } } var nn = new D(); function rn(e4, t4, n4, r3, o2, s2) { for (var a2, u2, c2, f2, l2, d2, h2, p2, v2 = t4.docs, y2 = 0, g2 = v2.length; y2 < g2; y2++) { var _2 = v2[y2]; _2._id && Ve(_2._id) || (_2 = v2[y2] = It(_2, n4.new_edits, e4)).error && !h2 && (h2 = _2); } if (h2) return s2(h2); var m2 = false, b2 = 0, w2 = new Array(v2.length), k2 = new i2(), j2 = false, O2 = r3._meta.blobSupport ? "blob" : "base64"; function $2() { m2 = true, x2(); } function x2() { p2 && m2 && (p2.docCount += b2, d2.put(p2)); } function q2() { j2 || (nn.notify(r3._meta.name), s2(null, w2)); } function A2(e5, t5, n5, r4, i3, o3, s3, a3) { e5.metadata.winningRev = t5, e5.metadata.deleted = n5; var u3 = e5.data; if (u3._id = e5.metadata.id, u3._rev = e5.metadata.rev, r4 && (u3._deleted = true), u3._attachments && Object.keys(u3._attachments).length) return function(e6, t6, n6, r5, i4, o4) { var s4 = e6.data, a4 = 0, u4 = Object.keys(s4._attachments); function c3() { a4 === u4.length && S2(e6, t6, n6, r5, i4, o4); } function l3() { a4++, c3(); } u4.forEach(function(n7) { var r6 = e6.data._attachments[n7]; if (r6.stub) a4++, c3(); else { var i5 = r6.data; delete r6.data, r6.revpos = parseInt(t6, 10), function(e7, t7, n8) { f2.count(e7).onsuccess = function(r7) { if (r7.target.result) return n8(); var i6 = { digest: e7, body: t7 }; f2.put(i6).onsuccess = n8; }; }(r6.digest, i5, l3); } }); }(e5, t5, n5, i3, s3, a3); b2 += o3, x2(), S2(e5, t5, n5, i3, s3, a3); } function S2(e5, t5, n5, i3, o3, s3) { var f3 = e5.data, d3 = e5.metadata; function h3(o4) { var s4 = e5.stemmedRevs || []; i3 && r3.auto_compaction && (s4 = s4.concat(function(e6) { var t6 = []; return Ce(e6.rev_tree, function(e7, n6, r4, i4, o5) { o5.status !== "available" || e7 || (t6.push(n6 + "-" + r4), o5.status = "missing"); }), t6; }(e5.metadata))), s4 && s4.length && en(s4, e5.metadata.id, a2), d3.seq = o4.target.result; var c3 = Gt(d3, t5, n5); u2.put(c3).onsuccess = p3; } function p3() { w2[o3] = { ok: true, id: d3.id, rev: d3.rev }, k2.set(e5.metadata.id, e5.metadata), function(e6, t6, n6) { var r4 = 0, i4 = Object.keys(e6.data._attachments || {}); if (!i4.length) return n6(); function o4() { ++r4 === i4.length && n6(); } function s4(n7) { var r5 = e6.data._attachments[n7].digest, i5 = l2.put({ seq: t6, digestSeq: r5 + "::" + t6 }); i5.onsuccess = o4, i5.onerror = function(e7) { e7.preventDefault(), e7.stopPropagation(), o4(); }; } for (var a3 = 0; a3 < i4.length; a3++) s4(i4[a3]); }(e5, d3.seq, s3); } f3._doc_id_rev = d3.id + "::" + d3.rev, delete f3._id, delete f3._rev; var v3 = c2.put(f3); v3.onsuccess = h3, v3.onerror = function(e6) { e6.preventDefault(), e6.stopPropagation(), c2.index("_doc_id_rev").getKey(f3._doc_id_rev).onsuccess = function(e7) { c2.put(f3, e7.target.result).onsuccess = h3; }; }; } !function(e5, t5, n5) { if (!e5.length) return n5(); var r4, i3 = 0; function o3() { i3++, e5.length === i3 && (r4 ? n5(r4) : n5()); } e5.forEach(function(e6) { var n6 = e6.data && e6.data._attachments ? Object.keys(e6.data._attachments) : [], i4 = 0; if (!n6.length) return o3(); function s3(e7) { r4 = e7, ++i4 === n6.length && o3(); } for (var a3 in e6.data._attachments) Object.prototype.hasOwnProperty.call(e6.data._attachments, a3) && Tt(e6.data._attachments[a3], t5, s3); }); }(v2, O2, function(t5) { if (t5) return s2(t5); !function() { var t6 = tn(o2, [Nt, Rt, Ft, Jt, Ut, zt], "readwrite"); if (t6.error) return s2(t6.error); (a2 = t6.txn).onabort = Qt(s2), a2.ontimeout = Qt(s2), a2.oncomplete = q2, u2 = a2.objectStore(Nt), c2 = a2.objectStore(Rt), f2 = a2.objectStore(Ft), l2 = a2.objectStore(Ut), (d2 = a2.objectStore(zt)).get(zt).onsuccess = function(e5) { p2 = e5.target.result, x2(); }, function(e5) { var t7 = []; if (v2.forEach(function(e6) { e6.data && e6.data._attachments && Object.keys(e6.data._attachments).forEach(function(n6) { var r5 = e6.data._attachments[n6]; r5.stub && t7.push(r5.digest); }); }), !t7.length) return e5(); var n5, r4 = 0; t7.forEach(function(i3) { !function(e6, t8) { f2.get(e6).onsuccess = function(n6) { if (n6.target.result) t8(); else { var r5 = ee(H, "unknown stub attachment with digest " + e6); r5.status = 412, t8(r5); } }; }(i3, function(i4) { i4 && !n5 && (n5 = i4), ++r4 === t7.length && e5(n5); }); }); }(function(t7) { if (t7) return j2 = true, s2(t7); !function() { if (v2.length) for (var t8 = 0, i3 = 0, o3 = v2.length; i3 < o3; i3++) { var s3 = v2[i3]; s3._id && Ve(s3._id) ? c3() : u2.get(s3.metadata.id).onsuccess = f3; } function c3() { ++t8 === v2.length && Mt(e4.revs_limit, v2, r3, k2, a2, w2, A2, n4, $2); } function f3(e5) { var t9 = Wt(e5.target.result); t9 && k2.set(t9.id, t9), c3(); } }(); }); }(); }); } function on(e4, t4, n4, r3, i3) { var o2, s2, a2; function u2(e5) { s2 = e5.target.result, o2 && i3(o2, s2, a2); } function c2(e5) { o2 = e5.target.result, s2 && i3(o2, s2, a2); } function f2(e5) { var t5 = e5.target.result; if (!t5) return i3(); i3([t5.key], [t5.value], t5); } r3 === -1 && (r3 = 1e3), typeof e4.getAll == "function" && typeof e4.getAllKeys == "function" && r3 > 1 && !n4 ? (a2 = { continue: function() { if (!o2.length) return i3(); var n5, a3 = o2[o2.length - 1]; if (t4 && t4.upper) try { n5 = IDBKeyRange.bound(a3, t4.upper, true, t4.upperOpen); } catch (e5) { if (e5.name === "DataError" && e5.code === 0) return i3(); } else n5 = IDBKeyRange.lowerBound(a3, true); t4 = n5, o2 = null, s2 = null, e4.getAll(t4, r3).onsuccess = u2, e4.getAllKeys(t4, r3).onsuccess = c2; } }, e4.getAll(t4, r3).onsuccess = u2, e4.getAllKeys(t4, r3).onsuccess = c2) : n4 ? e4.openCursor(t4, "prev").onsuccess = f2 : e4.openCursor(t4).onsuccess = f2; } function sn(e4, t4, n4) { var r3, i3, o2 = "startkey" in e4 && e4.startkey, s2 = "endkey" in e4 && e4.endkey, a2 = "key" in e4 && e4.key, u2 = "keys" in e4 && e4.keys, c2 = e4.skip || 0, f2 = typeof e4.limit == "number" ? e4.limit : -1, l2 = e4.inclusive_end !== false; if (!u2 && (r3 = function(e5, t5, n5, r4, i4) { try { if (e5 && t5) return i4 ? IDBKeyRange.bound(t5, e5, !n5, false) : IDBKeyRange.bound(e5, t5, false, !n5); if (e5) return i4 ? IDBKeyRange.upperBound(e5) : IDBKeyRange.lowerBound(e5); if (t5) return i4 ? IDBKeyRange.lowerBound(t5, !n5) : IDBKeyRange.upperBound(t5, !n5); if (r4) return IDBKeyRange.only(r4); } catch (e6) { return { error: e6 }; } return null; }(o2, s2, l2, a2, e4.descending), (i3 = r3 && r3.error) && (i3.name !== "DataError" || i3.code !== 0))) return n4(ee(X, i3.name, i3.message)); var d2 = [Nt, Rt, zt]; e4.attachments && d2.push(Ft); var h2 = tn(t4, d2, "readonly"); if (h2.error) return n4(h2.error); var p2 = h2.txn; p2.oncomplete = function() { e4.attachments ? Ht(w2, e4.binary).then($2) : $2(); }, p2.onabort = Qt(n4); var v2, y2, g2 = p2.objectStore(Nt), _2 = p2.objectStore(Rt), m2 = p2.objectStore(zt), b2 = _2.index("_doc_id_rev"), w2 = []; function k2(t5, n5) { var r4 = { id: n5.id, key: n5.id, value: { rev: t5 } }; n5.deleted ? u2 && (w2.push(r4), r4.value.deleted = true, r4.doc = null) : c2-- <= 0 && (w2.push(r4), e4.include_docs && function(t6, n6, r5) { var i4 = t6.id + "::" + r5; b2.get(i4).onsuccess = function(r6) { if (n6.doc = Zt(r6.target.result) || {}, e4.conflicts) { var i5 = Be(t6); i5.length && (n6.doc._conflicts = i5); } Yt(n6.doc, e4, p2); }; }(n5, r4, t5)); } function j2(e5) { for (var t5 = 0, n5 = e5.length; t5 < n5 && w2.length !== f2; t5++) { var r4 = e5[t5]; if (r4.error && u2) w2.push(r4); else { var i4 = Wt(r4); k2(i4.winningRev, i4); } } } function O2(e5, t5, n5) { n5 && (j2(t5), w2.length < f2 && n5.continue()); } function $2() { var t5 = { total_rows: v2, offset: e4.skip, rows: w2 }; e4.update_seq && y2 !== void 0 && (t5.update_seq = y2), n4(null, t5); } return m2.get(zt).onsuccess = function(e5) { v2 = e5.target.result.docCount; }, e4.update_seq && (_2.openCursor(null, "prev").onsuccess = function(e5) { var t5 = e5.target.result, n5 = void 0; return t5 && t5.key && (n5 = t5.key), function(e6) { e6.target.result && e6.target.result.length > 0 && (y2 = e6.target.result[0]); }({ target: { result: [n5] } }); }), i3 || f2 === 0 ? void 0 : u2 ? function(e5, t5, n5) { var r4 = new Array(e5.length), i4 = 0; e5.forEach(function(o3, s3) { t5.get(o3).onsuccess = function(t6) { t6.target.result ? r4[s3] = t6.target.result : r4[s3] = { key: o3, error: "not_found" }, ++i4 === e5.length && n5(e5, r4, {}); }; }); }(e4.keys, g2, O2) : f2 === -1 ? function(e5, t5, n5) { if (typeof e5.getAll != "function") { var r4 = []; e5.openCursor(t5).onsuccess = function(e6) { var t6 = e6.target.result; t6 ? (r4.push(t6.value), t6.continue()) : n5({ target: { result: r4 } }); }; } else e5.getAll(t5).onsuccess = n5; }(g2, r3, function(t5) { var n5 = t5.target.result; e4.descending && (n5 = n5.reverse()), j2(n5); }) : void on(g2, r3, e4.descending, f2 + c2, O2); } var an = false, un = []; function cn() { !an && un.length && (an = true, un.shift()()); } var fn, ln = new i2(), dn = new i2(); function hn(e4, t4) { var n4 = this; !function(t5, o2, a2) { un.push(function() { var t6; t6 = function(e5, t7) { !function(e6, t8, n5, r3) { try { e6(t8, n5); } catch (t9) { r3.emit("error", t9); } }(o2, e5, t7, a2), an = false, s()(function() { cn(); }); }, function(e5, t7, n5) { var o3 = t7.name, a3 = null, u2 = null; function c2(e6) { return function(t8, n6) { t8 && t8 instanceof Error && !t8.reason && u2 && (t8.reason = u2), e6(t8, n6); }; } function f2(e6) { var t8 = e6.createObjectStore(Nt, { keyPath: "id" }); e6.createObjectStore(Rt, { autoIncrement: true }).createIndex("_doc_id_rev", "_doc_id_rev", { unique: true }), e6.createObjectStore(Ft, { keyPath: "digest" }), e6.createObjectStore(zt, { keyPath: "id", autoIncrement: false }), e6.createObjectStore(Kt), t8.createIndex("deletedOrLocal", "deletedOrLocal", { unique: false }), e6.createObjectStore(Jt, { keyPath: "_id" }); var n6 = e6.createObjectStore(Ut, { autoIncrement: true }); n6.createIndex("seq", "seq"), n6.createIndex("digestSeq", "digestSeq", { unique: true }); } function l2(e6, t8) { var n6 = e6.objectStore(Nt); n6.createIndex("deletedOrLocal", "deletedOrLocal", { unique: false }), n6.openCursor().onsuccess = function(e7) { var r3 = e7.target.result; if (r3) { var i3 = r3.value, o4 = Ke(i3); i3.deletedOrLocal = o4 ? "1" : "0", n6.put(i3), r3.continue(); } else t8(); }; } function d2(e6) { e6.createObjectStore(Jt, { keyPath: "_id" }).createIndex("_doc_id_rev", "_doc_id_rev", { unique: true }); } function h2(e6, t8) { var n6 = e6.objectStore(Jt), r3 = e6.objectStore(Nt), i3 = e6.objectStore(Rt); r3.openCursor().onsuccess = function(e7) { var o4 = e7.target.result; if (o4) { var s2 = o4.value, a4 = s2.id, u3 = Ve(a4), c3 = Pe(s2); if (u3) { var f3 = a4 + "::" + c3, l3 = a4 + "::", d3 = a4 + "::~", h3 = i3.index("_doc_id_rev"), p3 = IDBKeyRange.bound(l3, d3, false, false), v3 = h3.openCursor(p3); v3.onsuccess = function(e8) { if (v3 = e8.target.result) { var t9 = v3.value; t9._doc_id_rev === f3 && n6.put(t9), i3.delete(v3.primaryKey), v3.continue(); } else r3.delete(o4.primaryKey), o4.continue(); }; } else o4.continue(); } else t8 && t8(); }; } function p2(e6) { var t8 = e6.createObjectStore(Ut, { autoIncrement: true }); t8.createIndex("seq", "seq"), t8.createIndex("digestSeq", "digestSeq", { unique: true }); } function v2(e6, t8) { var n6 = e6.objectStore(Rt), r3 = e6.objectStore(Ft), i3 = e6.objectStore(Ut); r3.count().onsuccess = function(e7) { if (!e7.target.result) return t8(); n6.openCursor().onsuccess = function(e8) { var n7 = e8.target.result; if (!n7) return t8(); for (var r4 = n7.value, o4 = n7.primaryKey, s2 = Object.keys(r4._attachments || {}), a4 = {}, u3 = 0; u3 < s2.length; u3++) a4[r4._attachments[s2[u3]].digest] = true; var c3 = Object.keys(a4); for (u3 = 0; u3 < c3.length; u3++) { var f3 = c3[u3]; i3.put({ seq: o4, digestSeq: f3 + "::" + o4 }); } n7.continue(); }; }; } function y2(e6) { function t8(e7) { return e7.data ? Wt(e7) : (e7.deleted = e7.deletedOrLocal === "1", e7); } var n6 = e6.objectStore(Rt), r3 = e6.objectStore(Nt); r3.openCursor().onsuccess = function(e7) { var i3 = e7.target.result; if (i3) { var o4 = t8(i3.value); if (o4.winningRev = o4.winningRev || Pe(o4), o4.seq) return a4(); s2(); } function s2() { var e8 = o4.id + "::", t9 = o4.id + "::\uFFFF", r4 = n6.index("_doc_id_rev").openCursor(IDBKeyRange.bound(e8, t9)), i4 = 0; r4.onsuccess = function(e9) { var t10 = e9.target.result; if (!t10) return o4.seq = i4, a4(); var n7 = t10.primaryKey; n7 > i4 && (i4 = n7), t10.continue(); }; } function a4() { var e8 = Gt(o4, o4.winningRev, o4.deleted); r3.put(e8).onsuccess = function() { i3.continue(); }; } }; } e5._meta = null, e5._remote = false, e5.type = function() { return "idb"; }, e5._id = x(function(t8) { t8(null, e5._meta.instanceId); }), e5._bulkDocs = function(n6, r3, i3) { rn(t7, n6, r3, e5, a3, c2(i3)); }, e5._get = function(e6, t8, n6) { var r3, i3, o4, s2 = t8.ctx; if (!s2) { var u3 = tn(a3, [Nt, Rt, Ft], "readonly"); if (u3.error) return n6(u3.error); s2 = u3.txn; } function c3() { n6(o4, { doc: r3, metadata: i3, ctx: s2 }); } s2.objectStore(Nt).get(e6).onsuccess = function(e7) { if (!(i3 = Wt(e7.target.result))) return o4 = ee(R, "missing"), c3(); var n7; if (t8.rev) n7 = t8.latest ? function(e8, t9) { for (var n8, r4 = t9.rev_tree.slice(); n8 = r4.pop(); ) { var i4 = n8.pos, o5 = n8.ids, s3 = o5[0], a5 = o5[1], u5 = o5[2], c4 = u5.length === 0, f3 = n8.history ? n8.history.slice() : []; if (f3.push({ id: s3, pos: i4, opts: a5 }), c4) for (var l3 = 0, d3 = f3.length; l3 < d3; l3++) { var h3 = f3[l3]; if (h3.pos + "-" + h3.id === e8) return i4 + "-" + s3; } for (var p3 = 0, v3 = u5.length; p3 < v3; p3++) r4.push({ pos: i4 + 1, ids: u5[p3], history: f3 }); } throw new Error("Unable to resolve latest revision for id " + t9.id + ", rev " + e8); }(t8.rev, i3) : t8.rev; else if (n7 = i3.winningRev, Ke(i3)) return o4 = ee(R, "deleted"), c3(); var a4 = s2.objectStore(Rt), u4 = i3.id + "::" + n7; a4.index("_doc_id_rev").get(u4).onsuccess = function(e8) { if ((r3 = e8.target.result) && (r3 = Zt(r3)), !r3) return o4 = ee(R, "missing"), c3(); c3(); }; }; }, e5._getAttachment = function(e6, t8, n6, r3, i3) { var o4; if (r3.ctx) o4 = r3.ctx; else { var s2 = tn(a3, [Nt, Rt, Ft], "readonly"); if (s2.error) return i3(s2.error); o4 = s2.txn; } var u3 = n6.digest, c3 = n6.content_type; o4.objectStore(Ft).get(u3).onsuccess = function(e7) { Xt(e7.target.result.body, c3, r3.binary, function(e8) { i3(null, e8); }); }; }, e5._info = function(t8) { var n6, r3, i3 = tn(a3, [zt, Rt], "readonly"); if (i3.error) return t8(i3.error); var o4 = i3.txn; o4.objectStore(zt).get(zt).onsuccess = function(e6) { r3 = e6.target.result.docCount; }, o4.objectStore(Rt).openCursor(null, "prev").onsuccess = function(e6) { var t9 = e6.target.result; n6 = t9 ? t9.key : 0; }, o4.oncomplete = function() { t8(null, { doc_count: r3, update_seq: n6, idb_attachment_format: e5._meta.blobSupport ? "binary" : "base64" }); }; }, e5._allDocs = function(e6, t8) { sn(e6, a3, c2(t8)); }, e5._changes = function(t8) { return function(e6, t9, n6, o4) { if ((e6 = O(e6)).continuous) { var s2 = n6 + ":" + Ee(); return nn.addListener(n6, s2, t9, e6), nn.notify(n6), { cancel: function() { nn.removeListener(n6, s2); } }; } var a4 = e6.doc_ids && new r2(e6.doc_ids); e6.since = e6.since || 0; var u3 = e6.since, c3 = "limit" in e6 ? e6.limit : -1; c3 === 0 && (c3 = 1); var f3, l3, d3, h3, p3 = [], v3 = 0, y3 = ne(e6), g3 = new i2(); function _3(e7, t10, n7, r3) { if (n7.seq !== t10) return r3(); if (n7.winningRev === e7._rev) return r3(n7, e7); var i3 = e7._id + "::" + n7.winningRev; h3.get(i3).onsuccess = function(e8) { r3(n7, Zt(e8.target.result)); }; } function m2() { e6.complete(null, { results: p3, last_seq: u3 }); } var b2 = [Nt, Rt]; e6.attachments && b2.push(Ft); var w2 = tn(o4, b2, "readonly"); if (w2.error) return e6.complete(w2.error); (f3 = w2.txn).onabort = Qt(e6.complete), f3.oncomplete = function() { !e6.continuous && e6.attachments ? Ht(p3).then(m2) : m2(); }, l3 = f3.objectStore(Rt), d3 = f3.objectStore(Nt), h3 = l3.index("_doc_id_rev"), on(l3, e6.since && !e6.descending ? IDBKeyRange.lowerBound(e6.since, true) : null, e6.descending, c3, function(t10, n7, r3) { if (r3 && t10.length) { var i3 = new Array(t10.length), o5 = new Array(t10.length), s3 = 0; n7.forEach(function(n8, u4) { !function(e7, t11, n9) { if (a4 && !a4.has(e7._id)) return n9(); var r4 = g3.get(e7._id); if (r4) return _3(e7, t11, r4, n9); d3.get(e7._id).onsuccess = function(i4) { r4 = Wt(i4.target.result), g3.set(e7._id, r4), _3(e7, t11, r4, n9); }; }(Zt(n8), t10[u4], function(n9, a5) { o5[u4] = n9, i3[u4] = a5, ++s3 === t10.length && function() { for (var t11 = [], n10 = 0, s4 = i3.length; n10 < s4 && v3 !== c3; n10++) { var a6 = i3[n10]; if (a6) { var u5 = o5[n10]; t11.push(l4(u5, a6)); } } Promise.all(t11).then(function(t12) { for (var n11 = 0, r4 = t12.length; n11 < r4; n11++) t12[n11] && e6.onChange(t12[n11]); }).catch(e6.complete), v3 !== c3 && r3.continue(); }(); }); }); } function l4(t11, n8) { var r4 = e6.processChange(n8, t11, e6); u3 = r4.seq = t11.seq; var i4 = y3(r4); return typeof i4 == "object" ? Promise.reject(i4) : i4 ? (v3++, e6.return_docs && p3.push(r4), e6.attachments && e6.include_docs ? new Promise(function(t12) { Yt(n8, e6, f3, function() { Ht([r4], e6.binary).then(function() { t12(r4); }); }); }) : Promise.resolve(r4)) : Promise.resolve(); } }); }(t8, e5, o3, a3); }, e5._close = function(e6) { a3.close(), ln.delete(o3), e6(); }, e5._getRevisionTree = function(e6, t8) { var n6 = tn(a3, [Nt], "readonly"); if (n6.error) return t8(n6.error); n6.txn.objectStore(Nt).get(e6).onsuccess = function(e7) { var n7 = Wt(e7.target.result); n7 ? t8(null, n7.rev_tree) : t8(ee(R)); }; }, e5._doCompaction = function(e6, t8, n6) { var r3 = tn(a3, [Nt, Rt, Ft, Ut], "readwrite"); if (r3.error) return n6(r3.error); var i3 = r3.txn; i3.objectStore(Nt).get(e6).onsuccess = function(n7) { var r4 = Wt(n7.target.result); Ce(r4.rev_tree, function(e7, n8, r5, i4, o5) { var s3 = n8 + "-" + r5; t8.indexOf(s3) !== -1 && (o5.status = "missing"); }), en(t8, e6, i3); var o4 = r4.winningRev, s2 = r4.deleted; i3.objectStore(Nt).put(Gt(r4, o4, s2)); }, i3.onabort = Qt(n6), i3.oncomplete = function() { n6(); }; }, e5._getLocal = function(e6, t8) { var n6 = tn(a3, [Jt], "readonly"); if (n6.error) return t8(n6.error); var r3 = n6.txn.objectStore(Jt).get(e6); r3.onerror = Qt(t8), r3.onsuccess = function(e7) { var n7 = e7.target.result; n7 ? (delete n7._doc_id_rev, t8(null, n7)) : t8(ee(R)); }; }, e5._putLocal = function(e6, t8, n6) { typeof t8 == "function" && (n6 = t8, t8 = {}), delete e6._revisions; var r3 = e6._rev, i3 = e6._id; e6._rev = r3 ? "0-" + (parseInt(r3.split("-")[1], 10) + 1) : "0-1"; var o4, s2 = t8.ctx; if (!s2) { var u3 = tn(a3, [Jt], "readwrite"); if (u3.error) return n6(u3.error); (s2 = u3.txn).onerror = Qt(n6), s2.oncomplete = function() { o4 && n6(null, o4); }; } var c3, f3 = s2.objectStore(Jt); r3 ? (c3 = f3.get(i3)).onsuccess = function(i4) { var s3 = i4.target.result; s3 && s3._rev === r3 ? f3.put(e6).onsuccess = function() { o4 = { ok: true, id: e6._id, rev: e6._rev }, t8.ctx && n6(null, o4); } : n6(ee(F)); } : ((c3 = f3.add(e6)).onerror = function(e7) { n6(ee(F)), e7.preventDefault(), e7.stopPropagation(); }, c3.onsuccess = function() { o4 = { ok: true, id: e6._id, rev: e6._rev }, t8.ctx && n6(null, o4); }); }, e5._removeLocal = function(e6, t8, n6) { typeof t8 == "function" && (n6 = t8, t8 = {}); var r3, i3 = t8.ctx; if (!i3) { var o4 = tn(a3, [Jt], "readwrite"); if (o4.error) return n6(o4.error); (i3 = o4.txn).oncomplete = function() { r3 && n6(null, r3); }; } var s2 = e6._id, u3 = i3.objectStore(Jt), c3 = u3.get(s2); c3.onerror = Qt(n6), c3.onsuccess = function(i4) { var o5 = i4.target.result; o5 && o5._rev === e6._rev ? (u3.delete(s2), r3 = { ok: true, id: s2, rev: "0-0" }, t8.ctx && n6(null, r3)) : n6(ee(R)); }; }, e5._destroy = function(e6, t8) { nn.removeAllListeners(o3); var n6 = dn.get(o3); n6 && n6.result && (n6.result.close(), ln.delete(o3)); var r3 = indexedDB.deleteDatabase(o3); r3.onsuccess = function() { dn.delete(o3), C() && o3 in localStorage && delete localStorage[o3], t8(null, { ok: true }); }, r3.onerror = Qt(t8); }; var g2 = ln.get(o3); if (g2) return a3 = g2.idb, e5._meta = g2.global, s()(function() { n5(null, e5); }); var _2 = indexedDB.open(o3, 5); dn.set(o3, _2), _2.onupgradeneeded = function(e6) { var t8 = e6.target.result; if (e6.oldVersion < 1) return f2(t8); var n6 = e6.currentTarget.transaction; e6.oldVersion < 3 && d2(t8), e6.oldVersion < 4 && p2(t8); var r3 = [l2, h2, v2, y2], i3 = e6.oldVersion; function o4() { var e7 = r3[i3 - 1]; i3++, e7 && e7(n6, o4); } o4(); }, _2.onsuccess = function(t8) { (a3 = t8.target.result).onversionchange = function() { a3.close(), ln.delete(o3); }, a3.onabort = function(e6) { L("error", "Database has a global failure", e6.target.error), u2 = e6.target.error, a3.close(), ln.delete(o3); }; var r3, i3, s2, c3, f3 = a3.transaction([zt, Kt, Nt], "readwrite"), l3 = false; function d3() { s2 !== void 0 && l3 && (e5._meta = { name: o3, instanceId: c3, blobSupport: s2 }, ln.set(o3, { idb: a3, global: e5._meta }), n5(null, e5)); } function h3() { if (i3 !== void 0 && r3 !== void 0) { var e6 = o3 + "_id"; e6 in r3 ? c3 = r3[e6] : r3[e6] = c3 = Ee(), r3.docCount = i3, f3.objectStore(zt).put(r3); } } f3.objectStore(zt).get(zt).onsuccess = function(e6) { r3 = e6.target.result || { id: zt }, h3(); }, function(e6, t9) { e6.objectStore(Nt).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess = function(e7) { t9(e7.target.result); }; }(f3, function(e6) { i3 = e6, h3(); }), fn || (fn = function(e6) { return new Promise(function(t9) { var n6 = ge([""]), r4 = e6.objectStore(Kt).put(n6, "key"); r4.onsuccess = function() { var e7 = navigator.userAgent.match(/Chrome\/(\d+)/), n7 = navigator.userAgent.match(/Edge\//); t9(n7 || !e7 || parseInt(e7[1], 10) >= 43); }, r4.onerror = e6.onabort = function(e7) { e7.preventDefault(), e7.stopPropagation(), t9(false); }; }).catch(function() { return false; }); }(f3)), fn.then(function(e6) { s2 = e6, d3(); }), f3.oncomplete = function() { l3 = true, d3(); }, f3.onabort = Qt(n5); }, _2.onerror = function(e6) { var t8 = e6.target.error && e6.target.error.message; t8 ? t8.indexOf("stored database is a higher version") !== -1 && (t8 = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter')) : t8 = "Failed to open indexedDB, are you in private browsing mode?", L("error", t8), n5(ee(X, t8)); }; }(n4, e4, t6); }), cn(); }(0, t4, n4.constructor); } hn.valid = function() { try { return typeof indexedDB != "undefined" && typeof IDBKeyRange != "undefined"; } catch (e4) { return false; } }; var pn = 5e3, vn = {}; function yn(e4) { var t4 = e4.doc || e4.ok, n4 = t4 && t4._attachments; n4 && Object.keys(n4).forEach(function(e5) { var t5 = n4[e5]; t5.data = be(t5.data, t5.content_type); }); } function gn(e4) { return /^_design/.test(e4) ? "_design/" + encodeURIComponent(e4.slice(8)) : /^_local/.test(e4) ? "_local/" + encodeURIComponent(e4.slice(7)) : encodeURIComponent(e4); } function _n(e4) { return e4._attachments && Object.keys(e4._attachments) ? Promise.all(Object.keys(e4._attachments).map(function(t4) { var n4 = e4._attachments[t4]; if (n4.data && typeof n4.data != "string") return new Promise(function(e5) { je(n4.data, e5); }).then(function(e5) { n4.data = e5; }); })) : Promise.resolve(); } function mn(e4, t4) { return bn(e4, e4.db + "/" + t4); } function bn(e4, t4) { var n4 = e4.path ? "/" : ""; return e4.protocol + "://" + e4.host + (e4.port ? ":" + e4.port : "") + "/" + e4.path + n4 + t4; } function wn(e4) { return "?" + Object.keys(e4).map(function(t4) { return t4 + "=" + encodeURIComponent(e4[t4]); }).join("&"); } function kn(e4, t4) { var n4 = this, r3 = function(e5, t5) { if (function(e6) { if (!e6.prefix) return false; var t6 = de(e6.prefix).protocol; return t6 === "http" || t6 === "https"; }(t5)) { var n5 = t5.name.substr(t5.prefix.length); e5 = t5.prefix.replace(/\/?$/, "/") + encodeURIComponent(n5); } var r4 = de(e5); (r4.user || r4.password) && (r4.auth = { username: r4.user, password: r4.password }); var i4 = r4.path.replace(/(^\/|\/$)/g, "").split("/"); return r4.db = i4.pop(), r4.db.indexOf("%") === -1 && (r4.db = encodeURIComponent(r4.db)), r4.path = i4.join("/"), r4; }(e4.name, e4), i3 = mn(r3, ""); e4 = O(e4); var o2, a2 = function(t5, n5) { if ((n5 = n5 || {}).headers = n5.headers || new it(), n5.credentials = "include", e4.auth || r3.auth) { var i4 = e4.auth || r3.auth, o3 = i4.username + ":" + i4.password, s2 = ye(unescape(encodeURIComponent(o3))); n5.headers.set("Authorization", "Basic " + s2); } var a3 = e4.headers || {}; return Object.keys(a3).forEach(function(e5) { n5.headers.append(e5, a3[e5]); }), function(e5) { var t6 = typeof navigator != "undefined" && navigator.userAgent ? navigator.userAgent.toLowerCase() : "", n6 = t6.indexOf("msie") !== -1, r4 = t6.indexOf("trident") !== -1, i5 = t6.indexOf("edge") !== -1, o4 = !("method" in e5) || e5.method === "GET"; return (n6 || r4 || i5) && o4; }(n5) && (t5 += (t5.indexOf("?") === -1 ? "?" : "&") + "_nonce=" + Date.now()), (e4.fetch || rt)(t5, n5); }; function u2(e5, t5) { return q(e5, d()(function(e6) { f2().then(function() { return t5.apply(this, e6); }).catch(function(t6) { e6.pop()(t6); }); })).bind(n4); } function c2(e5, t5, n5) { var r4 = {}; return (t5 = t5 || {}).headers = t5.headers || new it(), t5.headers.get("Content-Type") || t5.headers.set("Content-Type", "application/json"), t5.headers.get("Accept") || t5.headers.set("Accept", "application/json"), a2(e5, t5).then(function(e6) { return r4.ok = e6.ok, r4.status = e6.status, e6.json(); }).then(function(e6) { if (r4.data = e6, !r4.ok) { r4.data.status = r4.status; var t6 = te(r4.data); if (n5) return n5(t6); throw t6; } if (Array.isArray(r4.data) && (r4.data = r4.data.map(function(e7) { return e7.error || e7.missing ? te(e7) : e7; })), !n5) return r4; n5(null, r4.data); }); } function f2() { return e4.skip_setup ? Promise.resolve() : o2 || ((o2 = c2(i3).catch(function(e5) { return e5 && e5.status && e5.status === 404 ? (I(404, "PouchDB is just detecting if the remote exists."), c2(i3, { method: "PUT" })) : Promise.reject(e5); }).catch(function(e5) { return !(!e5 || !e5.status || e5.status !== 412) || Promise.reject(e5); })).catch(function() { o2 = null; }), o2); } function l2(e5) { return e5.split("/").map(encodeURIComponent).join("/"); } s()(function() { t4(null, n4); }), n4._remote = true, n4.type = function() { return "http"; }, n4.id = u2("id", function(e5) { a2(bn(r3, "")).then(function(e6) { return e6.json(); }).catch(function() { return {}; }).then(function(t5) { var n5 = t5 && t5.uuid ? t5.uuid + r3.db : mn(r3, ""); e5(null, n5); }); }), n4.compact = u2("compact", function(e5, t5) { typeof e5 == "function" && (t5 = e5, e5 = {}), e5 = O(e5), c2(mn(r3, "_compact"), { method: "POST" }).then(function() { !function r4() { n4.info(function(n5, i4) { i4 && !i4.compact_running ? t5(null, { ok: true }) : setTimeout(r4, e5.interval || 200); }); }(); }); }), n4.bulkGet = q("bulkGet", function(e5, t5) { var n5 = this; function i4(t6) { var n6 = {}; e5.revs && (n6.revs = true), e5.attachments && (n6.attachments = true), e5.latest && (n6.latest = true), c2(mn(r3, "_bulk_get" + wn(n6)), { method: "POST", body: JSON.stringify({ docs: e5.docs }) }).then(function(n7) { e5.attachments && e5.binary && n7.data.results.forEach(function(e6) { e6.docs.forEach(yn); }), t6(null, n7.data); }).catch(t6); } function o3() { var r4 = Math.ceil(e5.docs.length / 50), i5 = 0, o4 = new Array(r4); function s3(e6) { return function(n6, s4) { o4[e6] = s4.results, ++i5 === r4 && t5(null, { results: re(o4) }); }; } for (var a4 = 0; a4 < r4; a4++) { var u3 = A(e5, ["revs", "attachments", "binary", "latest"]); u3.docs = e5.docs.slice(50 * a4, Math.min(e5.docs.length, 50 * (a4 + 1))), P(n5, u3, s3(a4)); } } var s2 = bn(r3, ""), a3 = vn[s2]; typeof a3 != "boolean" ? i4(function(e6, n6) { e6 ? (vn[s2] = false, I(e6.status, "PouchDB is just detecting if the remote supports the _bulk_get API."), o3()) : (vn[s2] = true, t5(null, n6)); }) : a3 ? i4(t5) : o3(); }), n4._info = function(e5) { f2().then(function() { return a2(mn(r3, "")); }).then(function(e6) { return e6.json(); }).then(function(t5) { t5.host = mn(r3, ""), e5(null, t5); }).catch(e5); }, n4.fetch = function(e5, t5) { return f2().then(function() { var n5 = e5.substring(0, 1) === "/" ? bn(r3, e5.substring(1)) : mn(r3, e5); return a2(n5, t5); }); }, n4.get = u2("get", function(e5, t5, n5) { typeof t5 == "function" && (n5 = t5, t5 = {}); var i4 = {}; function o3(e6) { var n6, i5 = e6._attachments, o4 = i5 && Object.keys(i5); if (i5 && o4.length) return n6 = o4.map(function(n7) { return function() { return function(n8) { var o5 = i5[n8], s2 = gn(e6._id) + "/" + l2(n8) + "?rev=" + e6._rev; return a2(mn(r3, s2)).then(function(e7) { return "buffer" in e7 ? e7.buffer() : e7.blob(); }).then(function(e7) { if (t5.binary) { var n9 = Object.getOwnPropertyDescriptor(e7.__proto__, "type"); return n9 && !n9.set || (e7.type = o5.content_type), e7; } return new Promise(function(t6) { je(e7, t6); }); }).then(function(e7) { delete o5.stub, delete o5.length, o5.data = e7; }); }(n7); }; }), new Promise(function(e7, t6) { var r4, i6 = 0, o5 = 0, s2 = 0, a3 = n6.length; function u3() { ++s2 === a3 ? r4 ? t6(r4) : e7() : l3(); } function c3() { i6--, u3(); } function f3(e8) { i6--, r4 = r4 || e8, u3(); } function l3() { for (; i6 < 5 && o5 < a3; ) i6++, n6[o5++]().then(c3, f3); } l3(); }); } (t5 = O(t5)).revs && (i4.revs = true), t5.revs_info && (i4.revs_info = true), t5.latest && (i4.latest = true), t5.open_revs && (t5.open_revs !== "all" && (t5.open_revs = JSON.stringify(t5.open_revs)), i4.open_revs = t5.open_revs), t5.rev && (i4.rev = t5.rev), t5.conflicts && (i4.conflicts = t5.conflicts), t5.update_seq && (i4.update_seq = t5.update_seq), e5 = gn(e5), c2(mn(r3, e5 + wn(i4))).then(function(e6) { return Promise.resolve().then(function() { if (t5.attachments) return n6 = e6.data, Array.isArray(n6) ? Promise.all(n6.map(function(e7) { if (e7.ok) return o3(e7.ok); })) : o3(n6); var n6; }).then(function() { n5(null, e6.data); }); }).catch(function(t6) { t6.docId = e5, n5(t6); }); }), n4.remove = u2("remove", function(e5, t5, n5, i4) { var o3; typeof t5 == "string" ? (o3 = { _id: e5, _rev: t5 }, typeof n5 == "function" && (i4 = n5, n5 = {})) : (o3 = e5, typeof t5 == "function" ? (i4 = t5, n5 = {}) : (i4 = n5, n5 = t5)); var s2 = o3._rev || n5.rev; c2(mn(r3, gn(o3._id)) + "?rev=" + s2, { method: "DELETE" }, i4).catch(i4); }), n4.getAttachment = u2("getAttachment", function(e5, t5, n5, i4) { typeof n5 == "function" && (i4 = n5, n5 = {}); var o3, s2 = n5.rev ? "?rev=" + n5.rev : "", u3 = mn(r3, gn(e5)) + "/" + l2(t5) + s2; a2(u3, { method: "GET" }).then(function(e6) { if (o3 = e6.headers.get("content-type"), e6.ok) return typeof process == "undefined" || process.browser || typeof e6.buffer != "function" ? e6.blob() : e6.buffer(); throw e6; }).then(function(e6) { typeof process == "undefined" || process.browser || (e6.type = o3), i4(null, e6); }).catch(function(e6) { i4(e6); }); }), n4.removeAttachment = u2("removeAttachment", function(e5, t5, n5, i4) { c2(mn(r3, gn(e5) + "/" + l2(t5)) + "?rev=" + n5, { method: "DELETE" }, i4).catch(i4); }), n4.putAttachment = u2("putAttachment", function(e5, t5, n5, i4, o3, s2) { typeof o3 == "function" && (s2 = o3, o3 = i4, i4 = n5, n5 = null); var a3 = gn(e5) + "/" + l2(t5), u3 = mn(r3, a3); if (n5 && (u3 += "?rev=" + n5), typeof i4 == "string") { var f3; try { f3 = ve(i4); } catch (e6) { return s2(ee(V, "Attachment is not a valid base64 string")); } i4 = f3 ? me(f3, o3) : ""; } c2(u3, { headers: new it({ "Content-Type": o3 }), method: "PUT", body: i4 }, s2).catch(s2); }), n4._bulkDocs = function(e5, t5, n5) { e5.new_edits = t5.new_edits, f2().then(function() { return Promise.all(e5.docs.map(_n)); }).then(function() { return c2(mn(r3, "_bulk_docs"), { method: "POST", body: JSON.stringify(e5) }, n5); }).catch(n5); }, n4._put = function(e5, t5, n5) { f2().then(function() { return _n(e5); }).then(function() { return c2(mn(r3, gn(e5._id)), { method: "PUT", body: JSON.stringify(e5) }); }).then(function(e6) { n5(null, e6.data); }).catch(function(t6) { t6.docId = e5 && e5._id, n5(t6); }); }, n4.allDocs = u2("allDocs", function(e5, t5) { typeof e5 == "function" && (t5 = e5, e5 = {}); var n5, i4 = {}, o3 = "GET"; (e5 = O(e5)).conflicts && (i4.conflicts = true), e5.update_seq && (i4.update_seq = true), e5.descending && (i4.descending = true), e5.include_docs && (i4.include_docs = true), e5.attachments && (i4.attachments = true), e5.key && (i4.key = JSON.stringify(e5.key)), e5.start_key && (e5.startkey = e5.start_key), e5.startkey && (i4.startkey = JSON.stringify(e5.startkey)), e5.end_key && (e5.endkey = e5.end_key), e5.endkey && (i4.endkey = JSON.stringify(e5.endkey)), e5.inclusive_end !== void 0 && (i4.inclusive_end = !!e5.inclusive_end), e5.limit !== void 0 && (i4.limit = e5.limit), e5.skip !== void 0 && (i4.skip = e5.skip); var s2 = wn(i4); e5.keys !== void 0 && (o3 = "POST", n5 = { keys: e5.keys }), c2(mn(r3, "_all_docs" + s2), { method: o3, body: JSON.stringify(n5) }).then(function(n6) { e5.include_docs && e5.attachments && e5.binary && n6.data.rows.forEach(yn), t5(null, n6.data); }).catch(t5); }), n4._changes = function(e5) { var t5 = "batch_size" in e5 ? e5.batch_size : 25; (e5 = O(e5)).continuous && !("heartbeat" in e5) && (e5.heartbeat = 1e4); var n5 = "timeout" in e5 ? e5.timeout : 3e4; "timeout" in e5 && e5.timeout && n5 - e5.timeout < pn && (n5 = e5.timeout + pn), "heartbeat" in e5 && e5.heartbeat && n5 - e5.heartbeat < pn && (n5 = e5.heartbeat + pn); var i4 = {}; "timeout" in e5 && e5.timeout && (i4.timeout = e5.timeout); var o3 = e5.limit !== void 0 && e5.limit, a3 = o3; if (e5.style && (i4.style = e5.style), (e5.include_docs || e5.filter && typeof e5.filter == "function") && (i4.include_docs = true), e5.attachments && (i4.attachments = true), e5.continuous && (i4.feed = "longpoll"), e5.seq_interval && (i4.seq_interval = e5.seq_interval), e5.conflicts && (i4.conflicts = true), e5.descending && (i4.descending = true), e5.update_seq && (i4.update_seq = true), "heartbeat" in e5 && e5.heartbeat && (i4.heartbeat = e5.heartbeat), e5.filter && typeof e5.filter == "string" && (i4.filter = e5.filter), e5.view && typeof e5.view == "string" && (i4.filter = "_view", i4.view = e5.view), e5.query_params && typeof e5.query_params == "object") for (var u3 in e5.query_params) Object.prototype.hasOwnProperty.call(e5.query_params, u3) && (i4[u3] = e5.query_params[u3]); var l3, d2 = "GET"; e5.doc_ids ? (i4.filter = "_doc_ids", d2 = "POST", l3 = { doc_ids: e5.doc_ids }) : e5.selector && (i4.filter = "_selector", d2 = "POST", l3 = { selector: e5.selector }); var h2, p2 = new nt(), v2 = function(n6, s2) { if (!e5.aborted) { i4.since = n6, typeof i4.since == "object" && (i4.since = JSON.stringify(i4.since)), e5.descending ? o3 && (i4.limit = a3) : i4.limit = !o3 || a3 > t5 ? t5 : a3; var u4 = mn(r3, "_changes" + wn(i4)), v3 = { signal: p2.signal, method: d2, body: JSON.stringify(l3) }; h2 = n6, e5.aborted || f2().then(function() { return c2(u4, v3, s2); }).catch(s2); } }, y2 = { results: [] }, g2 = function(n6, r4) { if (!e5.aborted) { var i5 = 0; if (r4 && r4.results) { i5 = r4.results.length, y2.last_seq = r4.last_seq; var u4 = null, c3 = null; typeof r4.pending == "number" && (u4 = r4.pending), typeof y2.last_seq != "string" && typeof y2.last_seq != "number" || (c3 = y2.last_seq), e5.query_params, r4.results = r4.results.filter(function(t6) { a3--; var n7 = ne(e5)(t6); return n7 && (e5.include_docs && e5.attachments && e5.binary && yn(t6), e5.return_docs && y2.results.push(t6), e5.onChange(t6, u4, c3)), n7; }); } else if (n6) return e5.aborted = true, void e5.complete(n6); r4 && r4.last_seq && (h2 = r4.last_seq); var f3 = o3 && a3 <= 0 || r4 && i5 < t5 || e5.descending; (!e5.continuous || o3 && a3 <= 0) && f3 ? e5.complete(null, y2) : s()(function() { v2(h2, g2); }); } }; return v2(e5.since || 0, g2), { cancel: function() { e5.aborted = true, p2.abort(); } }; }, n4.revsDiff = u2("revsDiff", function(e5, t5, n5) { typeof t5 == "function" && (n5 = t5, t5 = {}), c2(mn(r3, "_revs_diff"), { method: "POST", body: JSON.stringify(e5) }, n5).catch(n5); }), n4._close = function(e5) { e5(); }, n4._destroy = function(e5, t5) { c2(mn(r3, ""), { method: "DELETE" }).then(function(e6) { t5(null, e6); }).catch(function(e6) { e6.status === 404 ? t5(null, { ok: true }) : t5(e6); }); }; } function jn(e4) { this.status = 400, this.name = "query_parse_error", this.message = e4, this.error = true; try { Error.captureStackTrace(this, jn); } catch (e5) { } } function On(e4) { this.status = 404, this.name = "not_found", this.message = e4, this.error = true; try { Error.captureStackTrace(this, On); } catch (e5) { } } function $n(e4) { this.status = 500, this.name = "invalid_value", this.message = e4, this.error = true; try { Error.captureStackTrace(this, $n); } catch (e5) { } } function xn(e4, t4) { return t4 && e4.then(function(e5) { s()(function() { t4(null, e5); }); }, function(e5) { s()(function() { t4(e5); }); }), e4; } function qn(e4, t4) { return function() { var n4 = arguments, r3 = this; return e4.add(function() { return t4.apply(r3, n4); }); }; } function An(e4) { var t4 = new r2(e4), n4 = new Array(t4.size), i3 = -1; return t4.forEach(function(e5) { n4[++i3] = e5; }), n4; } function Sn(e4) { var t4 = new Array(e4.size), n4 = -1; return e4.forEach(function(e5, r3) { t4[++n4] = r3; }), t4; } function En(e4) { return new $n("builtin " + e4 + " function requires map values to be numbers or number arrays"); } function Pn(e4) { for (var t4 = 0, n4 = 0, r3 = e4.length; n4 < r3; n4++) { var i3 = e4[n4]; if (typeof i3 != "number") { if (!Array.isArray(i3)) throw En("_sum"); t4 = typeof t4 == "number" ? [t4] : t4; for (var o2 = 0, s2 = i3.length; o2 < s2; o2++) { var a2 = i3[o2]; if (typeof a2 != "number") throw En("_sum"); t4[o2] === void 0 ? t4.push(a2) : t4[o2] += a2; } } else typeof t4 == "number" ? t4 += i3 : t4[0] += i3; } return t4; } kn.valid = function() { return true; }, p()(jn, Error), p()(On, Error), p()($n, Error); var Cn = L.bind(null, "log"), Dn = Array.isArray, Ln = JSON.parse; function Bn(e4, t4) { return he("return (" + e4.replace(/;\s*$/, "") + ");", { emit: t4, sum: Pn, log: Cn, isArray: Dn, toJSON: Ln }); } function In() { this.promise = new Promise(function(e4) { e4(); }); } function Tn(e4) { if (!e4) return "undefined"; switch (typeof e4) { case "function": case "string": return e4.toString(); default: return JSON.stringify(e4); } } function Mn(e4, t4, n4, r3, i3, o2) { var s2, a2 = function(e5, t5) { return Tn(e5) + Tn(t5) + "undefined"; }(n4, r3); if (!i3 && (s2 = e4._cachedViews = e4._cachedViews || {})[a2]) return s2[a2]; var u2 = e4.info().then(function(u3) { var c2 = u3.db_name + "-mrview-" + (i3 ? "temp" : Ae(a2)); return pe(e4, "_local/" + o2, function(e5) { e5.views = e5.views || {}; var n5 = t4; n5.indexOf("/") === -1 && (n5 = t4 + "/" + t4); var r4 = e5.views[n5] = e5.views[n5] || {}; if (!r4[c2]) return r4[c2] = true, e5; }).then(function() { return e4.registerDependentDatabase(c2).then(function(t5) { var i4 = t5.db; i4.auto_compaction = true; var o3 = { name: c2, db: i4, sourceDB: e4, adapter: e4.adapter, mapFun: n4, reduceFun: r3 }; return o3.db.get("_local/lastSeq").catch(function(e5) { if (e5.status !== 404) throw e5; }).then(function(e5) { return o3.seq = e5 ? e5.seq : 0, s2 && o3.db.once("destroyed", function() { delete s2[a2]; }), o3; }); }); }); }); return s2 && (s2[a2] = u2), u2; } In.prototype.add = function(e4) { return this.promise = this.promise.catch(function() { }).then(function() { return e4(); }), this.promise; }, In.prototype.finish = function() { return this.promise; }; var Nn = {}, Rn = new In(); function Fn(e4) { return e4.indexOf("/") === -1 ? [e4, e4] : e4.split("/"); } function Un(e4, t4) { try { e4.emit("error", t4); } catch (e5) { L("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."), L("error", t4); } } var zn = function(e4, t4) { return Pn(t4); }, Jn = function(e4, t4) { return t4.length; }, Kn = function(e4, t4) { return { sum: Pn(t4), min: Math.min.apply(null, t4), max: Math.max.apply(null, t4), count: t4.length, sumsqr: function(e5) { for (var t5 = 0, n4 = 0, r3 = e5.length; n4 < r3; n4++) { var i3 = e5[n4]; t5 += i3 * i3; } return t5; }(t4) }; }, Vn = function(e4, t4, n4, o2) { function a2(e5, t5, n5) { try { t5(n5); } catch (t6) { Un(e5, t6); } } function u2(e5, t5, n5, r3, i3) { try { return { output: t5(n5, r3, i3) }; } catch (t6) { return Un(e5, t6), { error: t6 }; } } function c2(e5, t5) { var n5 = vt(e5.key, t5.key); return n5 !== 0 ? n5 : vt(e5.value, t5.value); } function f2(e5, t5, n5) { return n5 = n5 || 0, typeof t5 == "number" ? e5.slice(n5, t5 + n5) : n5 > 0 ? e5.slice(n5) : e5; } function l2(e5) { var t5 = e5.value; return t5 && typeof t5 == "object" && t5._id || e5.id; } function h2(e5) { return function(t5) { return e5.include_docs && e5.attachments && e5.binary && function(e6) { e6.rows.forEach(function(e7) { var t6 = e7.doc && e7.doc._attachments; t6 && Object.keys(t6).forEach(function(e8) { var n5 = t6[e8]; t6[e8].data = be(n5.data, n5.content_type); }); }); }(t5), t5; }; } function p2(e5, t5, n5, r3) { var i3 = t5[e5]; i3 !== void 0 && (r3 && (i3 = encodeURIComponent(JSON.stringify(i3))), n5.push(e5 + "=" + i3)); } function v2(e5) { if (e5 !== void 0) { var t5 = Number(e5); return isNaN(t5) || t5 !== parseInt(e5, 10) ? e5 : t5; } } function y2(e5, t5) { var n5 = e5.descending ? "endkey" : "startkey", r3 = e5.descending ? "startkey" : "endkey"; if (e5[n5] !== void 0 && e5[r3] !== void 0 && vt(e5[n5], e5[r3]) > 0) throw new jn("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); if (t5.reduce && e5.reduce !== false) { if (e5.include_docs) throw new jn("{include_docs:true} is invalid for reduce"); if (e5.keys && e5.keys.length > 1 && !e5.group && !e5.group_level) throw new jn("Multi-key fetches for reduce views must use {group: true}"); } ["group_level", "limit", "skip"].forEach(function(t6) { var n6 = function(e6) { if (e6) { if (typeof e6 != "number") return new jn('Invalid value for integer: "' + e6 + '"'); if (e6 < 0) return new jn('Invalid value for positive integer: "' + e6 + '"'); } }(e5[t6]); if (n6) throw n6; }); } function g2(e5) { return function(t5) { if (t5.status === 404) return e5; throw t5; }; } function _2(e5) { var t5 = typeof e5 == "string" ? e5 : e5.name, n5 = Nn[t5]; return n5 || (n5 = Nn[t5] = new In()), n5; } function m2(e5, t5) { return qn(_2(e5), function() { return function(e6, t6) { var n5, o3; var s2 = function(e7, t7) { if (typeof e7 == "function" && e7.length === 2) { var n6 = e7; return function(e8) { return n6(e8, t7); }; } return Bn(e7.toString(), t7); }(e6.mapFun, function(e7, t7) { var r3 = { id: o3._id, key: yt(e7) }; t7 != null && (r3.value = yt(t7)), n5.push(r3); }), u3 = e6.seq || 0; function f3(t7, n6) { return function() { return function(e7, t8, n7) { var i3 = "_local/lastSeq"; return e7.db.get(i3).catch(g2({ _id: i3, seq: 0 })).then(function(i4) { var o4 = Sn(t8); return Promise.all(o4.map(function(n8) { return function(e8, t9, n9) { var i5 = "_local/doc_" + e8, o5 = { _id: i5, keys: [] }, s3 = n9.get(e8), a3 = s3[0]; return (function(e9) { return e9.length === 1 && /^1-/.test(e9[0].rev); }(s3[1]) ? Promise.resolve(o5) : t9.db.get(i5).catch(g2(o5))).then(function(e9) { return function(e10) { return e10.keys.length ? t9.db.allDocs({ keys: e10.keys, include_docs: true }) : Promise.resolve({ rows: [] }); }(e9).then(function(t10) { return function(e10, t11) { for (var n10 = [], i6 = new r2(), o6 = 0, s4 = t11.rows.length; o6 < s4; o6++) { var u4 = t11.rows[o6].doc; if (u4 && (n10.push(u4), i6.add(u4._id), u4._deleted = !a3.has(u4._id), !u4._deleted)) { var c3 = a3.get(u4._id); "value" in c3 && (u4.value = c3.value); } } var f4 = Sn(a3); return f4.forEach(function(e11) { if (!i6.has(e11)) { var t12 = { _id: e11 }, r3 = a3.get(e11); "value" in r3 && (t12.value = r3.value), n10.push(t12); } }), e10.keys = An(f4.concat(e10.keys)), n10.push(e10), n10; }(e9, t10); }); }); }(n8, e7, t8); })).then(function(t9) { var r3 = re(t9); return i4.seq = n7, r3.push(i4), e7.db.bulkDocs({ docs: r3 }); }); }); }(e6, t7, n6); }; } let l3 = 0, d2 = { view: e6.name, indexed_docs: l3 }; e6.sourceDB.emit("indexing", d2); var h3 = new In(); function p3() { return e6.sourceDB.changes({ return_docs: true, conflicts: true, include_docs: true, style: "all_docs", since: u3, limit: t6.changes_batch_size }).then(v3); } function v3(r3) { var d3 = r3.results; if (!d3.length) return; var v4 = function(t7) { for (var r4 = new i2(), f4 = 0, l4 = t7.length; f4 < l4; f4++) { var d4 = t7[f4]; if (d4.doc._id[0] !== "_") { n5 = [], (o3 = d4.doc)._deleted || a2(e6.sourceDB, s2, o3), n5.sort(c2); var h4 = y3(n5); r4.set(d4.doc._id, [h4, d4.changes]); } u3 = d4.seq; } return r4; }(d3); h3.add(f3(v4, u3)), l3 += d3.length; let g3 = { view: e6.name, last_seq: r3.last_seq, results_count: d3.length, indexed_docs: l3 }; return e6.sourceDB.emit("indexing", g3), d3.length < t6.changes_batch_size ? void 0 : p3(); } function y3(e7) { for (var t7, n6 = new i2(), r3 = 0, o4 = e7.length; r3 < o4; r3++) { var s3 = e7[r3], a3 = [s3.key, s3.id]; r3 > 0 && vt(s3.key, t7) === 0 && a3.push(r3), n6.set(gt(a3), s3), t7 = s3.key; } return n6; } return p3().then(function() { return h3.finish(); }).then(function() { e6.seq = u3; }); }(e5, t5); })(); } function b2(e5, t5) { return qn(_2(e5), function() { return function(e6, t6) { var n5, r3 = e6.reduceFun && t6.reduce !== false, o3 = t6.skip || 0; function s2(t7) { return t7.include_docs = true, e6.db.allDocs(t7).then(function(e7) { return n5 = e7.total_rows, e7.rows.map(function(e8) { if ("value" in e8.doc && typeof e8.doc.value == "object" && e8.doc.value !== null) { var t8 = Object.keys(e8.doc.value).sort(), n6 = ["id", "key", "value"]; if (!(t8 < n6 || t8 > n6)) return e8.doc.value; } var r4 = function(e9) { for (var t9 = [], n7 = [], r5 = 0; ; ) { var i3 = e9[r5++]; if (i3 !== "\0") switch (i3) { case "1": t9.push(null); break; case "2": t9.push(e9[r5] === "1"), r5++; break; case "3": var o4 = _t(e9, r5); t9.push(o4.num), r5 += o4.length; break; case "4": for (var s3 = ""; ; ) { var a4 = e9[r5]; if (a4 === "\0") break; s3 += a4, r5++; } s3 = s3.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, ""), t9.push(s3); break; case "5": var u3 = { element: [], index: t9.length }; t9.push(u3.element), n7.push(u3); break; case "6": var c4 = { element: {}, index: t9.length }; t9.push(c4.element), n7.push(c4); break; default: throw new Error("bad collationIndex or unexpectedly reached end of input: " + i3); } else { if (t9.length === 1) return t9.pop(); mt(t9, n7); } } }(e8.doc._id); return { key: r4[0], id: r4[1], value: "value" in e8.doc ? e8.doc.value : null }; }); }); } function a3(s3) { var a4; if (a4 = r3 ? function(e7, t7, n6) { n6.group_level === 0 && delete n6.group_level; var r4 = n6.group || n6.group_level, i3 = function(e8) { var t8 = e8.toString(), n7 = function(e9) { if (/^_sum/.test(e9)) return zn; if (/^_count/.test(e9)) return Jn; if (/^_stats/.test(e9)) return Kn; if (/^_/.test(e9)) throw new Error(e9 + " is not a supported reduce function."); }(t8); return n7 || Bn(t8); }(e7.reduceFun), o4 = [], s4 = isNaN(n6.group_level) ? Number.POSITIVE_INFINITY : n6.group_level; t7.forEach(function(e8) { var t8 = o4[o4.length - 1], n7 = r4 ? e8.key : null; if (r4 && Array.isArray(n7) && (n7 = n7.slice(0, s4)), t8 && vt(t8.groupKey, n7) === 0) return t8.keys.push([e8.key, e8.id]), void t8.values.push(e8.value); o4.push({ keys: [[e8.key, e8.id]], values: [e8.value], groupKey: n7 }); }), t7 = []; for (var a5 = 0, c5 = o4.length; a5 < c5; a5++) { var l3 = o4[a5], d3 = u2(e7.sourceDB, i3, l3.keys, l3.values, false); if (d3.error && d3.error instanceof $n) throw d3.error; t7.push({ value: d3.error ? null : d3.output, key: l3.groupKey }); } return { rows: f2(t7, n6.limit, n6.skip) }; }(e6, s3, t6) : t6.keys === void 0 ? { total_rows: n5, offset: o3, rows: s3 } : { total_rows: n5, offset: o3, rows: f2(s3, t6.limit, t6.skip) }, t6.update_seq && (a4.update_seq = e6.seq), t6.include_docs) { var c4 = An(s3.map(l2)); return e6.sourceDB.allDocs({ keys: c4, include_docs: true, conflicts: t6.conflicts, attachments: t6.attachments, binary: t6.binary }).then(function(e7) { var t7 = new i2(); return e7.rows.forEach(function(e8) { t7.set(e8.id, e8.doc); }), s3.forEach(function(e8) { var n6 = l2(e8), r4 = t7.get(n6); r4 && (e8.doc = r4); }), a4; }); } return a4; } if (t6.keys === void 0 || t6.keys.length || (t6.limit = 0, delete t6.keys), t6.keys !== void 0) { var c3 = t6.keys.map(function(e7) { var n6 = { startkey: gt([e7]), endkey: gt([e7, {}]) }; return t6.update_seq && (n6.update_seq = true), s2(n6); }); return Promise.all(c3).then(re).then(a3); } var d2, h3, p3 = { descending: t6.descending }; if (t6.update_seq && (p3.update_seq = true), "start_key" in t6 && (d2 = t6.start_key), "startkey" in t6 && (d2 = t6.startkey), "end_key" in t6 && (h3 = t6.end_key), "endkey" in t6 && (h3 = t6.endkey), d2 !== void 0 && (p3.startkey = t6.descending ? gt([d2, {}]) : gt([d2])), h3 !== void 0) { var v3 = t6.inclusive_end !== false; t6.descending && (v3 = !v3), p3.endkey = gt(v3 ? [h3, {}] : [h3]); } if (t6.key !== void 0) { var y3 = gt([t6.key]), g3 = gt([t6.key, {}]); p3.descending ? (p3.endkey = y3, p3.startkey = g3) : (p3.startkey = y3, p3.endkey = g3); } return r3 || (typeof t6.limit == "number" && (p3.limit = t6.limit), p3.skip = o3), s2(p3).then(a3); }(e5, t5); })(); } function w2(t5, n5, r3) { if (typeof t5._query == "function") return function(e5, t6, n6) { return new Promise(function(r4, i4) { e5._query(t6, n6, function(e6, t7) { if (e6) return i4(e6); r4(t7); }); }); }(t5, n5, r3); if (oe(t5)) return function(e5, t6, n6) { var r4, i4, o4, s2 = [], a4 = "GET"; if (p2("reduce", n6, s2), p2("include_docs", n6, s2), p2("attachments", n6, s2), p2("limit", n6, s2), p2("descending", n6, s2), p2("group", n6, s2), p2("group_level", n6, s2), p2("skip", n6, s2), p2("stale", n6, s2), p2("conflicts", n6, s2), p2("startkey", n6, s2, true), p2("start_key", n6, s2, true), p2("endkey", n6, s2, true), p2("end_key", n6, s2, true), p2("inclusive_end", n6, s2), p2("key", n6, s2, true), p2("update_seq", n6, s2), s2 = (s2 = s2.join("&")) === "" ? "" : "?" + s2, n6.keys !== void 0) { var u4 = "keys=" + encodeURIComponent(JSON.stringify(n6.keys)); u4.length + s2.length + 1 <= 2e3 ? s2 += (s2[0] === "?" ? "&" : "?") + u4 : (a4 = "POST", typeof t6 == "string" ? r4 = { keys: n6.keys } : t6.keys = n6.keys); } if (typeof t6 == "string") { var c4 = Fn(t6); return e5.fetch("_design/" + c4[0] + "/_view/" + c4[1] + s2, { headers: new it({ "Content-Type": "application/json" }), method: a4, body: JSON.stringify(r4) }).then(function(e6) { return i4 = e6.ok, o4 = e6.status, e6.json(); }).then(function(e6) { if (!i4) throw e6.status = o4, te(e6); return e6.rows.forEach(function(e7) { if (e7.value && e7.value.error && e7.value.error === "builtin_reduce_error") throw new Error(e7.reason); }), e6; }).then(h2(n6)); } return r4 = r4 || {}, Object.keys(t6).forEach(function(e6) { Array.isArray(t6[e6]) ? r4[e6] = t6[e6] : r4[e6] = t6[e6].toString(); }), e5.fetch("_temp_view" + s2, { headers: new it({ "Content-Type": "application/json" }), method: "POST", body: JSON.stringify(r4) }).then(function(e6) { return i4 = e6.ok, o4 = e6.status, e6.json(); }).then(function(e6) { if (!i4) throw e6.status = o4, te(e6); return e6; }).then(h2(n6)); }(t5, n5, r3); var i3 = { changes_batch_size: t5.__opts.view_update_changes_batch_size || 50 }; if (typeof n5 != "string") return y2(r3, n5), Rn.add(function() { return Mn(t5, "temp_view/temp_view", n5.map, n5.reduce, true, e4).then(function(e5) { return t6 = m2(e5, i3).then(function() { return b2(e5, r3); }), n6 = function() { return e5.db.destroy(); }, t6.then(function(e6) { return n6().then(function() { return e6; }); }, function(e6) { return n6().then(function() { throw e6; }); }); var t6, n6; }); }), Rn.finish(); var o3 = n5, a3 = Fn(o3), u3 = a3[0], c3 = a3[1]; return t5.get("_design/" + u3).then(function(n6) { var a4 = n6.views && n6.views[c3]; if (!a4) throw new On("ddoc " + n6._id + " has no view named " + c3); return function(e5, t6) { var n7 = e5.views && e5.views[t6]; if (typeof n7.map != "string") throw new On("ddoc " + e5._id + " has no string view named " + t6 + ", instead found object of type: " + typeof n7.map); }(n6, c3), y2(r3, a4), Mn(t5, o3, a4.map, a4.reduce, false, e4).then(function(e5) { return r3.stale === "ok" || r3.stale === "update_after" ? (r3.stale === "update_after" && s()(function() { m2(e5, i3); }), b2(e5, r3)) : m2(e5, i3).then(function() { return b2(e5, r3); }); }); }); } var k2; return { query: function(e5, t5, n5) { var r3 = this; typeof t5 == "function" && (n5 = t5, t5 = {}), t5 = t5 ? function(e6) { return e6.group_level = v2(e6.group_level), e6.limit = v2(e6.limit), e6.skip = v2(e6.skip), e6; }(t5) : {}, typeof e5 == "function" && (e5 = { map: e5 }); var i3 = Promise.resolve().then(function() { return w2(r3, e5, t5); }); return xn(i3, n5), i3; }, viewCleanup: (k2 = function() { var e5 = this; return typeof e5._viewCleanup == "function" ? function(e6) { return new Promise(function(t5, n5) { e6._viewCleanup(function(e7, r3) { if (e7) return n5(e7); t5(r3); }); }); }(e5) : oe(e5) ? function(e6) { return e6.fetch("_view_cleanup", { headers: new it({ "Content-Type": "application/json" }), method: "POST" }).then(function(e7) { return e7.json(); }); }(e5) : function(e6) { return e6.get("_local/mrviews").then(function(t5) { var n5 = new i2(); Object.keys(t5.views).forEach(function(e7) { var t6 = Fn(e7), i3 = "_design/" + t6[0], o4 = t6[1], s2 = n5.get(i3); s2 || (s2 = new r2(), n5.set(i3, s2)), s2.add(o4); }); var o3 = { keys: Sn(n5), include_docs: true }; return e6.allDocs(o3).then(function(r3) { var i3 = {}; r3.rows.forEach(function(e7) { var r4 = e7.key.substring(8); n5.get(e7.key).forEach(function(n6) { var o5 = r4 + "/" + n6; t5.views[o5] || (o5 = n6); var s2 = Object.keys(t5.views[o5]), a3 = e7.doc && e7.doc.views && e7.doc.views[n6]; s2.forEach(function(e8) { i3[e8] = i3[e8] || a3; }); }); }); var o4 = Object.keys(i3).filter(function(e7) { return !i3[e7]; }).map(function(t6) { return qn(_2(t6), function() { return new e6.constructor(t6, e6.__opts).destroy(); })(); }); return Promise.all(o4).then(function() { return { ok: true }; }); }); }, g2({ ok: true })); }(e5); }, d()(function(e5) { var t5 = e5.pop(), n5 = k2.apply(this, e5); return typeof t5 == "function" && xn(n5, t5), n5; })) }; }("mrviews"), Qn = { query: function(e4, t4, n4) { return Vn.query.call(this, e4, t4, n4); }, viewCleanup: function(e4) { return Vn.viewCleanup.call(this, e4); } }; function Gn(e4) { return /^1-/.test(e4); } function Wn(e4, t4) { var n4 = Object.keys(t4._attachments); return Promise.all(n4.map(function(n5) { return e4.getAttachment(t4._id, n5, { rev: t4._rev }); })); } function Zn(e4, t4, n4, r3) { n4 = O(n4); var i3 = [], o2 = true; return Promise.resolve().then(function() { var t5 = Object.keys(n4).filter(function(e5) { var t6 = n4[e5].missing; return t6.length === 1 && Gn(t6[0]); }); if (t5.length > 0) return function(t6) { return e4.allDocs({ keys: t6, include_docs: true, conflicts: true }).then(function(e5) { if (r3.cancelled) throw new Error("cancelled"); e5.rows.forEach(function(e6) { var t7; e6.deleted || !e6.doc || !Gn(e6.value.rev) || (t7 = e6.doc)._attachments && Object.keys(t7._attachments).length > 0 || function(e7) { return e7._conflicts && e7._conflicts.length > 0; }(e6.doc) || (e6.doc._conflicts && delete e6.doc._conflicts, i3.push(e6.doc), delete n4[e6.id]); }); }); }(t5); }).then(function() { var s2 = function(e5) { var t5 = []; return Object.keys(e5).forEach(function(n5) { e5[n5].missing.forEach(function(e6) { t5.push({ id: n5, rev: e6 }); }); }), { docs: t5, revs: true, latest: true }; }(n4); if (s2.docs.length) return e4.bulkGet(s2).then(function(n5) { if (r3.cancelled) throw new Error("cancelled"); return Promise.all(n5.results.map(function(n6) { return Promise.all(n6.docs.map(function(n7) { var r4 = n7.ok; return n7.error && (o2 = false), r4 && r4._attachments ? function(e5, t5, n8) { var r5 = oe(t5) && !oe(e5), i4 = Object.keys(n8._attachments); return r5 ? e5.get(n8._id).then(function(r6) { return Promise.all(i4.map(function(i5) { return function(e6, t6, n9) { return !e6._attachments || !e6._attachments[n9] || e6._attachments[n9].digest !== t6._attachments[n9].digest; }(r6, n8, i5) ? t5.getAttachment(n8._id, i5) : e5.getAttachment(r6._id, i5); })); }).catch(function(e6) { if (e6.status !== 404) throw e6; return Wn(t5, n8); }) : Wn(t5, n8); }(t4, e4, r4).then(function(e5) { var t5 = Object.keys(r4._attachments); return e5.forEach(function(e6, n8) { var i4 = r4._attachments[t5[n8]]; delete i4.stub, delete i4.length, i4.data = e6; }), r4; }) : r4; })); })).then(function(e5) { i3 = i3.concat(re(e5).filter(Boolean)); }); }); }).then(function() { return { ok: o2, docs: i3 }; }); } var Xn = "pouchdb"; function Yn(e4, t4, n4, r3, i3) { return e4.get(t4).catch(function(n5) { if (n5.status === 404) return e4.adapter !== "http" && e4.adapter !== "https" || I(404, "PouchDB is just checking if a remote checkpoint exists."), { session_id: r3, _id: t4, history: [], replicator: Xn, version: 1 }; throw n5; }).then(function(o2) { if (!i3.cancelled && o2.last_seq !== n4) return o2.history = (o2.history || []).filter(function(e5) { return e5.session_id !== r3; }), o2.history.unshift({ last_seq: n4, session_id: r3 }), o2.history = o2.history.slice(0, 5), o2.version = 1, o2.replicator = Xn, o2.session_id = r3, o2.last_seq = n4, e4.put(o2).catch(function(o3) { if (o3.status === 409) return Yn(e4, t4, n4, r3, i3); throw o3; }); }); } function Hn(e4, t4, n4, r3, i3) { this.src = e4, this.target = t4, this.id = n4, this.returnValue = r3, this.opts = i3 || {}; } Hn.prototype.writeCheckpoint = function(e4, t4) { var n4 = this; return this.updateTarget(e4, t4).then(function() { return n4.updateSource(e4, t4); }); }, Hn.prototype.updateTarget = function(e4, t4) { return this.opts.writeTargetCheckpoint ? Yn(this.target, this.id, e4, t4, this.returnValue) : Promise.resolve(true); }, Hn.prototype.updateSource = function(e4, t4) { if (this.opts.writeSourceCheckpoint) { var n4 = this; return Yn(this.src, this.id, e4, t4, this.returnValue).catch(function(e5) { if (rr(e5)) return n4.opts.writeSourceCheckpoint = false, true; throw e5; }); } return Promise.resolve(true); }; var er = { undefined: function(e4, t4) { return vt(e4.last_seq, t4.last_seq) === 0 ? t4.last_seq : 0; }, 1: function(e4, t4) { return (n4 = t4, r3 = e4, n4.session_id === r3.session_id ? { last_seq: n4.last_seq, history: n4.history } : tr(n4.history, r3.history)).last_seq; var n4, r3; } }; function tr(e4, t4) { var n4 = e4[0], r3 = e4.slice(1), i3 = t4[0], o2 = t4.slice(1); return n4 && t4.length !== 0 ? nr(n4.session_id, t4) ? { last_seq: n4.last_seq, history: e4 } : nr(i3.session_id, r3) ? { last_seq: i3.last_seq, history: o2 } : tr(r3, o2) : { last_seq: 0, history: [] }; } function nr(e4, t4) { var n4 = t4[0], r3 = t4.slice(1); return !(!e4 || t4.length === 0) && (e4 === n4.session_id || nr(e4, r3)); } function rr(e4) { return typeof e4.status == "number" && Math.floor(e4.status / 100) === 4; } function ir(e4, t4, n4, r3, i3) { var o2, a2, u2, c2 = [], f2 = { seq: 0, changes: [], docs: [] }, l2 = false, d2 = false, h2 = false, p2 = 0, v2 = n4.continuous || n4.live || false, y2 = n4.batch_size || 100, g2 = n4.batches_limit || 10, _2 = n4.style || "all_docs", m2 = false, b2 = n4.doc_ids, w2 = n4.selector, k2 = [], j2 = Ee(); i3 = i3 || { ok: true, start_time: new Date().toISOString(), docs_read: 0, docs_written: 0, doc_write_failures: 0, errors: [] }; var $2 = {}; function x2() { return u2 ? Promise.resolve() : function(e5, t5, n5) { var r4 = n5.doc_ids ? n5.doc_ids.sort(vt) : "", i4 = n5.filter ? n5.filter.toString() : "", o3 = "", s2 = "", a3 = ""; return n5.selector && (a3 = JSON.stringify(n5.selector)), n5.filter && n5.query_params && (o3 = JSON.stringify(function(e6) { return Object.keys(e6).sort(vt).reduce(function(t6, n6) { return t6[n6] = e6[n6], t6; }, {}); }(n5.query_params))), n5.filter && n5.filter === "_view" && (s2 = n5.view.toString()), Promise.all([e5.id(), t5.id()]).then(function(e6) { var t6 = e6[0] + e6[1] + i4 + s2 + o3 + r4 + a3; return new Promise(function(e7) { qe(t6, e7); }); }).then(function(e6) { return "_local/" + e6.replace(/\//g, ".").replace(/\+/g, "_"); }); }(e4, t4, n4).then(function(i4) { a2 = i4; var o3; o3 = n4.checkpoint === false ? { writeSourceCheckpoint: false, writeTargetCheckpoint: false } : n4.checkpoint === "source" ? { writeSourceCheckpoint: true, writeTargetCheckpoint: false } : n4.checkpoint === "target" ? { writeSourceCheckpoint: false, writeTargetCheckpoint: true } : { writeSourceCheckpoint: true, writeTargetCheckpoint: true }, u2 = new Hn(e4, t4, a2, r3, o3); }); } function q2() { if (k2 = [], o2.docs.length !== 0) { var e5 = o2.docs, s2 = { timeout: n4.timeout }; return t4.bulkDocs({ docs: e5, new_edits: false }, s2).then(function(t5) { if (r3.cancelled) throw D2(), new Error("cancelled"); var n5 = Object.create(null); t5.forEach(function(e6) { e6.error && (n5[e6.id] = e6); }); var o3 = Object.keys(n5).length; i3.doc_write_failures += o3, i3.docs_written += e5.length - o3, e5.forEach(function(e6) { var t6 = n5[e6._id]; if (t6) { i3.errors.push(t6); var o4 = (t6.name || "").toLowerCase(); if (o4 !== "unauthorized" && o4 !== "forbidden") throw t6; r3.emit("denied", O(t6)); } else k2.push(e6); }); }, function(t5) { throw i3.doc_write_failures += e5.length, t5; }); } } function A2() { if (o2.error) throw new Error("There was a problem getting docs."); i3.last_seq = p2 = o2.seq; var e5 = O(i3); return k2.length && (e5.docs = k2, typeof o2.pending == "number" && (e5.pending = o2.pending, delete o2.pending), r3.emit("change", e5)), l2 = true, u2.writeCheckpoint(o2.seq, j2).then(function() { if (r3.emit("checkpoint", { checkpoint: o2.seq }), l2 = false, r3.cancelled) throw D2(), new Error("cancelled"); o2 = void 0, M2(); }).catch(function(e6) { throw R2(e6), e6; }); } function S2() { return Zn(e4, t4, o2.diffs, r3).then(function(e5) { o2.error = !e5.ok, e5.docs.forEach(function(e6) { delete o2.diffs[e6._id], i3.docs_read++, o2.docs.push(e6); }); }); } function E2() { var e5; r3.cancelled || o2 || (c2.length !== 0 ? (o2 = c2.shift(), r3.emit("checkpoint", { start_next_batch: o2.seq }), (e5 = {}, o2.changes.forEach(function(t5) { r3.emit("checkpoint", { revs_diff: t5 }), t5.id !== "_user/" && (e5[t5.id] = t5.changes.map(function(e6) { return e6.rev; })); }), t4.revsDiff(e5).then(function(e6) { if (r3.cancelled) throw D2(), new Error("cancelled"); o2.diffs = e6; })).then(S2).then(q2).then(A2).then(E2).catch(function(e6) { C2("batch processing terminated with error", e6); })) : P2(true)); } function P2(e5) { f2.changes.length !== 0 ? (e5 || d2 || f2.changes.length >= y2) && (c2.push(f2), f2 = { seq: 0, changes: [], docs: [] }, r3.state !== "pending" && r3.state !== "stopped" || (r3.state = "active", r3.emit("active")), E2()) : c2.length !== 0 || o2 || ((v2 && $2.live || d2) && (r3.state = "pending", r3.emit("paused")), d2 && D2()); } function C2(e5, t5) { h2 || (t5.message || (t5.message = e5), i3.ok = false, i3.status = "aborting", c2 = [], f2 = { seq: 0, changes: [], docs: [] }, D2(t5)); } function D2(o3) { if (!(h2 || r3.cancelled && (i3.status = "cancelled", l2))) if (i3.status = i3.status || "complete", i3.end_time = new Date().toISOString(), i3.last_seq = p2, h2 = true, o3) { (o3 = ee(o3)).result = i3; var s2 = (o3.name || "").toLowerCase(); s2 === "unauthorized" || s2 === "forbidden" ? (r3.emit("error", o3), r3.removeAllListeners()) : function(e5, t5, n5, r4) { if (e5.retry === false) return t5.emit("error", n5), void t5.removeAllListeners(); if (typeof e5.back_off_function != "function" && (e5.back_off_function = B), t5.emit("requestError", n5), t5.state === "active" || t5.state === "pending") { t5.emit("paused", n5), t5.state = "stopped"; var i4 = function() { e5.current_back_off = 0; }; t5.once("paused", function() { t5.removeListener("active", i4); }), t5.once("active", i4); } e5.current_back_off = e5.current_back_off || 0, e5.current_back_off = e5.back_off_function(e5.current_back_off), setTimeout(r4, e5.current_back_off); }(n4, r3, o3, function() { ir(e4, t4, n4, r3); }); } else r3.emit("complete", i3), r3.removeAllListeners(); } function L2(e5, t5, i4) { if (r3.cancelled) return D2(); typeof t5 == "number" && (f2.pending = t5), ne(n4)(e5) && (f2.seq = e5.seq || i4, f2.changes.push(e5), r3.emit("checkpoint", { pending_batch: f2.seq }), s()(function() { P2(c2.length === 0 && $2.live); })); } function I2(e5) { if (m2 = false, r3.cancelled) return D2(); if (e5.results.length > 0) $2.since = e5.results[e5.results.length - 1].seq, M2(), P2(true); else { var t5 = function() { v2 ? ($2.live = true, M2()) : d2 = true, P2(true); }; o2 || e5.results.length !== 0 ? t5() : (l2 = true, u2.writeCheckpoint(e5.last_seq, j2).then(function() { l2 = false, i3.last_seq = p2 = e5.last_seq, t5(); }).catch(R2)); } } function T2(e5) { if (m2 = false, r3.cancelled) return D2(); C2("changes rejected", e5); } function M2() { if (!m2 && !d2 && c2.length < g2) { m2 = true, r3._changes && (r3.removeListener("cancel", r3._abortChanges), r3._changes.cancel()), r3.once("cancel", i4); var t5 = e4.changes($2).on("change", L2); t5.then(o3, o3), t5.then(I2).catch(T2), n4.retry && (r3._changes = t5, r3._abortChanges = i4); } function i4() { t5.cancel(); } function o3() { r3.removeListener("cancel", i4); } } function N2() { x2().then(function() { if (!r3.cancelled) return u2.getCheckpoint().then(function(e5) { $2 = { since: p2 = e5, limit: y2, batch_size: y2, style: _2, doc_ids: b2, selector: w2, return_docs: true }, n4.filter && (typeof n4.filter != "string" ? $2.include_docs = true : $2.filter = n4.filter), "heartbeat" in n4 && ($2.heartbeat = n4.heartbeat), "timeout" in n4 && ($2.timeout = n4.timeout), n4.query_params && ($2.query_params = n4.query_params), n4.view && ($2.view = n4.view), M2(); }); D2(); }).catch(function(e5) { C2("getCheckpoint rejected with ", e5); }); } function R2(e5) { l2 = false, C2("writeCheckpoint completed with error", e5); } r3.ready(e4, t4), r3.cancelled ? D2() : (r3._addedListeners || (r3.once("cancel", D2), typeof n4.complete == "function" && (r3.once("error", n4.complete), r3.once("complete", function(e5) { n4.complete(null, e5); })), r3._addedListeners = true), n4.since === void 0 ? N2() : x2().then(function() { return l2 = true, u2.writeCheckpoint(n4.since, j2); }).then(function() { l2 = false, r3.cancelled ? D2() : (p2 = n4.since, N2()); }).catch(R2)); } function or() { y().call(this), this.cancelled = false, this.state = "pending"; var e4 = this, t4 = new Promise(function(t5, n4) { e4.once("complete", t5), e4.once("error", n4); }); e4.then = function(e5, n4) { return t4.then(e5, n4); }, e4.catch = function(e5) { return t4.catch(e5); }, e4.catch(function() { }); } function sr(e4, t4) { var n4 = t4.PouchConstructor; return typeof e4 == "string" ? new n4(e4, t4) : e4; } function ar(e4, t4, n4, r3) { if (typeof n4 == "function" && (r3 = n4, n4 = {}), n4 === void 0 && (n4 = {}), n4.doc_ids && !Array.isArray(n4.doc_ids)) throw ee(W, "`doc_ids` filter parameter is not a list."); n4.complete = r3, (n4 = O(n4)).continuous = n4.continuous || n4.live, n4.retry = "retry" in n4 && n4.retry, n4.PouchConstructor = n4.PouchConstructor || this; var i3 = new or(n4); return ir(sr(e4, n4), sr(t4, n4), n4, i3), i3; } function ur(e4, t4, n4, r3) { return typeof n4 == "function" && (r3 = n4, n4 = {}), n4 === void 0 && (n4 = {}), (n4 = O(n4)).PouchConstructor = n4.PouchConstructor || this, new cr(e4 = sr(e4, n4), t4 = sr(t4, n4), n4, r3); } function cr(e4, t4, n4, r3) { var i3 = this; this.canceled = false; var o2 = n4.push ? T({}, n4, n4.push) : n4, s2 = n4.pull ? T({}, n4, n4.pull) : n4; function a2(e5) { i3.emit("change", { direction: "pull", change: e5 }); } function u2(e5) { i3.emit("change", { direction: "push", change: e5 }); } function c2(e5) { i3.emit("denied", { direction: "push", doc: e5 }); } function f2(e5) { i3.emit("denied", { direction: "pull", doc: e5 }); } function l2() { i3.pushPaused = true, i3.pullPaused && i3.emit("paused"); } function d2() { i3.pullPaused = true, i3.pushPaused && i3.emit("paused"); } function h2() { i3.pushPaused = false, i3.pullPaused && i3.emit("active", { direction: "push" }); } function p2() { i3.pullPaused = false, i3.pushPaused && i3.emit("active", { direction: "pull" }); } this.push = ar(e4, t4, o2), this.pull = ar(t4, e4, s2), this.pushPaused = true, this.pullPaused = true; var v2 = {}; function y2(e5) { return function(t5, n5) { (t5 === "change" && (n5 === a2 || n5 === u2) || t5 === "denied" && (n5 === f2 || n5 === c2) || t5 === "paused" && (n5 === d2 || n5 === l2) || t5 === "active" && (n5 === p2 || n5 === h2)) && (t5 in v2 || (v2[t5] = {}), v2[t5][e5] = true, Object.keys(v2[t5]).length === 2 && i3.removeAllListeners(t5)); }; } function g2(e5, t5, n5) { e5.listeners(t5).indexOf(n5) == -1 && e5.on(t5, n5); } n4.live && (this.push.on("complete", i3.pull.cancel.bind(i3.pull)), this.pull.on("complete", i3.push.cancel.bind(i3.push))), this.on("newListener", function(e5) { e5 === "change" ? (g2(i3.pull, "change", a2), g2(i3.push, "change", u2)) : e5 === "denied" ? (g2(i3.pull, "denied", f2), g2(i3.push, "denied", c2)) : e5 === "active" ? (g2(i3.pull, "active", p2), g2(i3.push, "active", h2)) : e5 === "paused" && (g2(i3.pull, "paused", d2), g2(i3.push, "paused", l2)); }), this.on("removeListener", function(e5) { e5 === "change" ? (i3.pull.removeListener("change", a2), i3.push.removeListener("change", u2)) : e5 === "denied" ? (i3.pull.removeListener("denied", f2), i3.push.removeListener("denied", c2)) : e5 === "active" ? (i3.pull.removeListener("active", p2), i3.push.removeListener("active", h2)) : e5 === "paused" && (i3.pull.removeListener("paused", d2), i3.push.removeListener("paused", l2)); }), this.pull.on("removeListener", y2("pull")), this.push.on("removeListener", y2("push")); var _2 = Promise.all([this.push, this.pull]).then(function(e5) { var t5 = { push: e5[0], pull: e5[1] }; return i3.emit("complete", t5), r3 && r3(null, t5), i3.removeAllListeners(), t5; }, function(e5) { if (i3.cancel(), r3 ? r3(e5) : i3.emit("error", e5), i3.removeAllListeners(), r3) throw e5; }); this.then = function(e5, t5) { return _2.then(e5, t5); }, this.catch = function(e5) { return _2.catch(e5); }; } Hn.prototype.getCheckpoint = function() { var e4 = this; return e4.opts && e4.opts.writeSourceCheckpoint && !e4.opts.writeTargetCheckpoint ? e4.src.get(e4.id).then(function(e5) { return e5.last_seq || 0; }).catch(function(e5) { if (e5.status !== 404) throw e5; return 0; }) : e4.target.get(e4.id).then(function(t4) { return e4.opts && e4.opts.writeTargetCheckpoint && !e4.opts.writeSourceCheckpoint ? t4.last_seq || 0 : e4.src.get(e4.id).then(function(e5) { return t4.version !== e5.version ? 0 : (n4 = t4.version ? t4.version.toString() : "undefined") in er ? er[n4](t4, e5) : 0; var n4; }, function(n4) { if (n4.status === 404 && t4.last_seq) return e4.src.put({ _id: e4.id, last_seq: 0 }).then(function() { return 0; }, function(n5) { return rr(n5) ? (e4.opts.writeSourceCheckpoint = false, t4.last_seq) : 0; }); throw n4; }); }).catch(function(e5) { if (e5.status !== 404) throw e5; return 0; }); }, p()(or, y()), or.prototype.cancel = function() { this.cancelled = true, this.state = "cancelled", this.emit("cancel"); }, or.prototype.ready = function(e4, t4) { var n4 = this; function r3() { n4.cancel(); } function i3() { e4.removeListener("destroyed", r3), t4.removeListener("destroyed", r3); } n4._readyCalled || (n4._readyCalled = true, e4.once("destroyed", r3), t4.once("destroyed", r3), n4.once("complete", i3), n4.once("error", i3)); }, p()(cr, y()), cr.prototype.cancel = function() { this.canceled || (this.canceled = true, this.push.cancel(), this.pull.cancel()); }, tt.plugin(function(e4) { e4.adapter("idb", hn, true); }).plugin(function(e4) { e4.adapter("http", kn, false), e4.adapter("https", kn, false); }).plugin(Qn).plugin(function(e4) { e4.replicate = ar, e4.sync = ur, Object.defineProperty(e4.prototype, "replicate", { get: function() { var e5 = this; return this.replicateMethods === void 0 && (this.replicateMethods = { from: function(t4, n4, r3) { return e5.constructor.replicate(t4, e5, n4, r3); }, to: function(t4, n4, r3) { return e5.constructor.replicate(e5, t4, n4, r3); } }), this.replicateMethods; } }), e4.prototype.sync = function(e5, t4, n4) { return this.constructor.sync(this, e5, t4, n4); }; }); const fr = tt; }, 614: (e3, t3, n3) => { n3.d(t3, { Z: () => vt }); var r2 = n3(717), i2 = n3.n(r2); function o(e4, t4, n4) { Error.call(this, n4), this.status = e4, this.name = t4, this.message = n4, this.error = true; } i2()(o, Error), o.prototype.toString = function() { return JSON.stringify({ status: this.status, name: this.name, message: this.message, reason: this.reason }); }, new o(401, "unauthorized", "Name or password is incorrect."), new o(400, "bad_request", "Missing JSON list of 'docs'"), new o(404, "not_found", "missing"), new o(409, "conflict", "Document update conflict"), new o(400, "bad_request", "_id field must contain a string"), new o(412, "missing_id", "_id is required for puts"), new o(400, "bad_request", "Only reserved document ids may start with underscore."), new o(412, "precondition_failed", "Database not open"); var s = new o(500, "unknown_error", "Database encountered an unknown error"); function a(e4) { if (typeof e4 != "object") { var t4 = e4; (e4 = s).data = t4; } return "error" in e4 && e4.error === "conflict" && (e4.name = "conflict", e4.status = 409), "name" in e4 || (e4.name = e4.error || "unknown"), "status" in e4 || (e4.status = 500), "message" in e4 || (e4.message = e4.message || e4.reason), "stack" in e4 || (e4.stack = new Error().stack), e4; } new o(500, "badarg", "Some query argument is invalid"), new o(400, "invalid_request", "Request was invalid"), new o(400, "query_parse_error", "Some query parameter is invalid"), new o(500, "doc_validation", "Bad special document member"), new o(400, "bad_request", "Something wrong with the request"), new o(400, "bad_request", "Document must be a JSON object"), new o(404, "not_found", "Database not found"), new o(500, "indexed_db_went_bad", "unknown"), new o(500, "web_sql_went_bad", "unknown"), new o(500, "levelDB_went_went_bad", "unknown"), new o(403, "forbidden", "Forbidden by design doc validate_doc_update function"), new o(400, "bad_request", "Invalid rev format"), new o(412, "file_exists", "The database could not be created, the file already exists."), new o(412, "missing_stub", "A pre-existing attachment stub wasn't found"), new o(413, "invalid_url", "Provided URL is invalid"), typeof AbortController != "undefined" && AbortController, fetch; var u, c, f = Headers; function l(e4) { return "$" + e4; } function d(e4) { return e4.substring(1); } function h() { this._store = {}; } function p(e4) { if (this._store = new h(), e4 && Array.isArray(e4)) for (var t4 = 0, n4 = e4.length; t4 < n4; t4++) this.add(e4[t4]); } function v(e4) { for (var t4 = e4.length, n4 = new ArrayBuffer(t4), r3 = new Uint8Array(n4), i3 = 0; i3 < t4; i3++) r3[i3] = e4.charCodeAt(i3); return n4; } function y(e4, t4) { return function(e5, t5) { return function(e6, t6) { e6 = e6 || [], t6 = t6 || {}; try { return new Blob(e6, t6); } catch (i3) { if (i3.name !== "TypeError") throw i3; for (var n4 = new (typeof BlobBuilder != "undefined" ? BlobBuilder : typeof MSBlobBuilder != "undefined" ? MSBlobBuilder : typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : WebKitBlobBuilder)(), r3 = 0; r3 < e6.length; r3 += 1) n4.append(e6[r3]); return n4.getBlob(t6.type); } }([v(e5)], { type: t5 }); }(atob(e4), t4); } h.prototype.get = function(e4) { var t4 = l(e4); return this._store[t4]; }, h.prototype.set = function(e4, t4) { var n4 = l(e4); return this._store[n4] = t4, true; }, h.prototype.has = function(e4) { return l(e4) in this._store; }, h.prototype.keys = function() { return Object.keys(this._store).map((e4) => d(e4)); }, h.prototype.delete = function(e4) { var t4 = l(e4), n4 = t4 in this._store; return delete this._store[t4], n4; }, h.prototype.forEach = function(e4) { for (var t4 = Object.keys(this._store), n4 = 0, r3 = t4.length; n4 < r3; n4++) { var i3 = t4[n4]; e4(this._store[i3], i3 = d(i3)); } }, Object.defineProperty(h.prototype, "size", { get: function() { return Object.keys(this._store).length; } }), p.prototype.add = function(e4) { return this._store.set(e4, true); }, p.prototype.has = function(e4) { return this._store.has(e4); }, p.prototype.forEach = function(e4) { this._store.forEach(function(t4, n4) { e4(n4); }); }, Object.defineProperty(p.prototype, "size", { get: function() { return this._store.size; } }), function() { if (typeof Symbol == "undefined" || typeof Map == "undefined" || typeof Set == "undefined") return false; var e4 = Object.getOwnPropertyDescriptor(Map, Symbol.species); return e4 && "get" in e4 && Map[Symbol.species] === Map; }() ? (u = Set, c = Map) : (u = p, c = h); function g(e4, t4) { if (e4 === t4) return 0; e4 = _(e4), t4 = _(t4); var n4 = k(e4), r3 = k(t4); if (n4 - r3 != 0) return n4 - r3; switch (typeof e4) { case "number": return e4 - t4; case "boolean": return e4 < t4 ? -1 : 1; case "string": return function(e5, t5) { return e5 === t5 ? 0 : e5 > t5 ? 1 : -1; }(e4, t4); } return Array.isArray(e4) ? function(e5, t5) { for (var n5 = Math.min(e5.length, t5.length), r4 = 0; r4 < n5; r4++) { var i3 = g(e5[r4], t5[r4]); if (i3 !== 0) return i3; } return e5.length === t5.length ? 0 : e5.length > t5.length ? 1 : -1; }(e4, t4) : function(e5, t5) { for (var n5 = Object.keys(e5), r4 = Object.keys(t5), i3 = Math.min(n5.length, r4.length), o2 = 0; o2 < i3; o2++) { var s2 = g(n5[o2], r4[o2]); if (s2 !== 0) return s2; if ((s2 = g(e5[n5[o2]], t5[r4[o2]])) !== 0) return s2; } return n5.length === r4.length ? 0 : n5.length > r4.length ? 1 : -1; }(e4, t4); } function _(e4) { switch (typeof e4) { case "undefined": return null; case "number": return e4 === 1 / 0 || e4 === -1 / 0 || isNaN(e4) ? null : e4; case "object": var t4 = e4; if (Array.isArray(e4)) { var n4 = e4.length; e4 = new Array(n4); for (var r3 = 0; r3 < n4; r3++) e4[r3] = _(t4[r3]); } else { if (e4 instanceof Date) return e4.toJSON(); if (e4 !== null) { for (var i3 in e4 = {}, t4) if (Object.prototype.hasOwnProperty.call(t4, i3)) { var o2 = t4[i3]; o2 !== void 0 && (e4[i3] = _(o2)); } } } } return e4; } function m(e4) { return k(e4 = _(e4)) + "" + function(e5) { if (e5 !== null) switch (typeof e5) { case "boolean": return e5 ? 1 : 0; case "number": return function(e6) { if (e6 === 0) return "1"; var t5, n5 = e6.toExponential().split(/e\+?/), r4 = parseInt(n5[1], 10), i4 = e6 < 0, o3 = i4 ? "0" : "2"; o3 += "" + (function(e7, t6, n6) { for (var r5 = "", i5 = 3 - e7.length; r5.length < i5; ) r5 += "0"; return r5; }(t5 = ((i4 ? -r4 : r4) - -324).toString()) + t5); var s3 = Math.abs(parseFloat(n5[0])); i4 && (s3 = 10 - s3); var a2 = s3.toFixed(20); return o3 + "" + a2.replace(/\.?0+$/, ""); }(e5); case "string": return e5.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, ""); case "object": var t4 = Array.isArray(e5), n4 = t4 ? e5 : Object.keys(e5), r3 = -1, i3 = n4.length, o2 = ""; if (t4) for (; ++r3 < i3; ) o2 += m(n4[r3]); else for (; ++r3 < i3; ) { var s2 = n4[r3]; o2 += m(s2) + m(e5[s2]); } return o2; } return ""; }(e4) + "\0"; } function b(e4, t4) { var n4, r3 = t4; if (e4[t4] === "1") n4 = 0, t4++; else { var i3 = e4[t4] === "0"; t4++; var o2 = "", s2 = e4.substring(t4, t4 + 3), a2 = parseInt(s2, 10) + -324; for (i3 && (a2 = -a2), t4 += 3; ; ) { var u2 = e4[t4]; if (u2 === "\0") break; o2 += u2, t4++; } n4 = (o2 = o2.split(".")).length === 1 ? parseInt(o2, 10) : parseFloat(o2[0] + "." + o2[1]), i3 && (n4 -= 10), a2 !== 0 && (n4 = parseFloat(n4 + "e" + a2)); } return { num: n4, length: t4 - r3 }; } function w(e4, t4) { var n4 = e4.pop(); if (t4.length) { var r3 = t4[t4.length - 1]; n4 === r3.element && (t4.pop(), r3 = t4[t4.length - 1]); var i3 = r3.element, o2 = r3.index; Array.isArray(i3) ? i3.push(n4) : o2 === e4.length - 2 ? i3[e4.pop()] = n4 : e4.push(n4); } } function k(e4) { var t4 = ["boolean", "number", "string", "object"].indexOf(typeof e4); return ~t4 ? e4 === null ? 1 : Array.isArray(e4) ? 5 : t4 < 3 ? t4 + 2 : t4 + 3 : Array.isArray(e4) ? 5 : void 0; } var j = n3(105), O = n3.n(j), $ = n3(624), x = n3.n($), q = n3(187), A = n3.n(q), S = n3(586), E = n3(322), P = n3.n(E); function C(e4) { return P().hash(e4); } self.setImmediate || self.setTimeout; var D, L = Function.prototype.toString, B = L.call(Object); function I(e4) { var t4, n4, r3; if (!e4 || typeof e4 != "object") return e4; if (Array.isArray(e4)) { for (t4 = [], n4 = 0, r3 = e4.length; n4 < r3; n4++) t4[n4] = I(e4[n4]); return t4; } if (e4 instanceof Date && isFinite(e4)) return e4.toISOString(); if (function(e5) { return typeof ArrayBuffer != "undefined" && e5 instanceof ArrayBuffer || typeof Blob != "undefined" && e5 instanceof Blob; }(e4)) return function(e5) { if (e5 instanceof ArrayBuffer) return function(e6) { if (typeof e6.slice == "function") return e6.slice(0); var t6 = new ArrayBuffer(e6.byteLength), n6 = new Uint8Array(t6), r4 = new Uint8Array(e6); return n6.set(r4), t6; }(e5); var t5 = e5.size, n5 = e5.type; return typeof e5.slice == "function" ? e5.slice(0, t5, n5) : e5.webkitSlice(0, t5, n5); }(e4); if (!function(e5) { var t5 = Object.getPrototypeOf(e5); if (t5 === null) return true; var n5 = t5.constructor; return typeof n5 == "function" && n5 instanceof n5 && L.call(n5) == B; }(e4)) return e4; for (n4 in t4 = {}, e4) if (Object.prototype.hasOwnProperty.call(e4, n4)) { var i3 = I(e4[n4]); i3 !== void 0 && (t4[n4] = i3); } return t4; } function T(e4) { return O()(function(t4) { t4 = I(t4); var n4 = this, r3 = typeof t4[t4.length - 1] == "function" && t4.pop(), i3 = new Promise(function(r4, i4) { var o2, s2, a2; try { var u2 = (s2 = function(e5, t5) { e5 ? i4(e5) : r4(t5); }, a2 = false, O()(function(e5) { if (a2) throw new Error("once called more than once"); a2 = true, s2.apply(this, e5); })); t4.push(u2), (o2 = e4.apply(n4, t4)) && typeof o2.then == "function" && r4(o2); } catch (e5) { i4(e5); } }); return r3 && i3.then(function(e5) { r3(null, e5); }, r3), i3; }); } try { localStorage.setItem("_pouch_check_localstorage", 1), D = !!localStorage.getItem("_pouch_check_localstorage"); } catch (e4) { D = false; } function M() { return D; } function N() { A().call(this), this._listeners = {}, function(e4) { M() && addEventListener("storage", function(t4) { e4.emit(t4.key); }); }(this); } function R(e4) { if (typeof console != "undefined" && typeof console[e4] == "function") { var t4 = Array.prototype.slice.call(arguments, 1); console[e4].apply(console, t4); } } i2()(N, A()), N.prototype.addListener = function(e4, t4, n4, r3) { if (!this._listeners[t4]) { var i3 = this, o2 = false; this._listeners[t4] = s2, this.on(e4, s2); } function s2() { if (i3._listeners[t4]) if (o2) o2 = "waiting"; else { o2 = true; var e5 = function(e6, t5) { for (var n5 = {}, r4 = 0, i4 = t5.length; r4 < i4; r4++) { var o3 = t5[r4]; o3 in e6 && (n5[o3] = e6[o3]); } return n5; }(r3, ["style", "include_docs", "attachments", "conflicts", "filter", "doc_ids", "view", "since", "query_params", "binary", "return_docs"]); n4.changes(e5).on("change", function(e6) { e6.seq > r3.since && !r3.cancelled && (r3.since = e6.seq, r3.onChange(e6)); }).on("complete", function() { o2 === "waiting" && x()(s2), o2 = false; }).on("error", function() { o2 = false; }); } } }, N.prototype.removeListener = function(e4, t4) { t4 in this._listeners && (A().prototype.removeListener.call(this, e4, this._listeners[t4]), delete this._listeners[t4]); }, N.prototype.notifyLocalWindows = function(e4) { M() && (localStorage[e4] = localStorage[e4] === "a" ? "b" : "a"); }, N.prototype.notify = function(e4) { this.emit(e4), this.notifyLocalWindows(e4); }; var F = typeof Object.assign == "function" ? Object.assign : function(e4) { for (var t4 = Object(e4), n4 = 1; n4 < arguments.length; n4++) { var r3 = arguments[n4]; if (r3 != null) for (var i3 in r3) Object.prototype.hasOwnProperty.call(r3, i3) && (t4[i3] = r3[i3]); } return t4; }; function U(e4) { for (var t4 = [], n4 = 0, r3 = e4.length; n4 < r3; n4++) t4 = t4.concat(e4[n4]); return t4; } function z(e4) { return typeof e4._remote == "boolean" ? e4._remote : typeof e4.type == "function" && (R("warn", "db.type() is deprecated and will be removed in a future version of PouchDB"), e4.type() === "http"); } function J(e4, t4, n4) { return e4.get(t4).catch(function(e5) { if (e5.status !== 404) throw e5; return {}; }).then(function(r3) { var i3 = r3._rev, o2 = n4(r3); return o2 ? (o2._id = t4, o2._rev = i3, function(e5, t5, n5) { return e5.put(t5).then(function(e6) { return { updated: true, rev: e6.rev }; }, function(r4) { if (r4.status !== 409) throw r4; return J(e5, t5._id, n5); }); }(e4, o2, n4)) : { updated: false, rev: i3 }; }); } function K(e4) { this.status = 400, this.name = "query_parse_error", this.message = e4, this.error = true; try { Error.captureStackTrace(this, K); } catch (e5) { } } function V(e4) { this.status = 404, this.name = "not_found", this.message = e4, this.error = true; try { Error.captureStackTrace(this, V); } catch (e5) { } } function Q(e4) { this.status = 500, this.name = "invalid_value", this.message = e4, this.error = true; try { Error.captureStackTrace(this, Q); } catch (e5) { } } function G(e4, t4) { return t4 && e4.then(function(e5) { x()(function() { t4(null, e5); }); }, function(e5) { x()(function() { t4(e5); }); }), e4; } function W(e4, t4) { return function() { var n4 = arguments, r3 = this; return e4.add(function() { return t4.apply(r3, n4); }); }; } function Z(e4) { var t4 = new u(e4), n4 = new Array(t4.size), r3 = -1; return t4.forEach(function(e5) { n4[++r3] = e5; }), n4; } function X(e4) { var t4 = new Array(e4.size), n4 = -1; return e4.forEach(function(e5, r3) { t4[++n4] = r3; }), t4; } function Y() { this.promise = new Promise(function(e4) { e4(); }); } function H(e4) { if (!e4) return "undefined"; switch (typeof e4) { case "function": case "string": return e4.toString(); default: return JSON.stringify(e4); } } function ee(e4, t4, n4, r3, i3, o2) { var s2, a2 = function(e5, t5) { return H(e5) + H(t5) + "undefined"; }(n4, r3); if (!i3 && (s2 = e4._cachedViews = e4._cachedViews || {})[a2]) return s2[a2]; var u2 = e4.info().then(function(u3) { var c2 = u3.db_name + "-mrview-" + (i3 ? "temp" : C(a2)); return J(e4, "_local/" + o2, function(e5) { e5.views = e5.views || {}; var n5 = t4; n5.indexOf("/") === -1 && (n5 = t4 + "/" + t4); var r4 = e5.views[n5] = e5.views[n5] || {}; if (!r4[c2]) return r4[c2] = true, e5; }).then(function() { return e4.registerDependentDatabase(c2).then(function(t5) { var i4 = t5.db; i4.auto_compaction = true; var o3 = { name: c2, db: i4, sourceDB: e4, adapter: e4.adapter, mapFun: n4, reduceFun: r3 }; return o3.db.get("_local/lastSeq").catch(function(e5) { if (e5.status !== 404) throw e5; }).then(function(e5) { return o3.seq = e5 ? e5.seq : 0, s2 && o3.db.once("destroyed", function() { delete s2[a2]; }), o3; }); }); }); }); return s2 && (s2[a2] = u2), u2; } S.Z, i2()(K, Error), i2()(V, Error), i2()(Q, Error), Y.prototype.add = function(e4) { return this.promise = this.promise.catch(function() { }).then(function() { return e4(); }), this.promise; }, Y.prototype.finish = function() { return this.promise; }; var te = {}, ne = new Y(); function re(e4) { return e4.indexOf("/") === -1 ? [e4, e4] : e4.split("/"); } function ie(e4, t4) { try { e4.emit("error", t4); } catch (e5) { R("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."), R("error", t4); } } function oe(e4, t4) { for (var n4 = e4, r3 = 0, i3 = t4.length; r3 < i3 && (n4 = n4[t4[r3]]); r3++) ; return n4; } function se(e4, t4, n4) { for (var r3 = 0, i3 = t4.length; r3 < i3 - 1; r3++) { var o2 = t4[r3]; e4 = e4[o2] = e4[o2] || {}; } e4[t4[i3 - 1]] = n4; } function ae(e4, t4) { return e4 < t4 ? -1 : e4 > t4 ? 1 : 0; } function ue(e4) { for (var t4 = [], n4 = "", r3 = 0, i3 = e4.length; r3 < i3; r3++) { var o2 = e4[r3]; r3 > 0 && e4[r3 - 1] === "\\" && (o2 === "$" || o2 === ".") ? n4 = n4.substring(0, n4.length - 1) + o2 : o2 === "." ? (t4.push(n4), n4 = "") : n4 += o2; } return t4.push(n4), t4; } var ce = ["$or", "$nor", "$not"]; function fe(e4) { return ce.indexOf(e4) > -1; } function le(e4) { return Object.keys(e4)[0]; } function de(e4) { return e4[le(e4)]; } function he(e4) { var t4 = {}, n4 = { $or: true, $nor: true }; return e4.forEach(function(e5) { Object.keys(e5).forEach(function(r3) { var i3 = e5[r3]; if (typeof i3 != "object" && (i3 = { $eq: i3 }), fe(r3)) if (i3 instanceof Array) { if (n4[r3]) return n4[r3] = false, void (t4[r3] = i3); var o2 = []; t4[r3].forEach(function(e6) { Object.keys(i3).forEach(function(t5) { var n5 = i3[t5], r4 = Math.max(Object.keys(e6).length, Object.keys(n5).length), s3 = he([e6, n5]); Object.keys(s3).length <= r4 || o2.push(s3); }); }), t4[r3] = o2; } else t4[r3] = he([i3]); else { var s2 = t4[r3] = t4[r3] || {}; Object.keys(i3).forEach(function(e6) { var t5 = i3[e6]; return e6 === "$gt" || e6 === "$gte" ? function(e7, t6, n5) { n5.$eq === void 0 && (n5.$gte !== void 0 ? e7 === "$gte" ? t6 > n5.$gte && (n5.$gte = t6) : t6 >= n5.$gte && (delete n5.$gte, n5.$gt = t6) : n5.$gt !== void 0 ? e7 === "$gte" ? t6 > n5.$gt && (delete n5.$gt, n5.$gte = t6) : t6 > n5.$gt && (n5.$gt = t6) : n5[e7] = t6); }(e6, t5, s2) : e6 === "$lt" || e6 === "$lte" ? function(e7, t6, n5) { n5.$eq === void 0 && (n5.$lte !== void 0 ? e7 === "$lte" ? t6 < n5.$lte && (n5.$lte = t6) : t6 <= n5.$lte && (delete n5.$lte, n5.$lt = t6) : n5.$lt !== void 0 ? e7 === "$lte" ? t6 < n5.$lt && (delete n5.$lt, n5.$lte = t6) : t6 < n5.$lt && (n5.$lt = t6) : n5[e7] = t6); }(e6, t5, s2) : e6 === "$ne" ? function(e7, t6) { "$ne" in t6 ? t6.$ne.push(e7) : t6.$ne = [e7]; }(t5, s2) : e6 === "$eq" ? function(e7, t6) { delete t6.$gt, delete t6.$gte, delete t6.$lt, delete t6.$lte, delete t6.$ne, t6.$eq = e7; }(t5, s2) : e6 === "$regex" ? function(e7, t6) { "$regex" in t6 ? t6.$regex.push(e7) : t6.$regex = [e7]; }(t5, s2) : void (s2[e6] = t5); }); } }); }), t4; } function pe(e4) { for (var t4 in e4) { if (Array.isArray(e4)) for (var n4 in e4) e4[n4].$and && (e4[n4] = he(e4[n4].$and)); var r3 = e4[t4]; typeof r3 == "object" && pe(r3); } return e4; } function ve(e4, t4) { for (var n4 in e4) { n4 === "$and" && (t4 = true); var r3 = e4[n4]; typeof r3 == "object" && (t4 = ve(r3, t4)); } return t4; } function ye(e4) { var t4 = I(e4), n4 = false; ve(t4, false) && ("$and" in (t4 = pe(t4)) && (t4 = he(t4.$and)), n4 = true), ["$or", "$nor"].forEach(function(e5) { e5 in t4 && t4[e5].forEach(function(e6) { for (var t5 = Object.keys(e6), n5 = 0; n5 < t5.length; n5++) { var r4 = t5[n5], i4 = e6[r4]; typeof i4 == "object" && i4 !== null || (e6[r4] = { $eq: i4 }); } }); }), "$not" in t4 && (t4.$not = he([t4.$not])); for (var r3 = Object.keys(t4), i3 = 0; i3 < r3.length; i3++) { var o2 = r3[i3], s2 = t4[o2]; typeof s2 != "object" || s2 === null ? s2 = { $eq: s2 } : n4 || ("$ne" in s2 && (s2.$ne = [s2.$ne]), "$regex" in s2 && (s2.$regex = [s2.$regex])), t4[o2] = s2; } return t4; } function ge(e4, t4, n4) { if (e4 = e4.filter(function(e5) { return _e(e5.doc, t4.selector, n4); }), t4.sort) { var r3 = function(e5) { function t5(t6) { return e5.map(function(e6) { var n5 = ue(le(e6)); return oe(t6, n5); }); } return function(e6, n5) { var r4 = g(t5(e6.doc), t5(n5.doc)); return r4 !== 0 ? r4 : ae(e6.doc._id, n5.doc._id); }; }(t4.sort); e4 = e4.sort(r3), typeof t4.sort[0] != "string" && de(t4.sort[0]) === "desc" && (e4 = e4.reverse()); } if ("limit" in t4 || "skip" in t4) { var i3 = t4.skip || 0, o2 = ("limit" in t4 ? t4.limit : e4.length) + i3; e4 = e4.slice(i3, o2); } return e4; } function _e(e4, t4, n4) { return n4.every(function(n5) { var r3 = t4[n5], i3 = ue(n5), o2 = oe(e4, i3); return fe(n5) ? function(e5, t5, n6) { return e5 === "$or" ? t5.some(function(e6) { return _e(n6, e6, Object.keys(e6)); }) : e5 === "$not" ? !_e(n6, t5, Object.keys(t5)) : !t5.find(function(e6) { return _e(n6, e6, Object.keys(e6)); }); }(n5, r3, e4) : me(r3, e4, i3, o2); }); } function me(e4, t4, n4, r3) { return !e4 || (typeof e4 == "object" ? Object.keys(e4).every(function(i3) { var o2 = e4[i3]; if (i3.indexOf("$") === 0) return be(i3, t4, o2, n4, r3); var s2 = ue(i3); if (r3 === void 0 && typeof o2 != "object" && s2.length > 0) return false; var a2 = oe(r3, s2); return typeof o2 == "object" ? me(o2, t4, n4, a2) : be("$eq", t4, o2, s2, a2); }) : e4 === r3); } function be(e4, t4, n4, r3, i3) { if (!Oe[e4]) throw new Error('unknown operator "' + e4 + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all'); return Oe[e4](t4, n4, r3, i3); } function we(e4) { return e4 != null; } function ke(e4) { return e4 !== void 0; } function je(e4, t4) { return t4.some(function(t5) { return e4 instanceof Array ? e4.some(function(e5) { return g(t5, e5) === 0; }) : g(t5, e4) === 0; }); } var Oe = { $elemMatch: function(e4, t4, n4, r3) { return !!Array.isArray(r3) && r3.length !== 0 && (typeof r3[0] == "object" ? r3.some(function(e5) { return _e(e5, t4, Object.keys(t4)); }) : r3.some(function(r4) { return me(t4, e4, n4, r4); })); }, $allMatch: function(e4, t4, n4, r3) { return !!Array.isArray(r3) && r3.length !== 0 && (typeof r3[0] == "object" ? r3.every(function(e5) { return _e(e5, t4, Object.keys(t4)); }) : r3.every(function(r4) { return me(t4, e4, n4, r4); })); }, $eq: function(e4, t4, n4, r3) { return ke(r3) && g(r3, t4) === 0; }, $gte: function(e4, t4, n4, r3) { return ke(r3) && g(r3, t4) >= 0; }, $gt: function(e4, t4, n4, r3) { return ke(r3) && g(r3, t4) > 0; }, $lte: function(e4, t4, n4, r3) { return ke(r3) && g(r3, t4) <= 0; }, $lt: function(e4, t4, n4, r3) { return ke(r3) && g(r3, t4) < 0; }, $exists: function(e4, t4, n4, r3) { return t4 ? ke(r3) : !ke(r3); }, $mod: function(e4, t4, n4, r3) { return we(r3) && function(e5, t5) { return typeof e5 == "number" && parseInt(e5, 10) === e5 && e5 % t5[0] === t5[1]; }(r3, t4); }, $ne: function(e4, t4, n4, r3) { return t4.every(function(e5) { return g(r3, e5) !== 0; }); }, $in: function(e4, t4, n4, r3) { return we(r3) && je(r3, t4); }, $nin: function(e4, t4, n4, r3) { return we(r3) && !je(r3, t4); }, $size: function(e4, t4, n4, r3) { return we(r3) && Array.isArray(r3) && function(e5, t5) { return e5.length === t5; }(r3, t4); }, $all: function(e4, t4, n4, r3) { return Array.isArray(r3) && function(e5, t5) { return t5.every(function(t6) { return e5.some(function(e6) { return g(t6, e6) === 0; }); }); }(r3, t4); }, $regex: function(e4, t4, n4, r3) { return we(r3) && typeof r3 == "string" && t4.every(function(e5) { return function(e6, t5) { return new RegExp(t5).test(e6); }(r3, e5); }); }, $type: function(e4, t4, n4, r3) { return function(e5, t5) { switch (t5) { case "null": return e5 === null; case "boolean": return typeof e5 == "boolean"; case "number": return typeof e5 == "number"; case "string": return typeof e5 == "string"; case "array": return e5 instanceof Array; case "object": return {}.toString.call(e5) === "[object Object]"; } }(r3, t4); } }; function $e(e4, t4) { if (typeof t4 != "object") throw new Error("Selector error: expected a JSON object"); var n4 = ge([{ doc: e4 }], { selector: t4 = ye(t4) }, Object.keys(t4)); return n4 && n4.length === 1; } function xe(e4) { return (e4 = I(e4)).index || (e4.index = {}), ["type", "name", "ddoc"].forEach(function(t4) { e4.index[t4] && (e4[t4] = e4.index[t4], delete e4.index[t4]); }), e4.fields && (e4.index.fields = e4.fields, delete e4.fields), e4.type || (e4.type = "json"), e4; } function qe(e4, t4, n4) { var r3 = "", i3 = t4, o2 = true; if (["$in", "$nin", "$or", "$and", "$mod", "$nor", "$all"].indexOf(e4) !== -1 && (Array.isArray(t4) || (r3 = "Query operator " + e4 + " must be an array.")), ["$not", "$elemMatch", "$allMatch"].indexOf(e4) !== -1 && (Array.isArray(t4) || typeof t4 != "object" || t4 === null) && (r3 = "Query operator " + e4 + " must be an object."), e4 === "$mod" && Array.isArray(t4)) if (t4.length !== 2) r3 = "Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers."; else { var s2 = t4[0], a2 = t4[1]; s2 === 0 && (r3 = "Query operator $mod's divisor cannot be 0, cannot divide by zero.", o2 = false), typeof s2 == "number" && parseInt(s2, 10) === s2 || (r3 = "Query operator $mod's divisor is not an integer.", i3 = s2), parseInt(a2, 10) !== a2 && (r3 = "Query operator $mod's remainder is not an integer.", i3 = a2); } if (e4 === "$exists" && typeof t4 != "boolean" && (r3 = "Query operator $exists must be a boolean."), e4 === "$type") { var u2 = ["null", "boolean", "number", "string", "array", "object"], c2 = '"' + u2.slice(0, u2.length - 1).join('", "') + '", or "' + u2[u2.length - 1] + '"'; (typeof t4 != "string" || u2.indexOf(t4) == -1) && (r3 = "Query operator $type must be a string. Supported values: " + c2 + "."); } if (e4 === "$size" && parseInt(t4, 10) !== t4 && (r3 = "Query operator $size must be a integer."), e4 === "$regex" && typeof t4 != "string" && (console.log("here", n4), n4 ? r3 = "Query operator $regex must be a string." : t4 instanceof RegExp || (r3 = "Query operator $regex must be a string or an instance of a javascript regular expression.")), r3) throw o2 && (r3 += " Received" + (i3 === null ? " " : Array.isArray(i3) ? " array" : " " + typeof i3) + ": " + (typeof i3 == "object" && i3 !== null ? JSON.stringify(i3, null, " ") : i3)), new Error(r3); } var Ae = ["$all", "$allMatch", "$and", "$elemMatch", "$exists", "$in", "$mod", "$nin", "$nor", "$not", "$or", "$regex", "$size", "$type"], Se = ["$in", "$nin", "$mod", "$all"], Ee = ["$eq", "$gt", "$gte", "$lt", "$lte"]; function Pe(e4, t4) { if (Array.isArray(e4)) for (var n4 of e4) typeof n4 == "object" && s2 !== null && Pe(n4, t4); else for (var r3 = Object.keys(e4), i3 = 0; i3 < r3.length; i3++) { var o2 = r3[i3], s2 = e4[o2]; Ae.indexOf(o2) !== -1 && qe(o2, s2, t4), Ee.indexOf(o2) === -1 && Se.indexOf(o2) === -1 && typeof s2 == "object" && s2 !== null && Pe(s2, t4); } } function Ce(e4, t4, n4, r3) { var i3, o2; n4.headers = new f({ "Content-type": "application/json" }), e4.fetch(t4, n4).then(function(e5) { return i3 = e5.status, o2 = e5.ok, e5.json(); }).then(function(e5) { if (o2) r3(null, e5); else { e5.status = i3; var t5 = a(e5); r3(t5); } }).catch(r3); } function De(e4, t4, n4) { t4 = xe(t4), Ce(e4, "_index", { method: "POST", body: JSON.stringify(t4) }, n4); } function Le(e4, t4, n4) { Pe(t4.selector, true), Ce(e4, "_find", { method: "POST", body: JSON.stringify(t4) }, n4); } function Be(e4, t4, n4) { Ce(e4, "_explain", { method: "POST", body: JSON.stringify(t4) }, n4); } function Ie(e4, t4) { Ce(e4, "_index", { method: "GET" }, t4); } function Te(e4, t4, n4) { var r3 = t4.ddoc, i3 = t4.type || "json", o2 = t4.name; return r3 ? o2 ? void Ce(e4, "_index/" + [r3, i3, o2].map(encodeURIComponent).join("/"), { method: "DELETE" }, n4) : n4(new Error("you must provide an index's name")) : n4(new Error("you must provide an index's ddoc")); } function Me(e4) { return function() { for (var t4 = arguments.length, n4 = new Array(t4), r3 = -1; ++r3 < t4; ) n4[r3] = arguments[r3]; return e4.call(this, n4); }; } function Ne(e4) { return Me(function(t4) { var n4 = t4.pop(), r3 = e4.apply(this, t4); return function(e5, t5) { e5.then(function(e6) { x()(function() { t5(null, e6); }); }, function(e6) { x()(function() { t5(e6); }); }); }(r3, n4), r3; }); } var Re = Me(function(e4) { for (var t4 = [], n4 = 0, r3 = e4.length; n4 < r3; n4++) { var i3 = e4[n4]; Array.isArray(i3) ? t4 = t4.concat(Re.apply(null, i3)) : t4.push(i3); } return t4; }); function Fe(e4) { for (var t4 = {}, n4 = 0, r3 = e4.length; n4 < r3; n4++) t4 = F(t4, e4[n4]); return t4; } function Ue(e4, t4) { for (var n4 = 0, r3 = Math.min(e4.length, t4.length); n4 < r3; n4++) if (e4[n4] !== t4[n4]) return false; return true; } function ze(e4, t4) { if (e4.length !== t4.length) return false; for (var n4 = 0, r3 = e4.length; n4 < r3; n4++) if (e4[n4] !== t4[n4]) return false; return true; } var Je = function(e4, t4, n4, r3) { function i3(e5, t5, n5) { try { t5(n5); } catch (t6) { ie(e5, t6); } } function o2(e5, t5, n5, r4, i4) { try { return { output: t5(n5, r4, i4) }; } catch (t6) { return ie(e5, t6), { error: t6 }; } } function s2(e5, t5) { var n5 = g(e5.key, t5.key); return n5 !== 0 ? n5 : g(e5.value, t5.value); } function l2(e5, t5, n5) { return n5 = n5 || 0, typeof t5 == "number" ? e5.slice(n5, t5 + n5) : n5 > 0 ? e5.slice(n5) : e5; } function d2(e5) { var t5 = e5.value; return t5 && typeof t5 == "object" && t5._id || e5.id; } function h2(e5) { return function(t5) { return e5.include_docs && e5.attachments && e5.binary && function(e6) { e6.rows.forEach(function(e7) { var t6 = e7.doc && e7.doc._attachments; t6 && Object.keys(t6).forEach(function(e8) { var n5 = t6[e8]; t6[e8].data = y(n5.data, n5.content_type); }); }); }(t5), t5; }; } function p2(e5, t5, n5, r4) { var i4 = t5[e5]; i4 !== void 0 && (r4 && (i4 = encodeURIComponent(JSON.stringify(i4))), n5.push(e5 + "=" + i4)); } function v2(e5) { if (e5 !== void 0) { var t5 = Number(e5); return isNaN(t5) || t5 !== parseInt(e5, 10) ? e5 : t5; } } function k2(e5, t5) { var n5 = e5.descending ? "endkey" : "startkey", r4 = e5.descending ? "startkey" : "endkey"; if (e5[n5] !== void 0 && e5[r4] !== void 0 && g(e5[n5], e5[r4]) > 0) throw new K("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); if (t5.reduce && e5.reduce !== false) { if (e5.include_docs) throw new K("{include_docs:true} is invalid for reduce"); if (e5.keys && e5.keys.length > 1 && !e5.group && !e5.group_level) throw new K("Multi-key fetches for reduce views must use {group: true}"); } ["group_level", "limit", "skip"].forEach(function(t6) { var n6 = function(e6) { if (e6) { if (typeof e6 != "number") return new K('Invalid value for integer: "' + e6 + '"'); if (e6 < 0) return new K('Invalid value for positive integer: "' + e6 + '"'); } }(e5[t6]); if (n6) throw n6; }); } function j2(e5) { return function(t5) { if (t5.status === 404) return e5; throw t5; }; } function $2(e5) { var t5 = typeof e5 == "string" ? e5 : e5.name, n5 = te[t5]; return n5 || (n5 = te[t5] = new Y()), n5; } function q2(e5, n5) { return W($2(e5), function() { return function(e6, n6) { var r4, o3; var a2 = t4(e6.mapFun, function(e7, t5) { var n7 = { id: o3._id, key: _(e7) }; t5 != null && (n7.value = _(t5)), r4.push(n7); }), f2 = e6.seq || 0; function l3(t5, n7) { return function() { return function(e7, t6, n8) { var r5 = "_local/lastSeq"; return e7.db.get(r5).catch(j2({ _id: r5, seq: 0 })).then(function(r6) { var i4 = X(t6); return Promise.all(i4.map(function(n9) { return function(e8, t7, n10) { var r7, i5 = "_local/doc_" + e8, o4 = { _id: i5, keys: [] }, s3 = n10.get(e8), a3 = s3[0]; return (r7 = s3[1], r7.length === 1 && /^1-/.test(r7[0].rev) ? Promise.resolve(o4) : t7.db.get(i5).catch(j2(o4))).then(function(e9) { return function(e10) { return e10.keys.length ? t7.db.allDocs({ keys: e10.keys, include_docs: true }) : Promise.resolve({ rows: [] }); }(e9).then(function(t8) { return function(e10, t9) { for (var n11 = [], r8 = new u(), i6 = 0, o5 = t9.rows.length; i6 < o5; i6++) { var s4 = t9.rows[i6].doc; if (s4 && (n11.push(s4), r8.add(s4._id), s4._deleted = !a3.has(s4._id), !s4._deleted)) { var c2 = a3.get(s4._id); "value" in c2 && (s4.value = c2.value); } } var f3 = X(a3); return f3.forEach(function(e11) { if (!r8.has(e11)) { var t10 = { _id: e11 }, i7 = a3.get(e11); "value" in i7 && (t10.value = i7.value), n11.push(t10); } }), e10.keys = Z(f3.concat(e10.keys)), n11.push(e10), n11; }(e9, t8); }); }); }(n9, e7, t6); })).then(function(t7) { var i5 = U(t7); return r6.seq = n8, i5.push(r6), e7.db.bulkDocs({ docs: i5 }); }); }); }(e6, t5, n7); }; } let d3 = 0, h3 = { view: e6.name, indexed_docs: d3 }; e6.sourceDB.emit("indexing", h3); var p3 = new Y(); function v3() { return e6.sourceDB.changes({ return_docs: true, conflicts: true, include_docs: true, style: "all_docs", since: f2, limit: n6.changes_batch_size }).then(y2); } function y2(t5) { var u2 = t5.results; if (!u2.length) return; var h4 = function(t6) { for (var n7 = new c(), u3 = 0, l4 = t6.length; u3 < l4; u3++) { var d4 = t6[u3]; if (d4.doc._id[0] !== "_") { r4 = [], (o3 = d4.doc)._deleted || i3(e6.sourceDB, a2, o3), r4.sort(s2); var h5 = b2(r4); n7.set(d4.doc._id, [h5, d4.changes]); } f2 = d4.seq; } return n7; }(u2); p3.add(l3(h4, f2)), d3 += u2.length; let y3 = { view: e6.name, last_seq: t5.last_seq, results_count: u2.length, indexed_docs: d3 }; return e6.sourceDB.emit("indexing", y3), u2.length < n6.changes_batch_size ? void 0 : v3(); } function b2(e7) { for (var t5, n7 = new c(), r5 = 0, i4 = e7.length; r5 < i4; r5++) { var o4 = e7[r5], s3 = [o4.key, o4.id]; r5 > 0 && g(o4.key, t5) === 0 && s3.push(r5), n7.set(m(s3), o4), t5 = o4.key; } return n7; } return v3().then(function() { return p3.finish(); }).then(function() { e6.seq = f2; }); }(e5, n5); })(); } function A2(e5, t5) { return W($2(e5), function() { return function(e6, t6) { var r4, i4 = e6.reduceFun && t6.reduce !== false, s3 = t6.skip || 0; function a2(t7) { return t7.include_docs = true, e6.db.allDocs(t7).then(function(e7) { return r4 = e7.total_rows, e7.rows.map(function(e8) { if ("value" in e8.doc && typeof e8.doc.value == "object" && e8.doc.value !== null) { var t8 = Object.keys(e8.doc.value).sort(), n5 = ["id", "key", "value"]; if (!(t8 < n5 || t8 > n5)) return e8.doc.value; } var r5 = function(e9) { for (var t9 = [], n6 = [], r6 = 0; ; ) { var i5 = e9[r6++]; if (i5 !== "\0") switch (i5) { case "1": t9.push(null); break; case "2": t9.push(e9[r6] === "1"), r6++; break; case "3": var o3 = b(e9, r6); t9.push(o3.num), r6 += o3.length; break; case "4": for (var s4 = ""; ; ) { var a3 = e9[r6]; if (a3 === "\0") break; s4 += a3, r6++; } s4 = s4.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, ""), t9.push(s4); break; case "5": var u3 = { element: [], index: t9.length }; t9.push(u3.element), n6.push(u3); break; case "6": var c2 = { element: {}, index: t9.length }; t9.push(c2.element), n6.push(c2); break; default: throw new Error("bad collationIndex or unexpectedly reached end of input: " + i5); } else { if (t9.length === 1) return t9.pop(); w(t9, n6); } } }(e8.doc._id); return { key: r5[0], id: r5[1], value: "value" in e8.doc ? e8.doc.value : null }; }); }); } function u2(a3) { var u3; if (u3 = i4 ? function(e7, t7, r5) { r5.group_level === 0 && delete r5.group_level; var i5 = r5.group || r5.group_level, s4 = n4(e7.reduceFun), a4 = [], u4 = isNaN(r5.group_level) ? Number.POSITIVE_INFINITY : r5.group_level; t7.forEach(function(e8) { var t8 = a4[a4.length - 1], n5 = i5 ? e8.key : null; if (i5 && Array.isArray(n5) && (n5 = n5.slice(0, u4)), t8 && g(t8.groupKey, n5) === 0) return t8.keys.push([e8.key, e8.id]), void t8.values.push(e8.value); a4.push({ keys: [[e8.key, e8.id]], values: [e8.value], groupKey: n5 }); }), t7 = []; for (var c2 = 0, f4 = a4.length; c2 < f4; c2++) { var d3 = a4[c2], h4 = o2(e7.sourceDB, s4, d3.keys, d3.values, false); if (h4.error && h4.error instanceof Q) throw h4.error; t7.push({ value: h4.error ? null : h4.output, key: d3.groupKey }); } return { rows: l2(t7, r5.limit, r5.skip) }; }(e6, a3, t6) : t6.keys === void 0 ? { total_rows: r4, offset: s3, rows: a3 } : { total_rows: r4, offset: s3, rows: l2(a3, t6.limit, t6.skip) }, t6.update_seq && (u3.update_seq = e6.seq), t6.include_docs) { var f3 = Z(a3.map(d2)); return e6.sourceDB.allDocs({ keys: f3, include_docs: true, conflicts: t6.conflicts, attachments: t6.attachments, binary: t6.binary }).then(function(e7) { var t7 = new c(); return e7.rows.forEach(function(e8) { t7.set(e8.id, e8.doc); }), a3.forEach(function(e8) { var n5 = d2(e8), r5 = t7.get(n5); r5 && (e8.doc = r5); }), u3; }); } return u3; } if (t6.keys === void 0 || t6.keys.length || (t6.limit = 0, delete t6.keys), t6.keys !== void 0) { var f2 = t6.keys.map(function(e7) { var n5 = { startkey: m([e7]), endkey: m([e7, {}]) }; return t6.update_seq && (n5.update_seq = true), a2(n5); }); return Promise.all(f2).then(U).then(u2); } var h3, p3, v3 = { descending: t6.descending }; if (t6.update_seq && (v3.update_seq = true), "start_key" in t6 && (h3 = t6.start_key), "startkey" in t6 && (h3 = t6.startkey), "end_key" in t6 && (p3 = t6.end_key), "endkey" in t6 && (p3 = t6.endkey), h3 !== void 0 && (v3.startkey = t6.descending ? m([h3, {}]) : m([h3])), p3 !== void 0) { var y2 = t6.inclusive_end !== false; t6.descending && (y2 = !y2), v3.endkey = m(y2 ? [p3, {}] : [p3]); } if (t6.key !== void 0) { var _2 = m([t6.key]), k3 = m([t6.key, {}]); v3.descending ? (v3.endkey = _2, v3.startkey = k3) : (v3.startkey = _2, v3.endkey = k3); } return i4 || (typeof t6.limit == "number" && (v3.limit = t6.limit), v3.skip = s3), a2(v3).then(u2); }(e5, t5); })(); } var S2; return { query: function(t5, n5, i4) { var o3 = this; typeof n5 == "function" && (i4 = n5, n5 = {}), n5 = n5 ? function(e5) { return e5.group_level = v2(e5.group_level), e5.limit = v2(e5.limit), e5.skip = v2(e5.skip), e5; }(n5) : {}, typeof t5 == "function" && (t5 = { map: t5 }); var s3 = Promise.resolve().then(function() { return function(t6, n6, i5) { if (typeof t6._query == "function") return function(e5, t7, n7) { return new Promise(function(r4, i6) { e5._query(t7, n7, function(e6, t8) { if (e6) return i6(e6); r4(t8); }); }); }(t6, n6, i5); if (z(t6)) return function(e5, t7, n7) { var r4, i6, o5, s5 = [], u3 = "GET"; if (p2("reduce", n7, s5), p2("include_docs", n7, s5), p2("attachments", n7, s5), p2("limit", n7, s5), p2("descending", n7, s5), p2("group", n7, s5), p2("group_level", n7, s5), p2("skip", n7, s5), p2("stale", n7, s5), p2("conflicts", n7, s5), p2("startkey", n7, s5, true), p2("start_key", n7, s5, true), p2("endkey", n7, s5, true), p2("end_key", n7, s5, true), p2("inclusive_end", n7, s5), p2("key", n7, s5, true), p2("update_seq", n7, s5), s5 = (s5 = s5.join("&")) === "" ? "" : "?" + s5, n7.keys !== void 0) { var c3 = "keys=" + encodeURIComponent(JSON.stringify(n7.keys)); c3.length + s5.length + 1 <= 2e3 ? s5 += (s5[0] === "?" ? "&" : "?") + c3 : (u3 = "POST", typeof t7 == "string" ? r4 = { keys: n7.keys } : t7.keys = n7.keys); } if (typeof t7 == "string") { var l4 = re(t7); return e5.fetch("_design/" + l4[0] + "/_view/" + l4[1] + s5, { headers: new f({ "Content-Type": "application/json" }), method: u3, body: JSON.stringify(r4) }).then(function(e6) { return i6 = e6.ok, o5 = e6.status, e6.json(); }).then(function(e6) { if (!i6) throw e6.status = o5, a(e6); return e6.rows.forEach(function(e7) { if (e7.value && e7.value.error && e7.value.error === "builtin_reduce_error") throw new Error(e7.reason); }), e6; }).then(h2(n7)); } return r4 = r4 || {}, Object.keys(t7).forEach(function(e6) { Array.isArray(t7[e6]) ? r4[e6] = t7[e6] : r4[e6] = t7[e6].toString(); }), e5.fetch("_temp_view" + s5, { headers: new f({ "Content-Type": "application/json" }), method: "POST", body: JSON.stringify(r4) }).then(function(e6) { return i6 = e6.ok, o5 = e6.status, e6.json(); }).then(function(e6) { if (!i6) throw e6.status = o5, a(e6); return e6; }).then(h2(n7)); }(t6, n6, i5); var o4 = { changes_batch_size: t6.__opts.view_update_changes_batch_size || 50 }; if (typeof n6 != "string") return k2(i5, n6), ne.add(function() { return ee(t6, "temp_view/temp_view", n6.map, n6.reduce, true, e4).then(function(e5) { return t7 = q2(e5, o4).then(function() { return A2(e5, i5); }), n7 = function() { return e5.db.destroy(); }, t7.then(function(e6) { return n7().then(function() { return e6; }); }, function(e6) { return n7().then(function() { throw e6; }); }); var t7, n7; }); }), ne.finish(); var s4 = n6, u2 = re(s4), c2 = u2[0], l3 = u2[1]; return t6.get("_design/" + c2).then(function(n7) { var a2 = n7.views && n7.views[l3]; if (!a2) throw new V("ddoc " + n7._id + " has no view named " + l3); return r3(n7, l3), k2(i5, a2), ee(t6, s4, a2.map, a2.reduce, false, e4).then(function(e5) { return i5.stale === "ok" || i5.stale === "update_after" ? (i5.stale === "update_after" && x()(function() { q2(e5, o4); }), A2(e5, i5)) : q2(e5, o4).then(function() { return A2(e5, i5); }); }); }); }(o3, t5, n5); }); return G(s3, i4), s3; }, viewCleanup: (S2 = function() { var t5 = this; return typeof t5._viewCleanup == "function" ? function(e5) { return new Promise(function(t6, n5) { e5._viewCleanup(function(e6, r4) { if (e6) return n5(e6); t6(r4); }); }); }(t5) : z(t5) ? function(e5) { return e5.fetch("_view_cleanup", { headers: new f({ "Content-Type": "application/json" }), method: "POST" }).then(function(e6) { return e6.json(); }); }(t5) : function(t6) { return t6.get("_local/" + e4).then(function(e5) { var n5 = new c(); Object.keys(e5.views).forEach(function(e6) { var t7 = re(e6), r5 = "_design/" + t7[0], i4 = t7[1], o3 = n5.get(r5); o3 || (o3 = new u(), n5.set(r5, o3)), o3.add(i4); }); var r4 = { keys: X(n5), include_docs: true }; return t6.allDocs(r4).then(function(r5) { var i4 = {}; r5.rows.forEach(function(t7) { var r6 = t7.key.substring(8); n5.get(t7.key).forEach(function(n6) { var o4 = r6 + "/" + n6; e5.views[o4] || (o4 = n6); var s3 = Object.keys(e5.views[o4]), a2 = t7.doc && t7.doc.views && t7.doc.views[n6]; s3.forEach(function(e6) { i4[e6] = i4[e6] || a2; }); }); }); var o3 = Object.keys(i4).filter(function(e6) { return !i4[e6]; }).map(function(e6) { return W($2(e6), function() { return new t6.constructor(e6, t6.__opts).destroy(); })(); }); return Promise.all(o3).then(function() { return { ok: true }; }); }); }, j2({ ok: true })); }(t5); }, O()(function(e5) { var t5 = e5.pop(), n5 = S2.apply(this, e5); return typeof t5 == "function" && G(n5, t5), n5; })) }; }("indexes", function(e4, t4) { return function(e5, t5, n4) { var r3 = function(e6) { for (var t6 = 0, n5 = e6.length; t6 < n5; t6++) if (e6[t6].indexOf(".") !== -1) return false; return true; }(e5), i3 = e5.length === 1; return r3 ? i3 ? function(e6, t6, n5) { return function(r4) { n5 && !$e(r4, n5) || t6(r4[e6]); }; }(e5[0], t5, n4) : function(e6, t6, n5) { return function(r4) { if (!n5 || $e(r4, n5)) { for (var i4 = [], o2 = 0, s2 = e6.length; o2 < s2; o2++) i4.push(r4[e6[o2]]); t6(i4); } }; }(e5, t5, n4) : i3 ? function(e6, t6, n5) { var r4 = ue(e6); return function(e7) { if (!n5 || $e(e7, n5)) { for (var i4 = e7, o2 = 0, s2 = r4.length; o2 < s2; o2++) if ((i4 = i4[r4[o2]]) === void 0) return; t6(i4); } }; }(e5[0], t5, n4) : function(e6, t6, n5) { return function(r4) { if (!n5 || $e(r4, n5)) { for (var i4 = [], o2 = 0, s2 = e6.length; o2 < s2; o2++) { for (var a2 = ue(e6[o2]), u2 = r4, c2 = 0, f2 = a2.length; c2 < f2; c2++) if ((u2 = u2[a2[c2]]) === void 0) return; i4.push(u2); } t6(i4); } }; }(e5, t5, n4); }(Object.keys(e4.fields), t4, e4.partial_filter_selector); }, function() { throw new Error("reduce not supported"); }, function(e4, t4) { var n4 = e4.views[t4]; if (!n4.map || !n4.map.fields) throw new Error("ddoc " + e4._id + " with view " + t4 + " doesn't have map.fields defined. maybe it wasn't created by this plugin?"); }); function Ke(e4) { return e4._customFindAbstractMapper || Je; } function Ve(e4) { return e4.fields = e4.fields.map(function(e5) { if (typeof e5 == "string") { var t4 = {}; return t4[e5] = "asc", t4; } return e5; }), e4; } function Qe(e4, t4) { for (var n4 = [], r3 = 0; r3 < t4.def.fields.length; r3++) { var i3 = le(t4.def.fields[r3]); n4.push(e4[i3]); } return n4; } function Ge(e4) { return e4.allDocs({ startkey: "_design/", endkey: "_design/\uFFFF", include_docs: true }).then(function(e5) { var t4 = { indexes: [{ ddoc: null, name: "_all_docs", type: "special", def: { fields: [{ _id: "asc" }] } }] }; return t4.indexes = Re(t4.indexes, e5.rows.filter(function(e6) { return e6.doc.language === "query"; }).map(function(e6) { return (e6.doc.views !== void 0 ? Object.keys(e6.doc.views) : []).map(function(t5) { var n4 = e6.doc.views[t5]; return { ddoc: e6.id, name: t5, type: "json", def: Ve(n4.options.def) }; }); })), t4.indexes.sort(function(e6, t5) { return ae(e6.name, t5.name); }), t4.total_rows = t4.indexes.length, t4; }); } var We = null, Ze = { "\uFFFF": {} }; const Xe = { queryOpts: { limit: 0, startkey: Ze, endkey: We }, inMemoryFields: [] }; function Ye(e4, t4) { for (var n4 = e4.def.fields.map(le), r3 = 0, i3 = n4.length; r3 < i3; r3++) if (t4 === n4[r3]) return true; return false; } function He(e4, t4) { return le(e4[t4]) !== "$eq"; } function et(e4, t4) { var n4 = t4.def.fields.map(le); return e4.slice().sort(function(e5, t5) { var r3 = n4.indexOf(e5), i3 = n4.indexOf(t5); return r3 === -1 && (r3 = Number.MAX_VALUE), i3 === -1 && (i3 = Number.MAX_VALUE), ae(r3, i3); }); } function tt(e4, t4, n4, r3) { var i3 = Re(e4, function(e5, t5, n5) { for (var r4 = false, i4 = 0, o2 = (n5 = et(n5, e5)).length; i4 < o2; i4++) { var s2 = n5[i4]; if (r4 || !Ye(e5, s2)) return n5.slice(i4); i4 < o2 - 1 && He(t5, s2) && (r4 = true); } return []; }(t4, n4, r3), function(e5) { var t5 = []; return Object.keys(e5).forEach(function(n5) { var r4 = e5[n5]; Object.keys(r4).forEach(function(e6) { e6 === "$ne" && t5.push(n5); }); }), t5; }(n4)); return et(function(e5) { for (var t5 = {}, n5 = 0; n5 < e5.length; n5++) t5["$" + e5[n5]] = true; return Object.keys(t5).map(function(e6) { return e6.substring(1); }); }(i3), t4); } var nt = ["$eq", "$gt", "$gte", "$lt", "$lte"]; function rt(e4) { return nt.indexOf(e4) === -1; } function it(e4, t4, n4, r3) { var i3 = e4.def.fields.map(le); return !!function(e5, t5, n5) { if (t5) { var r4 = (s2 = e5, !((o2 = t5).length > s2.length) && Ue(o2, s2)), i4 = Ue(n5, e5); return r4 && i4; } var o2, s2; return function(e6, t6) { e6 = e6.slice(); for (var n6 = 0, r5 = t6.length; n6 < r5; n6++) { var i5 = t6[n6]; if (!e6.length) break; var o3 = e6.indexOf(i5); if (o3 === -1) return false; e6.splice(o3, 1); } return true; }(n5, e5); }(i3, t4, n4) && function(e5, t5) { var n5 = t5[e5[0]]; return n5 === void 0 || !(Object.keys(n5).length === 1 && le(n5) === "$ne"); }(i3, r3); } function ot(e4, t4) { switch (e4) { case "$eq": return { startkey: t4, endkey: t4 }; case "$lte": return { endkey: t4 }; case "$gte": return { startkey: t4 }; case "$lt": return { endkey: t4, inclusive_end: false }; case "$gt": return { startkey: t4, inclusive_start: false }; } } function st(e4, t4) { return t4.defaultUsed ? function(e5) { return { queryOpts: { startkey: null }, inMemoryFields: [Object.keys(e5)] }; }(e4) : t4.def.fields.length === 1 ? function(e5, t5) { var n4, r3 = le(t5.def.fields[0]), i3 = e5[r3] || {}, o2 = []; return Object.keys(i3).forEach(function(e6) { rt(e6) && o2.push(r3); var t6 = function(e7, t7) { switch (e7) { case "$eq": return { key: t7 }; case "$lte": return { endkey: t7 }; case "$gte": return { startkey: t7 }; case "$lt": return { endkey: t7, inclusive_end: false }; case "$gt": return { startkey: t7, inclusive_start: false }; } return { startkey: We }; }(e6, i3[e6]); n4 = n4 ? Fe([n4, t6]) : t6; }), { queryOpts: n4, inMemoryFields: o2 }; }(e4, t4) : function(e5, t5) { var n4, r3, i3 = t5.def.fields.map(le), o2 = [], s2 = [], a2 = []; function u2(e6) { n4 !== false && s2.push(We), r3 !== false && a2.push(Ze), o2 = i3.slice(e6); } for (var c2 = 0, f2 = i3.length; c2 < f2; c2++) { var l2 = e5[i3[c2]]; if (!l2 || !Object.keys(l2).length) { u2(c2); break; } if (Object.keys(l2).some(rt)) { u2(c2); break; } if (c2 > 0) { var d2 = "$gt" in l2 || "$gte" in l2 || "$lt" in l2 || "$lte" in l2, h2 = Object.keys(e5[i3[c2 - 1]]), p2 = ze(h2, ["$eq"]), v2 = ze(h2, Object.keys(l2)); if (d2 && !p2 && !v2) { u2(c2); break; } } for (var y2 = Object.keys(l2), g2 = null, _2 = 0; _2 < y2.length; _2++) { var m2 = y2[_2], b2 = ot(m2, l2[m2]); g2 = g2 ? Fe([g2, b2]) : b2; } s2.push("startkey" in g2 ? g2.startkey : We), a2.push("endkey" in g2 ? g2.endkey : Ze), "inclusive_start" in g2 && (n4 = g2.inclusive_start), "inclusive_end" in g2 && (r3 = g2.inclusive_end); } var w2 = { startkey: s2, endkey: a2 }; return n4 !== void 0 && (w2.inclusive_start = n4), r3 !== void 0 && (w2.inclusive_end = r3), { queryOpts: w2, inMemoryFields: o2 }; }(e4, t4); } function at(e4, t4) { var n4 = e4.selector, r3 = e4.sort; if (function(e5) { return Object.keys(e5).map(function(t5) { return e5[t5]; }).some(function(e6) { return typeof e6 == "object" && Object.keys(e6).length === 0; }); }(n4)) return F({}, Xe, { index: t4[0] }); var i3 = function(e5, t5) { var n5, r4 = Object.keys(e5), i4 = t5 ? t5.map(le) : []; return n5 = r4.length >= i4.length ? r4 : i4, i4.length === 0 ? { fields: n5 } : { fields: n5 = n5.sort(function(e6, t6) { var n6 = i4.indexOf(e6); n6 === -1 && (n6 = Number.MAX_VALUE); var r5 = i4.indexOf(t6); return r5 === -1 && (r5 = Number.MAX_VALUE), n6 < r5 ? -1 : n6 > r5 ? 1 : 0; }), sortOrder: t5.map(le) }; }(n4, r3), o2 = i3.fields, s2 = function(e5, t5, n5, r4, i4) { var o3 = function(e6, t6, n6, r5) { return r5.filter(function(r6) { return it(r6, n6, t6, e6); }); }(e5, t5, n5, r4); if (o3.length === 0) { if (i4) throw { error: "no_usable_index", message: "There is no index available for this selector." }; var s3 = r4[0]; return s3.defaultUsed = true, s3; } if (o3.length === 1 && !i4) return o3[0]; var a3 = function(e6) { for (var t6 = {}, n6 = 0, r5 = e6.length; n6 < r5; n6++) t6[e6[n6]] = true; return t6; }(t5); if (i4) { var u2 = "_design/" + i4[0], c2 = i4.length === 2 && i4[1], f2 = o3.find(function(e6) { return !(!c2 || e6.ddoc !== u2 || c2 !== e6.name) || e6.ddoc === u2; }); if (!f2) throw { error: "unknown_error", message: "Could not find that index or could not use that index for the query" }; return f2; } return function(e6, t6) { for (var n6 = null, r5 = -1, i5 = 0, o4 = e6.length; i5 < o4; i5++) { var s4 = e6[i5], a4 = t6(s4); a4 > r5 && (r5 = a4, n6 = s4); } return n6; }(o3, function(e6) { for (var t6 = e6.def.fields.map(le), n6 = 0, r5 = 0, i5 = t6.length; r5 < i5; r5++) { var o4 = t6[r5]; a3[o4] && n6++; } return n6; }); }(n4, o2, i3.sortOrder, t4, e4.use_index), a2 = st(n4, s2); return { queryOpts: a2.queryOpts, index: s2, inMemoryFields: tt(a2.inMemoryFields, s2, n4, o2) }; } function ut(e4, t4, n4) { var r3, i3; return t4.selector && (Pe(t4.selector, false), t4.selector = ye(t4.selector)), t4.sort && (t4.sort = function(e5) { if (!Array.isArray(e5)) throw new Error("invalid sort json - should be an array"); return e5.map(function(e6) { if (typeof e6 == "string") { var t5 = {}; return t5[e6] = "asc", t5; } return e6; }); }(t4.sort)), t4.use_index && (t4.use_index = (i3 = [], typeof (r3 = t4.use_index) == "string" ? i3.push(r3) : i3 = r3, i3.map(function(e5) { return e5.replace("_design/", ""); }))), function(e5) { if (typeof e5.selector != "object") throw new Error("you must provide a selector when you find()"); }(t4), Ge(e4).then(function(r4) { e4.constructor.emit("debug", ["find", "planning query", t4]); var i4 = at(t4, r4.indexes); e4.constructor.emit("debug", ["find", "query plan", i4]); var o2 = i4.index; !function(e5, t5) { if (t5.defaultUsed && e5.sort) { var n5 = e5.sort.filter(function(e6) { return Object.keys(e6)[0] !== "_id"; }).map(function(e6) { return Object.keys(e6)[0]; }); if (n5.length > 0) throw new Error('Cannot sort on field(s) "' + n5.join(",") + '" when using the default index'); } t5.defaultUsed; }(t4, o2); var s2 = F({ include_docs: true, reduce: false, indexes_count: r4.total_rows }, i4.queryOpts); return "startkey" in s2 && "endkey" in s2 && g(s2.startkey, s2.endkey) > 0 ? { docs: [] } : (t4.sort && typeof t4.sort[0] != "string" && de(t4.sort[0]) === "desc" && (s2.descending = true, s2 = function(e5) { var t5 = I(e5); return delete t5.startkey, delete t5.endkey, delete t5.inclusive_start, delete t5.inclusive_end, "endkey" in e5 && (t5.startkey = e5.endkey), "startkey" in e5 && (t5.endkey = e5.startkey), "inclusive_start" in e5 && (t5.inclusive_end = e5.inclusive_start), "inclusive_end" in e5 && (t5.inclusive_start = e5.inclusive_end), t5; }(s2)), i4.inMemoryFields.length || ("limit" in t4 && (s2.limit = t4.limit), "skip" in t4 && (s2.skip = t4.skip)), n4 ? Promise.resolve(i4, s2) : Promise.resolve().then(function() { if (o2.name === "_all_docs") return function(e5, t6) { var n6 = I(t6); return n6.descending ? ("endkey" in n6 && typeof n6.endkey != "string" && (n6.endkey = ""), "startkey" in n6 && typeof n6.startkey != "string" && (n6.limit = 0)) : ("startkey" in n6 && typeof n6.startkey != "string" && (n6.startkey = ""), "endkey" in n6 && typeof n6.endkey != "string" && (n6.limit = 0)), "key" in n6 && typeof n6.key != "string" && (n6.limit = 0), n6.limit > 0 && n6.indexes_count && (n6.original_limit = n6.limit, n6.limit += n6.indexes_count), e5.allDocs(n6).then(function(e6) { return e6.rows = e6.rows.filter(function(e7) { return !/^_design\//.test(e7.id); }), n6.original_limit && (n6.limit = n6.original_limit), e6.rows = e6.rows.slice(0, n6.limit), e6; }); }(e4, s2); var t5, n5 = (t5 = o2).ddoc.substring(8) + "/" + t5.name; return Ke(e4).query.call(e4, n5, s2); }).then(function(e5) { s2.inclusive_start === false && (e5.rows = function(e6, t5, n6) { for (var r5 = n6.def.fields, i5 = 0, o3 = e6.length; i5 < o3; i5++) { var s3 = Qe(e6[i5].doc, n6); if (r5.length === 1) s3 = s3[0]; else for (; s3.length > t5.length; ) s3.pop(); if (Math.abs(g(s3, t5)) > 0) break; } return i5 > 0 ? e6.slice(i5) : e6; }(e5.rows, s2.startkey, o2)), i4.inMemoryFields.length && (e5.rows = ge(e5.rows, t4, i4.inMemoryFields)); var n5 = { docs: e5.rows.map(function(e6) { var n6 = e6.doc; return t4.fields ? function(e7, t5) { for (var n7 = {}, r5 = 0, i5 = t5.length; r5 < i5; r5++) { var o3 = ue(t5[r5]), s3 = oe(e7, o3); s3 !== void 0 && se(n7, o3, s3); } return n7; }(n6, t4.fields) : n6; }) }; return o2.defaultUsed && (n5.warning = "No matching index found, create an index to optimize query time."), n5; })); }); } var ct = Ne(function(e4, t4) { var n4, r3 = I((t4 = xe(t4)).index); function i3() { return n4 || (n4 = C(JSON.stringify(t4))); } t4.index = Ve(t4.index), function(e5) { var t5 = e5.fields.filter(function(e6) { return de(e6) === "asc"; }); if (t5.length !== 0 && t5.length !== e5.fields.length) throw new Error("unsupported mixed sorting"); }(t4.index); var o2 = t4.name || "idx-" + i3(), s2 = t4.ddoc || "idx-" + i3(), a2 = "_design/" + s2, u2 = false, c2 = false; return e4.constructor.emit("debug", ["find", "creating index", a2]), J(e4, a2, function(e5) { return e5._rev && e5.language !== "query" && (u2 = true), e5.language = "query", e5.views = e5.views || {}, !(c2 = !!e5.views[o2]) && (e5.views[o2] = { map: { fields: Fe(t4.index.fields) }, reduce: "_count", options: { def: r3 } }, e5); }).then(function() { if (u2) throw new Error('invalid language for ddoc with id "' + a2 + '" (should be "query")'); }).then(function() { var t5 = s2 + "/" + o2; return Ke(e4).query.call(e4, t5, { limit: 0, reduce: false }).then(function() { return { id: a2, name: o2, result: c2 ? "exists" : "created" }; }); }); }), ft = Ne(ut), lt = Ne(function(e4, t4) { return ut(e4, t4, true).then(function(n4) { return { dbname: e4.name, index: n4.index, selector: t4.selector, range: { start_key: n4.queryOpts.startkey, end_key: n4.queryOpts.endkey }, opts: { use_index: t4.use_index || [], bookmark: "nil", limit: t4.limit, skip: t4.skip, sort: t4.sort || {}, fields: t4.fields, conflicts: false, r: [49] }, limit: t4.limit, skip: t4.skip || 0, fields: t4.fields }; }); }), dt = Ne(Ge), ht = Ne(function(e4, t4) { if (!t4.ddoc) throw new Error("you must supply an index.ddoc when deleting"); if (!t4.name) throw new Error("you must supply an index.name when deleting"); var n4 = t4.ddoc, r3 = t4.name; return J(e4, n4, function(e5) { return Object.keys(e5.views).length === 1 && e5.views[r3] ? { _id: n4, _deleted: true } : (delete e5.views[r3], e5); }).then(function() { return Ke(e4).viewCleanup.apply(e4); }).then(function() { return { ok: true }; }); }), pt = {}; pt.createIndex = T(function(e4, t4) { if (typeof e4 != "object") return t4(new Error("you must provide an index to create")); (z(this) ? De : ct)(this, e4, t4); }), pt.find = T(function(e4, t4) { if (t4 === void 0 && (t4 = e4, e4 = void 0), typeof e4 != "object") return t4(new Error("you must provide search parameters to find()")); (z(this) ? Le : ft)(this, e4, t4); }), pt.explain = T(function(e4, t4) { if (t4 === void 0 && (t4 = e4, e4 = void 0), typeof e4 != "object") return t4(new Error("you must provide search parameters to explain()")); (z(this) ? Be : lt)(this, e4, t4); }), pt.getIndexes = T(function(e4) { (z(this) ? Ie : dt)(this, e4); }), pt.deleteIndex = T(function(e4, t4) { if (typeof e4 != "object") return t4(new Error("you must provide an index to delete")); (z(this) ? Te : ht)(this, e4, t4); }); const vt = pt; }, 552: (e3) => { function t3(e4, t4) { return function(...n4) { function r2() { let r3 = null; const i2 = t4 === "query" ? 1 : 0; n4.length > i2 && typeof n4[n4.length - 1] == "function" && (r3 = n4.pop()); let o = e4._originals[t4].bind(e4); for (const n5 of e4._handlers[t4]) o = n5.bind(e4, o); const s = o(...n4); return s.then && r3 && function(e5, t5) { e5.then((...e6) => { t5(null, ...e6); }).catch((e6) => { t5(e6); }); }(s, r3), s; } return t4 !== "changes" && e4.taskqueue && !e4.taskqueue.isReady ? new Promise((t5, n5) => { e4.taskqueue.addTask((e5) => { e5 ? n5(e5) : t5(); }); }).then(r2) : r2(); }; } const n3 = { install: function(e4, n4 = {}) { e4._originals && e4._handlers || (e4._originals = {}, e4._handlers = {}); for (const [r2, i2] of Object.entries(n4)) { if (!(r2 in e4)) throw new Error(`Method '${r2}' does not exist on given base, so it cannot be wrapped.`); r2 in e4._originals || (e4._originals[r2] = e4[r2]), r2 in e4._handlers ? e4._handlers[r2].unshift(i2) : (e4._handlers[r2] = [i2], e4[r2] = t3(e4, r2)); } }, uninstall: function(e4, t4) { if (!e4._originals || !e4._handlers) throw new Error("No wrapper methods installed, so no methods can be uninstalled."); for (const [n4, r2] of Object.entries(t4)) { const t5 = `Wrapper method for '${n4}' not installed: ${r2.toString()}`; if (!(n4 in e4._handlers)) throw new Error(t5); const i2 = e4._handlers[n4].indexOf(r2); if (i2 === -1) throw new Error(t5); e4._handlers[n4].splice(i2, 1); } } }; try { e3.exports = n3; } catch (e4) { } try { window.PouchDBWrappers = n3; } catch (e4) { } }, 322: (e3) => { e3.exports = function(e4) { var t3 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; function n3(e5, t4) { var n4 = e5[0], r3 = e5[1], i3 = e5[2], o2 = e5[3]; r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & i3 | ~r3 & o2) + t4[0] - 680876936 | 0) << 7 | n4 >>> 25) + r3 | 0) & r3 | ~n4 & i3) + t4[1] - 389564586 | 0) << 12 | o2 >>> 20) + n4 | 0) & n4 | ~o2 & r3) + t4[2] + 606105819 | 0) << 17 | i3 >>> 15) + o2 | 0) & o2 | ~i3 & n4) + t4[3] - 1044525330 | 0) << 22 | r3 >>> 10) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & i3 | ~r3 & o2) + t4[4] - 176418897 | 0) << 7 | n4 >>> 25) + r3 | 0) & r3 | ~n4 & i3) + t4[5] + 1200080426 | 0) << 12 | o2 >>> 20) + n4 | 0) & n4 | ~o2 & r3) + t4[6] - 1473231341 | 0) << 17 | i3 >>> 15) + o2 | 0) & o2 | ~i3 & n4) + t4[7] - 45705983 | 0) << 22 | r3 >>> 10) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & i3 | ~r3 & o2) + t4[8] + 1770035416 | 0) << 7 | n4 >>> 25) + r3 | 0) & r3 | ~n4 & i3) + t4[9] - 1958414417 | 0) << 12 | o2 >>> 20) + n4 | 0) & n4 | ~o2 & r3) + t4[10] - 42063 | 0) << 17 | i3 >>> 15) + o2 | 0) & o2 | ~i3 & n4) + t4[11] - 1990404162 | 0) << 22 | r3 >>> 10) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & i3 | ~r3 & o2) + t4[12] + 1804603682 | 0) << 7 | n4 >>> 25) + r3 | 0) & r3 | ~n4 & i3) + t4[13] - 40341101 | 0) << 12 | o2 >>> 20) + n4 | 0) & n4 | ~o2 & r3) + t4[14] - 1502002290 | 0) << 17 | i3 >>> 15) + o2 | 0) & o2 | ~i3 & n4) + t4[15] + 1236535329 | 0) << 22 | r3 >>> 10) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & o2 | i3 & ~o2) + t4[1] - 165796510 | 0) << 5 | n4 >>> 27) + r3 | 0) & i3 | r3 & ~i3) + t4[6] - 1069501632 | 0) << 9 | o2 >>> 23) + n4 | 0) & r3 | n4 & ~r3) + t4[11] + 643717713 | 0) << 14 | i3 >>> 18) + o2 | 0) & n4 | o2 & ~n4) + t4[0] - 373897302 | 0) << 20 | r3 >>> 12) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & o2 | i3 & ~o2) + t4[5] - 701558691 | 0) << 5 | n4 >>> 27) + r3 | 0) & i3 | r3 & ~i3) + t4[10] + 38016083 | 0) << 9 | o2 >>> 23) + n4 | 0) & r3 | n4 & ~r3) + t4[15] - 660478335 | 0) << 14 | i3 >>> 18) + o2 | 0) & n4 | o2 & ~n4) + t4[4] - 405537848 | 0) << 20 | r3 >>> 12) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & o2 | i3 & ~o2) + t4[9] + 568446438 | 0) << 5 | n4 >>> 27) + r3 | 0) & i3 | r3 & ~i3) + t4[14] - 1019803690 | 0) << 9 | o2 >>> 23) + n4 | 0) & r3 | n4 & ~r3) + t4[3] - 187363961 | 0) << 14 | i3 >>> 18) + o2 | 0) & n4 | o2 & ~n4) + t4[8] + 1163531501 | 0) << 20 | r3 >>> 12) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 & o2 | i3 & ~o2) + t4[13] - 1444681467 | 0) << 5 | n4 >>> 27) + r3 | 0) & i3 | r3 & ~i3) + t4[2] - 51403784 | 0) << 9 | o2 >>> 23) + n4 | 0) & r3 | n4 & ~r3) + t4[7] + 1735328473 | 0) << 14 | i3 >>> 18) + o2 | 0) & n4 | o2 & ~n4) + t4[12] - 1926607734 | 0) << 20 | r3 >>> 12) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 ^ i3 ^ o2) + t4[5] - 378558 | 0) << 4 | n4 >>> 28) + r3 | 0) ^ r3 ^ i3) + t4[8] - 2022574463 | 0) << 11 | o2 >>> 21) + n4 | 0) ^ n4 ^ r3) + t4[11] + 1839030562 | 0) << 16 | i3 >>> 16) + o2 | 0) ^ o2 ^ n4) + t4[14] - 35309556 | 0) << 23 | r3 >>> 9) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 ^ i3 ^ o2) + t4[1] - 1530992060 | 0) << 4 | n4 >>> 28) + r3 | 0) ^ r3 ^ i3) + t4[4] + 1272893353 | 0) << 11 | o2 >>> 21) + n4 | 0) ^ n4 ^ r3) + t4[7] - 155497632 | 0) << 16 | i3 >>> 16) + o2 | 0) ^ o2 ^ n4) + t4[10] - 1094730640 | 0) << 23 | r3 >>> 9) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 ^ i3 ^ o2) + t4[13] + 681279174 | 0) << 4 | n4 >>> 28) + r3 | 0) ^ r3 ^ i3) + t4[0] - 358537222 | 0) << 11 | o2 >>> 21) + n4 | 0) ^ n4 ^ r3) + t4[3] - 722521979 | 0) << 16 | i3 >>> 16) + o2 | 0) ^ o2 ^ n4) + t4[6] + 76029189 | 0) << 23 | r3 >>> 9) + i3 | 0, r3 = ((r3 += ((i3 = ((i3 += ((o2 = ((o2 += ((n4 = ((n4 += (r3 ^ i3 ^ o2) + t4[9] - 640364487 | 0) << 4 | n4 >>> 28) + r3 | 0) ^ r3 ^ i3) + t4[12] - 421815835 | 0) << 11 | o2 >>> 21) + n4 | 0) ^ n4 ^ r3) + t4[15] + 530742520 | 0) << 16 | i3 >>> 16) + o2 | 0) ^ o2 ^ n4) + t4[2] - 995338651 | 0) << 23 | r3 >>> 9) + i3 | 0, r3 = ((r3 += ((o2 = ((o2 += (r3 ^ ((n4 = ((n4 += (i3 ^ (r3 | ~o2)) + t4[0] - 198630844 | 0) << 6 | n4 >>> 26) + r3 | 0) | ~i3)) + t4[7] + 1126891415 | 0) << 10 | o2 >>> 22) + n4 | 0) ^ ((i3 = ((i3 += (n4 ^ (o2 | ~r3)) + t4[14] - 1416354905 | 0) << 15 | i3 >>> 17) + o2 | 0) | ~n4)) + t4[5] - 57434055 | 0) << 21 | r3 >>> 11) + i3 | 0, r3 = ((r3 += ((o2 = ((o2 += (r3 ^ ((n4 = ((n4 += (i3 ^ (r3 | ~o2)) + t4[12] + 1700485571 | 0) << 6 | n4 >>> 26) + r3 | 0) | ~i3)) + t4[3] - 1894986606 | 0) << 10 | o2 >>> 22) + n4 | 0) ^ ((i3 = ((i3 += (n4 ^ (o2 | ~r3)) + t4[10] - 1051523 | 0) << 15 | i3 >>> 17) + o2 | 0) | ~n4)) + t4[1] - 2054922799 | 0) << 21 | r3 >>> 11) + i3 | 0, r3 = ((r3 += ((o2 = ((o2 += (r3 ^ ((n4 = ((n4 += (i3 ^ (r3 | ~o2)) + t4[8] + 1873313359 | 0) << 6 | n4 >>> 26) + r3 | 0) | ~i3)) + t4[15] - 30611744 | 0) << 10 | o2 >>> 22) + n4 | 0) ^ ((i3 = ((i3 += (n4 ^ (o2 | ~r3)) + t4[6] - 1560198380 | 0) << 15 | i3 >>> 17) + o2 | 0) | ~n4)) + t4[13] + 1309151649 | 0) << 21 | r3 >>> 11) + i3 | 0, r3 = ((r3 += ((o2 = ((o2 += (r3 ^ ((n4 = ((n4 += (i3 ^ (r3 | ~o2)) + t4[4] - 145523070 | 0) << 6 | n4 >>> 26) + r3 | 0) | ~i3)) + t4[11] - 1120210379 | 0) << 10 | o2 >>> 22) + n4 | 0) ^ ((i3 = ((i3 += (n4 ^ (o2 | ~r3)) + t4[2] + 718787259 | 0) << 15 | i3 >>> 17) + o2 | 0) | ~n4)) + t4[9] - 343485551 | 0) << 21 | r3 >>> 11) + i3 | 0, e5[0] = n4 + e5[0] | 0, e5[1] = r3 + e5[1] | 0, e5[2] = i3 + e5[2] | 0, e5[3] = o2 + e5[3] | 0; } function r2(e5) { var t4, n4 = []; for (t4 = 0; t4 < 64; t4 += 4) n4[t4 >> 2] = e5.charCodeAt(t4) + (e5.charCodeAt(t4 + 1) << 8) + (e5.charCodeAt(t4 + 2) << 16) + (e5.charCodeAt(t4 + 3) << 24); return n4; } function i2(e5) { var t4, n4 = []; for (t4 = 0; t4 < 64; t4 += 4) n4[t4 >> 2] = e5[t4] + (e5[t4 + 1] << 8) + (e5[t4 + 2] << 16) + (e5[t4 + 3] << 24); return n4; } function o(e5) { var t4, i3, o2, s2, a2, u2, c2 = e5.length, f2 = [1732584193, -271733879, -1732584194, 271733878]; for (t4 = 64; t4 <= c2; t4 += 64) n3(f2, r2(e5.substring(t4 - 64, t4))); for (i3 = (e5 = e5.substring(t4 - 64)).length, o2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], t4 = 0; t4 < i3; t4 += 1) o2[t4 >> 2] |= e5.charCodeAt(t4) << (t4 % 4 << 3); if (o2[t4 >> 2] |= 128 << (t4 % 4 << 3), t4 > 55) for (n3(f2, o2), t4 = 0; t4 < 16; t4 += 1) o2[t4] = 0; return s2 = (s2 = 8 * c2).toString(16).match(/(.*?)(.{0,8})$/), a2 = parseInt(s2[2], 16), u2 = parseInt(s2[1], 16) || 0, o2[14] = a2, o2[15] = u2, n3(f2, o2), f2; } function s(e5) { var n4, r3 = ""; for (n4 = 0; n4 < 4; n4 += 1) r3 += t3[e5 >> 8 * n4 + 4 & 15] + t3[e5 >> 8 * n4 & 15]; return r3; } function a(e5) { var t4; for (t4 = 0; t4 < e5.length; t4 += 1) e5[t4] = s(e5[t4]); return e5.join(""); } function u(e5) { return /[\u0080-\uFFFF]/.test(e5) && (e5 = unescape(encodeURIComponent(e5))), e5; } function c(e5) { var t4, n4 = [], r3 = e5.length; for (t4 = 0; t4 < r3 - 1; t4 += 2) n4.push(parseInt(e5.substr(t4, 2), 16)); return String.fromCharCode.apply(String, n4); } function f() { this.reset(); } return a(o("hello")), typeof ArrayBuffer == "undefined" || ArrayBuffer.prototype.slice || function() { function e5(e6, t4) { return (e6 = 0 | e6 || 0) < 0 ? Math.max(e6 + t4, 0) : Math.min(e6, t4); } ArrayBuffer.prototype.slice = function(t4, n4) { var r3, i3, o2, s2, a2 = this.byteLength, u2 = e5(t4, a2), c2 = a2; return n4 !== void 0 && (c2 = e5(n4, a2)), u2 > c2 ? new ArrayBuffer(0) : (r3 = c2 - u2, i3 = new ArrayBuffer(r3), o2 = new Uint8Array(i3), s2 = new Uint8Array(this, u2, r3), o2.set(s2), i3); }; }(), f.prototype.append = function(e5) { return this.appendBinary(u(e5)), this; }, f.prototype.appendBinary = function(e5) { this._buff += e5, this._length += e5.length; var t4, i3 = this._buff.length; for (t4 = 64; t4 <= i3; t4 += 64) n3(this._hash, r2(this._buff.substring(t4 - 64, t4))); return this._buff = this._buff.substring(t4 - 64), this; }, f.prototype.end = function(e5) { var t4, n4, r3 = this._buff, i3 = r3.length, o2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (t4 = 0; t4 < i3; t4 += 1) o2[t4 >> 2] |= r3.charCodeAt(t4) << (t4 % 4 << 3); return this._finish(o2, i3), n4 = a(this._hash), e5 && (n4 = c(n4)), this.reset(), n4; }, f.prototype.reset = function() { return this._buff = "", this._length = 0, this._hash = [1732584193, -271733879, -1732584194, 271733878], this; }, f.prototype.getState = function() { return { buff: this._buff, length: this._length, hash: this._hash.slice() }; }, f.prototype.setState = function(e5) { return this._buff = e5.buff, this._length = e5.length, this._hash = e5.hash, this; }, f.prototype.destroy = function() { delete this._hash, delete this._buff, delete this._length; }, f.prototype._finish = function(e5, t4) { var r3, i3, o2, s2 = t4; if (e5[s2 >> 2] |= 128 << (s2 % 4 << 3), s2 > 55) for (n3(this._hash, e5), s2 = 0; s2 < 16; s2 += 1) e5[s2] = 0; r3 = (r3 = 8 * this._length).toString(16).match(/(.*?)(.{0,8})$/), i3 = parseInt(r3[2], 16), o2 = parseInt(r3[1], 16) || 0, e5[14] = i3, e5[15] = o2, n3(this._hash, e5); }, f.hash = function(e5, t4) { return f.hashBinary(u(e5), t4); }, f.hashBinary = function(e5, t4) { var n4 = a(o(e5)); return t4 ? c(n4) : n4; }, f.ArrayBuffer = function() { this.reset(); }, f.ArrayBuffer.prototype.append = function(e5) { var t4, r3, o2, s2, a2, u2 = (r3 = this._buff.buffer, o2 = e5, s2 = true, (a2 = new Uint8Array(r3.byteLength + o2.byteLength)).set(new Uint8Array(r3)), a2.set(new Uint8Array(o2), r3.byteLength), s2 ? a2 : a2.buffer), c2 = u2.length; for (this._length += e5.byteLength, t4 = 64; t4 <= c2; t4 += 64) n3(this._hash, i2(u2.subarray(t4 - 64, t4))); return this._buff = t4 - 64 < c2 ? new Uint8Array(u2.buffer.slice(t4 - 64)) : new Uint8Array(0), this; }, f.ArrayBuffer.prototype.end = function(e5) { var t4, n4, r3 = this._buff, i3 = r3.length, o2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (t4 = 0; t4 < i3; t4 += 1) o2[t4 >> 2] |= r3[t4] << (t4 % 4 << 3); return this._finish(o2, i3), n4 = a(this._hash), e5 && (n4 = c(n4)), this.reset(), n4; }, f.ArrayBuffer.prototype.reset = function() { return this._buff = new Uint8Array(0), this._length = 0, this._hash = [1732584193, -271733879, -1732584194, 271733878], this; }, f.ArrayBuffer.prototype.getState = function() { var e5, t4 = f.prototype.getState.call(this); return t4.buff = (e5 = t4.buff, String.fromCharCode.apply(null, new Uint8Array(e5))), t4; }, f.ArrayBuffer.prototype.setState = function(e5) { return e5.buff = function(e6, t4) { var n4, r3 = e6.length, i3 = new ArrayBuffer(r3), o2 = new Uint8Array(i3); for (n4 = 0; n4 < r3; n4 += 1) o2[n4] = e6.charCodeAt(n4); return t4 ? o2 : i3; }(e5.buff, true), f.prototype.setState.call(this, e5); }, f.ArrayBuffer.prototype.destroy = f.prototype.destroy, f.ArrayBuffer.prototype._finish = f.prototype._finish, f.ArrayBuffer.hash = function(e5, t4) { var r3 = a(function(e6) { var t5, r4, o2, s2, a2, u2, c2 = e6.length, f2 = [1732584193, -271733879, -1732584194, 271733878]; for (t5 = 64; t5 <= c2; t5 += 64) n3(f2, i2(e6.subarray(t5 - 64, t5))); for (r4 = (e6 = t5 - 64 < c2 ? e6.subarray(t5 - 64) : new Uint8Array(0)).length, o2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], t5 = 0; t5 < r4; t5 += 1) o2[t5 >> 2] |= e6[t5] << (t5 % 4 << 3); if (o2[t5 >> 2] |= 128 << (t5 % 4 << 3), t5 > 55) for (n3(f2, o2), t5 = 0; t5 < 16; t5 += 1) o2[t5] = 0; return s2 = (s2 = 8 * c2).toString(16).match(/(.*?)(.{0,8})$/), a2 = parseInt(s2[2], 16), u2 = parseInt(s2[1], 16) || 0, o2[14] = a2, o2[15] = u2, n3(f2, o2), f2; }(new Uint8Array(e5))); return t4 ? c(r3) : r3; }, f; }(); }, 380: (e3, t3, n3) => { const r2 = n3(552); function i2(e4) { return e4[0] !== "_"; } function o(e4) { return !(typeof e4._id != "string" || !/^_local/.test(e4._id)) || !!e4._deleted && Object.keys(e4).filter(i2).length === 0; } function s(e4) { const t4 = function(t5) { return !o(t5) && e4.incoming ? e4.incoming(t5) : t5; }, n4 = function(t5) { return !o(t5) && e4.outgoing ? e4.outgoing(t5) : t5; }, i3 = { async get(e5, ...t5) { const r3 = await e5(...t5); return Array.isArray(r3) ? (await Promise.all(r3.map(async (e6) => { e6.ok && (e6.ok = await n4(e6.ok)); })), r3) : n4(r3); }, bulkDocs: async (e5, n5, ...r3) => (n5.docs ? n5.docs = await Promise.all(n5.docs.map(t4)) : n5 = await Promise.all(n5.map(t4)), e5(n5, ...r3)), async allDocs(e5, ...t5) { const r3 = await e5(...t5); return await Promise.all(r3.rows.map(async (e6) => { e6.doc && (e6.doc = await n4(e6.doc)); })), r3; }, async bulkGet(e5, ...t5) { const r3 = async (e6) => e6.ok ? { ok: await n4(e6.ok) } : e6; let { results: i4, ...o2 } = await e5(...t5); return i4 = await Promise.all(i4.map(async (e6) => { const { id: t6, docs: n5 } = e6; return t6 && n5 && Array.isArray(n5) ? { id: t6, docs: await Promise.all(n5.map(r3)) } : e6; })), { results: i4, ...o2 }; }, changes(e5, ...t5) { async function r3(e6) { return e6.doc ? (e6.doc = await n4(e6.doc), e6) : e6; } async function i4(e6) { return e6.results ? (e6.results = await Promise.all(e6.results.map(r3)), e6) : e6; } const o2 = e5(...t5), { on: s2, then: a } = o2; return Object.assign(o2, { on(e6, t6) { const n5 = t6; return e6 === "change" ? t6 = async (e7) => { n5(await r3(e7)); } : e6 === "complete" && (t6 = async (e7) => { n5(await i4(e7)); }), s2.call(o2, e6, t6); }, then: (e6, t6) => a.call(o2, i4).then(e6, t6) }); } }; this.type() === "http" && (i3.put = async function(e5, n5, ...r3) { return e5(n5 = await t4(n5), ...r3); }, i3.query = async function(e5, ...t5) { const r3 = await e5(...t5); return await Promise.all(r3.rows.map(async (e6) => { e6.doc && (e6.doc = await n4(e6.doc)); })), r3; }), r2.install(this, i3); } e3.exports = { transform: s, filter: s }, typeof window != "undefined" && window.PouchDB && window.PouchDB.plugin(t3); }, 586: (e3, t3, n3) => { var r2; n3.d(t3, { Z: () => f }); var i2 = new Uint8Array(16); function o() { if (!r2 && !(r2 = typeof crypto != "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != "undefined" && typeof msCrypto.getRandomValues == "function" && msCrypto.getRandomValues.bind(msCrypto))) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); return r2(i2); } const s = /^(?:[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, a = function(e4) { return typeof e4 == "string" && s.test(e4); }; for (var u = [], c = 0; c < 256; ++c) u.push((c + 256).toString(16).substr(1)); const f = function(e4, t4, n4) { var r3 = (e4 = e4 || {}).random || (e4.rng || o)(); if (r3[6] = 15 & r3[6] | 64, r3[8] = 63 & r3[8] | 128, t4) { n4 = n4 || 0; for (var i3 = 0; i3 < 16; ++i3) t4[n4 + i3] = r3[i3]; return t4; } return function(e5) { var t5 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, n5 = (u[e5[t5 + 0]] + u[e5[t5 + 1]] + u[e5[t5 + 2]] + u[e5[t5 + 3]] + "-" + u[e5[t5 + 4]] + u[e5[t5 + 5]] + "-" + u[e5[t5 + 6]] + u[e5[t5 + 7]] + "-" + u[e5[t5 + 8]] + u[e5[t5 + 9]] + "-" + u[e5[t5 + 10]] + u[e5[t5 + 11]] + u[e5[t5 + 12]] + u[e5[t5 + 13]] + u[e5[t5 + 14]] + u[e5[t5 + 15]]).toLowerCase(); if (!a(n5)) throw TypeError("Stringified UUID is invalid"); return n5; }(r3); }; }, 684: (e3, t3) => { function n3(e4, t4, n4) { var r2 = n4[n4.length - 1]; e4 === r2.element && (n4.pop(), r2 = n4[n4.length - 1]); var i2 = r2.element, o = r2.index; Array.isArray(i2) ? i2.push(e4) : o === t4.length - 2 ? i2[t4.pop()] = e4 : t4.push(e4); } t3.stringify = function(e4) { var t4 = []; t4.push({ obj: e4 }); for (var n4, r2, i2, o, s, a, u, c, f, l, d = ""; n4 = t4.pop(); ) if (r2 = n4.obj, d += n4.prefix || "", i2 = n4.val || "") d += i2; else if (typeof r2 != "object") d += r2 === void 0 ? null : JSON.stringify(r2); else if (r2 === null) d += "null"; else if (Array.isArray(r2)) { for (t4.push({ val: "]" }), o = r2.length - 1; o >= 0; o--) s = o === 0 ? "" : ",", t4.push({ obj: r2[o], prefix: s }); t4.push({ val: "[" }); } else { for (u in a = [], r2) r2.hasOwnProperty(u) && a.push(u); for (t4.push({ val: "}" }), o = a.length - 1; o >= 0; o--) f = r2[c = a[o]], l = o > 0 ? "," : "", l += JSON.stringify(c) + ":", t4.push({ obj: f, prefix: l }); t4.push({ val: "{" }); } return d; }, t3.parse = function(e4) { for (var t4, r2, i2, o, s, a, u, c, f, l = [], d = [], h = 0; ; ) if ((t4 = e4[h++]) !== "}" && t4 !== "]" && t4 !== void 0) switch (t4) { case " ": case " ": case "\n": case ":": case ",": break; case "n": h += 3, n3(null, l, d); break; case "t": h += 3, n3(true, l, d); break; case "f": h += 4, n3(false, l, d); break; case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "-": for (r2 = "", h--; ; ) { if (i2 = e4[h++], !/[\d\.\-e\+]/.test(i2)) { h--; break; } r2 += i2; } n3(parseFloat(r2), l, d); break; case '"': for (o = "", s = void 0, a = 0; (u = e4[h++]) !== '"' || s === "\\" && a % 2 == 1; ) o += u, (s = u) === "\\" ? a++ : a = 0; n3(JSON.parse('"' + o + '"'), l, d); break; case "[": c = { element: [], index: l.length }, l.push(c.element), d.push(c); break; case "{": f = { element: {}, index: l.length }, l.push(f.element), d.push(f); break; default: throw new Error("unexpectedly reached end of input: " + t4); } else { if (l.length === 1) return l.pop(); n3(l.pop(), l, d); } }; }, 525: () => { } }; var t2 = {}; function n2(r2) { var i2 = t2[r2]; if (i2 !== void 0) return i2.exports; var o = t2[r2] = { exports: {} }; return e2[r2](o, o.exports, n2), o.exports; } n2.n = (e3) => { var t3 = e3 && e3.__esModule ? () => e3.default : () => e3; return n2.d(t3, { a: t3 }), t3; }, n2.d = (e3, t3) => { for (var r2 in t3) n2.o(t3, r2) && !n2.o(e3, r2) && Object.defineProperty(e3, r2, { enumerable: true, get: t3[r2] }); }, n2.g = function() { if (typeof globalThis == "object") return globalThis; try { return this || new Function("return this")(); } catch (e3) { if (typeof window == "object") return window; } }(), n2.o = (e3, t3) => Object.prototype.hasOwnProperty.call(e3, t3); var r = {}; (() => { n2.d(r, { o: () => o }); const e3 = n2(198).Z, t3 = n2(614).Z, i2 = n2(380), o = e3.plugin(t3).plugin(i2); })(); var i = r.o; // src/lib/src/pouchdb-browser.ts var Pouch = i; // src/utils.ts var import_obsidian = __toModule(require("obsidian")); function path2id(filename) { const x = (0, import_obsidian.normalizePath)(filename); return path2id_base(x); } function id2path(filename) { return id2path_base((0, import_obsidian.normalizePath)(filename)); } var triggers = {}; function setTrigger(key, timeout, proc) { clearTrigger(key); triggers[key] = setTimeout(async () => { delete triggers[key]; await proc(); }, timeout); } function clearTrigger(key) { if (key in triggers) { clearTimeout(triggers[key]); } } function clearAllTriggers() { for (const v in triggers) { clearTimeout(triggers[v]); } } var intervals = {}; function clearAllPeriodic() { for (const v in intervals) { clearInterval(intervals[v]); } } var memos = {}; function memoObject(key, obj) { memos[key] = obj; return memos[key]; } async function memoIfNotExist(key, func) { if (!(key in memos)) { const w = func(); const v = w instanceof Promise ? await w : w; memos[key] = v; } return memos[key]; } function retrieveMemoObject(key) { if (key in memos) { return memos[key]; } else { return false; } } function disposeMemoObject(key) { delete memos[key]; } // src/LocalPouchDB.ts var LocalPouchDB = class extends LocalPouchDBBase { constructor() { super(...arguments); this.last_successful_post = false; } id2path(filename) { return id2path(filename); } path2id(filename) { return path2id(filename); } CreatePouchDBInstance(name, options) { return new Pouch(name, options); } beforeOnUnload() { this.kvDB.close(); } onClose() { this.kvDB.close(); } async onInitializeDatabase() { this.kvDB = await OpenKeyValueDatabase(this.dbname + "-livesync-kv"); } async onResetDatabase() { await this.kvDB.destroy(); } getLastPostFailedBySize() { return !this.last_successful_post; } async fetchByAPI(request) { var _a, _b; const ret = await (0, import_obsidian2.requestUrl)(request); if (ret.status - ret.status % 100 !== 200) { const er = new Error(`Request Error:${ret.status}`); if (ret.json) { er.message = ret.json.reason; er.name = `${(_a = ret.json.error) != null ? _a : ""}:${(_b = ret.json.message) != null ? _b : ""}`; } er.status = ret.status; throw er; } return ret; } async connectRemoteCouchDB(uri, auth, disableRequestURI, passphrase) { if (!isValidRemoteCouchDBURI(uri)) return "Remote URI is not valid"; if (uri.toLowerCase() != uri) return "Remote URI and database name could not contain capital letters."; if (uri.indexOf(" ") !== -1) return "Remote URI and database name could not contain spaces."; let authHeader = ""; if (auth.username && auth.password) { const utf8str = String.fromCharCode.apply(null, new TextEncoder().encode(`${auth.username}:${auth.password}`)); const encoded = window.btoa(utf8str); authHeader = "Basic " + encoded; } else { authHeader = ""; } const conf = { adapter: "http", auth, fetch: async (url, opts) => { var _a, _b; let size = ""; const localURL = url.toString().substring(uri.length); const method = (_a = opts.method) != null ? _a : "GET"; if (opts.body) { const opts_length = opts.body.toString().length; if (opts_length > 1e3 * 1e3 * 10) { if (isCloudantURI(uri)) { this.last_successful_post = false; Logger("This request should fail on IBM Cloudant.", LOG_LEVEL.VERBOSE); throw new Error("This request should fail on IBM Cloudant."); } } size = ` (${opts_length})`; } if (!disableRequestURI && typeof url == "string" && typeof ((_b = opts.body) != null ? _b : "") == "string") { const body = opts.body; const transformedHeaders = { ...opts.headers }; if (authHeader != "") transformedHeaders["authorization"] = authHeader; delete transformedHeaders["host"]; delete transformedHeaders["Host"]; delete transformedHeaders["content-length"]; delete transformedHeaders["Content-Length"]; const requestParam = { url, method: opts.method, body, headers: transformedHeaders, contentType: "application/json" }; try { const r2 = await this.fetchByAPI(requestParam); if (method == "POST" || method == "PUT") { this.last_successful_post = r2.status - r2.status % 100 == 200; } else { this.last_successful_post = true; } Logger(`HTTP:${method}${size} to:${localURL} -> ${r2.status}`, LOG_LEVEL.DEBUG); return new Response(r2.arrayBuffer, { headers: r2.headers, status: r2.status, statusText: `${r2.status}` }); } catch (ex) { Logger(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL.VERBOSE); if (url.toString().indexOf("_bulk_docs") !== -1) { this.last_successful_post = false; } Logger(ex); throw ex; } } try { const response = await fetch(url, opts); if (method == "POST" || method == "PUT") { this.last_successful_post = response.ok; } else { this.last_successful_post = true; } Logger(`HTTP:${method}${size} to:${localURL} -> ${response.status}`, LOG_LEVEL.DEBUG); return response; } catch (ex) { Logger(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL.VERBOSE); if (url.toString().indexOf("_bulk_docs") !== -1) { this.last_successful_post = false; } Logger(ex); throw ex; } } }; const db = new Pouch(uri, conf); if (passphrase && typeof passphrase === "string") { enableEncryption(db, passphrase); } try { const info = await db.info(); return { db, info }; } catch (ex) { let msg = `${ex.name}:${ex.message}`; if (ex.name == "TypeError" && ex.message == "Failed to fetch") { msg += "\n**Note** This error caused by many reasons. The only sure thing is you didn't touch the server.\nTo check details, open inspector."; } Logger(ex, LOG_LEVEL.VERBOSE); return msg; } } }; // src/LogDisplayModal.ts var import_obsidian3 = __toModule(require("obsidian")); var LogDisplayModal = class extends import_obsidian3.Modal { constructor(app2, plugin) { super(app2); this.plugin = plugin; } updateLog() { let msg = ""; for (const v of this.plugin.logMessage) { msg += escapeStringToHTML(v) + "
"; } this.logEl.innerHTML = msg; } onOpen() { const { contentEl } = this; contentEl.empty(); contentEl.createEl("h2", { text: "Sync Status" }); const div = contentEl.createDiv(""); div.addClass("op-scrollable"); div.addClass("op-pre"); this.logEl = div; this.updateLog = this.updateLog.bind(this); this.plugin.addLogHook = this.updateLog; this.updateLog(); } onClose() { const { contentEl } = this; contentEl.empty(); this.plugin.addLogHook = null; } }; // src/ConflictResolveModal.ts var import_obsidian4 = __toModule(require("obsidian")); var import_diff_match_patch = __toModule(require_diff_match_patch()); var ConflictResolveModal = class extends import_obsidian4.Modal { constructor(app2, diff, callback) { super(app2); this.result = diff; this.callback = callback; } onOpen() { const { contentEl } = this; contentEl.empty(); contentEl.createEl("h2", { text: "This document has conflicted changes." }); const div = contentEl.createDiv(""); div.addClass("op-scrollable"); let diff = ""; for (const v of this.result.diff) { const x1 = v[0]; const x2 = v[1]; if (x1 == import_diff_match_patch.DIFF_DELETE) { diff += "" + escapeStringToHTML(x2) + ""; } else if (x1 == import_diff_match_patch.DIFF_EQUAL) { diff += "" + escapeStringToHTML(x2) + ""; } else if (x1 == import_diff_match_patch.DIFF_INSERT) { diff += "" + escapeStringToHTML(x2) + ""; } } diff = diff.replace(/\n/g, "
"); div.innerHTML = diff; const div2 = contentEl.createDiv(""); const date1 = new Date(this.result.left.mtime).toLocaleString() + (this.result.left.deleted ? " (Deleted)" : ""); const date2 = new Date(this.result.right.mtime).toLocaleString() + (this.result.right.deleted ? " (Deleted)" : ""); div2.innerHTML = ` A:${date1}
B:${date2}
`; contentEl.createEl("button", { text: "Keep A" }, (e3) => { e3.addEventListener("click", async () => { await this.callback(this.result.right.rev); this.callback = null; this.close(); }); }); contentEl.createEl("button", { text: "Keep B" }, (e3) => { e3.addEventListener("click", async () => { await this.callback(this.result.left.rev); this.callback = null; this.close(); }); }); contentEl.createEl("button", { text: "Concat both" }, (e3) => { e3.addEventListener("click", async () => { await this.callback(""); this.callback = null; this.close(); }); }); contentEl.createEl("button", { text: "Not now" }, (e3) => { e3.addEventListener("click", () => { this.close(); }); }); } onClose() { const { contentEl } = this; contentEl.empty(); if (this.callback != null) { this.callback(null); } } }; // src/ObsidianLiveSyncSettingTab.ts var import_obsidian5 = __toModule(require("obsidian")); var requestToCouchDB = async (baseUri, username, password, origin2, key, body) => { const utf8str = String.fromCharCode.apply(null, new TextEncoder().encode(`${username}:${password}`)); const encoded = window.btoa(utf8str); const authHeader = "Basic " + encoded; const transformedHeaders = { authorization: authHeader, origin: origin2 }; const uri = `${baseUri}/_node/_local/_config${key ? "/" + key : ""}`; const requestParam = { url: uri, method: body ? "PUT" : "GET", headers: transformedHeaders, contentType: "application/json", body: body ? JSON.stringify(body) : void 0 }; return await (0, import_obsidian5.requestUrl)(requestParam); }; var ObsidianLiveSyncSettingTab = class extends import_obsidian5.PluginSettingTab { constructor(app2, plugin) { super(app2, plugin); this.plugin = plugin; } async testConnection() { const db = await this.plugin.localDatabase.connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.localDatabase.isMobile); if (typeof db === "string") { this.plugin.addLog(`could not connect to ${this.plugin.settings.couchDB_URI} : ${this.plugin.settings.couchDB_DBNAME} (${db})`, LOG_LEVEL.NOTICE); return; } this.plugin.addLog(`Connected to ${db.info.db_name}`, LOG_LEVEL.NOTICE); } display() { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Settings for Self-hosted LiveSync." }); containerEl.addClass("sls-setting"); containerEl.removeClass("isWizard"); const w = containerEl.createDiv(""); const screenElements = {}; const addScreenElement = (key, element2) => { if (!(key in screenElements)) { screenElements[key] = []; } screenElements[key].push(element2); }; w.addClass("sls-setting-menu"); w.innerHTML = ` `; const menuTabs = w.querySelectorAll(".sls-setting-label"); const changeDisplay = (screen) => { for (const k in screenElements) { if (k == screen) { screenElements[k].forEach((element2) => element2.removeClass("setting-collapsed")); } else { screenElements[k].forEach((element2) => element2.addClass("setting-collapsed")); } } w.querySelectorAll(`.sls-setting-label`).forEach((element2) => { element2.removeClass("selected"); element2.querySelector("input[type=radio]").checked = false; }); w.querySelectorAll(`.sls-setting-label.c-${screen}`).forEach((element2) => { element2.addClass("selected"); element2.querySelector("input[type=radio]").checked = true; }); }; menuTabs.forEach((element2) => { const e3 = element2.querySelector(".sls-setting-tab"); if (!e3) return; e3.addEventListener("change", (event) => { menuTabs.forEach((element3) => element3.removeClass("selected")); changeDisplay(event.currentTarget.value); element2.addClass("selected"); }); }); const containerInformationEl = containerEl.createDiv(); const h3El = containerInformationEl.createEl("h3", { text: "Updates" }); const informationDivEl = containerInformationEl.createEl("div", { text: "" }); const manifestVersion = "0.16.6"; const updateInformation = "### 0.16.0\n- Now hidden files need not be scanned. Changes will be detected automatically.\n - If you want it to back to its previous behaviour, please disable `Monitor changes to internal files`.\n - Due to using an internal API, this feature may become unusable with a major update. If this happens, please disable this once.\n\n#### Minors\n\n- 0.16.1 Added missing log updates.\n- 0.16.2 Fixed many problems caused by combinations of `Sync On Save` and the tracking logic that changed at 0.15.6.\n- 0.16.3\n - Fixed detection of IBM Cloudant (And if there are some issues, be fixed automatically).\n - A configuration information reporting tool has been implemented.\n- 0.16.4 Fixed detection failure. Please set the `Chunk size` again when using a self-hosted database.\n- 0.16.5\n - Fixed\n - Conflict detection and merging now be able to treat deleted files.\n - Logs while the boot-up sequence has been tidied up.\n - Fixed incorrect log entries.\n - New Feature\n - The feature of automatically deleting old expired metadata has been implemented.\n We can configure it in `Delete old metadata of deleted files on start-up` in the `General Settings` pane.\n- 0.16.6\n - Fixed\n - Automatic (temporary) batch size adjustment has been restored to work correctly.\n - Chunk splitting has been backed to the previous behaviour for saving them correctly.\n - Improved\n - Corrupted chunks will be detected automatically.\n - Now on the case-insensitive system, `aaa.md` and `AAA.md` will be treated as the same file or path at applying changesets.\n\nNote:\nBefore 0.16.5, LiveSync had some issues making chunks. In this case, synchronisation had became been always failing after a corrupted one should be made. After 0.16.6, the corrupted chunk is automatically detected. Sorry for troubling you but please do `rebuild everything` when this plug-in notified so.\n\n### 0.15.0\n- Outdated configuration items have been removed.\n- Setup wizard has been implemented!\n\nI appreciate for reviewing and giving me advice @Pouhon158!\n\n#### Minors\n- 0.15.1 Missed the stylesheet.\n- 0.15.2 The wizard has been improved and documented!\n- 0.15.3 Fixed the issue about locking/unlocking remote database while rebuilding in the wizard.\n- 0.15.4 Fixed issues about asynchronous processing (e.g., Conflict check or hidden file detection)\n- 0.15.5 Add new features for setting Self-hosted LiveSync up more easier.\n- 0.15.6 File tracking logic has been refined.\n- 0.15.7 Fixed bug about renaming file.\n- 0.15.8 Fixed bug about deleting empty directory, weird behaviour on boot-sequence on mobile devices.\n- 0.15.9 Improved chunk retrieving, now chunks are retrieved in batch on continuous requests.\n- 0.15.10 Fixed:\n - The boot sequence has been corrected and now boots smoothly.\n - Auto applying of batch save will be processed earlier than before.\n\n... To continue on to `updates_old.md`."; const lastVersion = ~~(versionNumberString2Number(manifestVersion) / 1e3); const tmpDiv = createSpan(); tmpDiv.addClass("sls-header-button"); tmpDiv.innerHTML = ``; if (lastVersion > this.plugin.settings.lastReadUpdates) { const informationButtonDiv = h3El.appendChild(tmpDiv); informationButtonDiv.querySelector("button").addEventListener("click", async () => { this.plugin.settings.lastReadUpdates = lastVersion; await this.plugin.saveSettings(); informationButtonDiv.remove(); }); } import_obsidian5.MarkdownRenderer.renderMarkdown(updateInformation, informationDivEl, "/", null); addScreenElement("100", containerInformationEl); 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.syncOnStart) return true; if (this.plugin.localDatabase.syncStatus == "CONNECTED") return true; if (this.plugin.localDatabase.syncStatus == "PAUSED") return true; return false; }; let inWizard = false; const setupWizardEl = containerEl.createDiv(); setupWizardEl.createEl("h3", { text: "Setup wizard" }); new import_obsidian5.Setting(setupWizardEl).setName("Discard the existing configuration and set up").addButton((text2) => { text2.setButtonText("Next").onClick(async () => { if (JSON.stringify(this.plugin.settings) != JSON.stringify(DEFAULT_SETTINGS)) { this.plugin.localDatabase.closeReplication(); this.plugin.settings = { ...DEFAULT_SETTINGS }; this.plugin.saveSettings(); Logger("Configuration has been flushed, please open it again", LOG_LEVEL.NOTICE); this.plugin.app.setting.close(); } else { containerEl.addClass("isWizard"); applyDisplayEnabled(); inWizard = true; changeDisplay("0"); } }); }); new import_obsidian5.Setting(setupWizardEl).setName("Do not discard the existing configuration and set up again").addButton((text2) => { text2.setButtonText("Next").onClick(async () => { this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; this.plugin.localDatabase.closeReplication(); await this.plugin.saveSettings(); containerEl.addClass("isWizard"); applyDisplayEnabled(); inWizard = true; changeDisplay("0"); }); }); const infoWarnForSubsequent = setupWizardEl.createEl("div", { text: `To set up second or subsequent device, please use 'Copy setup URI' and 'Open setup URI'` }); infoWarnForSubsequent.addClass("op-warn-info"); new import_obsidian5.Setting(setupWizardEl).setName("Copy setup URI").addButton((text2) => { text2.setButtonText("Copy setup URI").onClick(() => { this.plugin.app.commands.executeCommandById("obsidian-livesync:livesync-copysetupuri"); }); }).addButton((text2) => { text2.setButtonText("Open setup URI").onClick(() => { this.plugin.app.commands.executeCommandById("obsidian-livesync:livesync-opensetupuri"); }); }); addScreenElement("110", setupWizardEl); const containerRemoteDatabaseEl = containerEl.createDiv(); containerRemoteDatabaseEl.createEl("h3", { text: "Remote Database configuration" }); const syncWarn = containerRemoteDatabaseEl.createEl("div", { text: `These settings are kept locked while any synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.` }); syncWarn.addClass("op-warn-info"); syncWarn.addClass("sls-hidden"); const applyDisplayEnabled = () => { if (isAnySyncEnabled()) { dbSettings.forEach((e3) => { e3.setDisabled(true).setTooltip("Could not change this while any synchronization options are enabled."); }); syncWarn.removeClass("sls-hidden"); } else { dbSettings.forEach((e3) => { e3.setDisabled(false).setTooltip(""); }); syncWarn.addClass("sls-hidden"); } if (this.plugin.settings.liveSync) { syncNonLive.forEach((e3) => { e3.setDisabled(true).setTooltip(""); }); syncLive.forEach((e3) => { e3.setDisabled(false).setTooltip(""); }); } else if (this.plugin.settings.syncOnFileOpen || this.plugin.settings.syncOnSave || this.plugin.settings.syncOnStart || this.plugin.settings.periodicReplication) { syncNonLive.forEach((e3) => { e3.setDisabled(false).setTooltip(""); }); syncLive.forEach((e3) => { e3.setDisabled(true).setTooltip(""); }); } else { syncNonLive.forEach((e3) => { e3.setDisabled(false).setTooltip(""); }); syncLive.forEach((e3) => { e3.setDisabled(false).setTooltip(""); }); } }; const dbSettings = []; dbSettings.push(new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("URI").addText((text2) => text2.setPlaceholder("https://........").setValue(this.plugin.settings.couchDB_URI).onChange(async (value) => { this.plugin.settings.couchDB_URI = value; await this.plugin.saveSettings(); })), new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Username").setDesc("username").addText((text2) => text2.setPlaceholder("").setValue(this.plugin.settings.couchDB_USER).onChange(async (value) => { this.plugin.settings.couchDB_USER = value; await this.plugin.saveSettings(); })), new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Password").setDesc("password").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.couchDB_PASSWORD).onChange(async (value) => { this.plugin.settings.couchDB_PASSWORD = value; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "password"); }), new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Database name").addText((text2) => text2.setPlaceholder("").setValue(this.plugin.settings.couchDB_DBNAME).onChange(async (value) => { this.plugin.settings.couchDB_DBNAME = value; await this.plugin.saveSettings(); }))); new import_obsidian5.Setting(containerRemoteDatabaseEl).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((toggle) => toggle.setValue(this.plugin.settings.workingEncrypt).onChange(async (value) => { if (inWizard) { this.plugin.settings.encrypt = value; passphrase.setDisabled(!value); await this.plugin.saveSettings(); } else { this.plugin.settings.workingEncrypt = value; passphrase.setDisabled(!value); await this.plugin.saveSettings(); } })); const passphrase = new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Passphrase").setDesc("Encrypting passphrase. If you change the passphrase of a existing database, overwriting the remote database is strongly recommended.").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.workingPassphrase).onChange(async (value) => { if (inWizard) { this.plugin.settings.passphrase = value; await this.plugin.saveSettings(); } else { this.plugin.settings.workingPassphrase = value; await this.plugin.saveSettings(); } }); text2.inputEl.setAttribute("type", "password"); }); passphrase.setDisabled(!this.plugin.settings.workingEncrypt); const checkWorkingPassphrase = async () => { const settingForCheck = { ...this.plugin.settings, encrypt: this.plugin.settings.workingEncrypt, passphrase: this.plugin.settings.workingPassphrase }; console.dir(settingForCheck); const db = await this.plugin.localDatabase.connectRemoteCouchDBWithSetting(settingForCheck, this.plugin.localDatabase.isMobile); if (typeof db === "string") { Logger("Could not connect to the database.", LOG_LEVEL.NOTICE); return false; } else { if (await checkSyncInfo(db.db)) { return true; } else { Logger("Failed to read remote database", LOG_LEVEL.NOTICE); return false; } } }; const applyEncryption = async (sendToServer) => { if (this.plugin.settings.workingEncrypt && this.plugin.settings.workingPassphrase == "") { Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL.NOTICE); return; } if (this.plugin.settings.workingEncrypt && !await testCrypt()) { Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.NOTICE); return; } if (!await checkWorkingPassphrase()) { return; } if (!this.plugin.settings.workingEncrypt) { this.plugin.settings.workingPassphrase = ""; } this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; this.plugin.settings.encrypt = this.plugin.settings.workingEncrypt; this.plugin.settings.passphrase = this.plugin.settings.workingPassphrase; await this.plugin.saveSettings(); if (sendToServer) { await this.plugin.initializeDatabase(true); await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.replicateAllToServer(true); } else { await this.plugin.markRemoteResolved(); await this.plugin.replicate(true); } }; new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Apply").setDesc("Apply encryption settings").setClass("wizardHidden").addButton((button) => button.setButtonText("Apply").setWarning().setDisabled(false).setClass("sls-btn-right").onClick(async () => { await applyEncryption(true); })).addButton((button) => button.setButtonText("Apply w/o rebuilding").setWarning().setDisabled(false).setClass("sls-btn-right").onClick(async () => { await applyEncryption(false); })); const rebuildDB = async (method) => { this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; await this.plugin.saveSettings(); applyDisplayEnabled(); await delay(2e3); if (method == "localOnly") { await this.plugin.resetLocalDatabase(); await this.plugin.markRemoteResolved(); await this.plugin.replicate(true); } if (method == "remoteOnly") { await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.replicateAllToServer(true); } if (method == "rebuildBothByThisDevice") { await this.plugin.resetLocalDatabase(); await this.plugin.initializeDatabase(true); await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.replicateAllToServer(true); } }; new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Overwrite remote database").setDesc("Overwrite remote database with local DB and passphrase.").setClass("wizardHidden").addButton((button) => button.setButtonText("Send").setWarning().setDisabled(false).setClass("sls-btn-left").onClick(async () => { await rebuildDB("remoteOnly"); })); new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").setClass("wizardHidden").addButton((button) => button.setButtonText("Rebuild").setWarning().setDisabled(false).setClass("sls-btn-left").onClick(async () => { await rebuildDB("rebuildBothByThisDevice"); })); new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Test Database Connection").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((button) => button.setButtonText("Test").setDisabled(false).onClick(async () => { await this.testConnection(); })); new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Check database configuration").addButton((button) => button.setButtonText("Check").setDisabled(false).onClick(async () => { const checkConfig = async () => { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; try { if (isCloudantURI(this.plugin.settings.couchDB_URI)) { Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL.NOTICE); return; } const r2 = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin); Logger(JSON.stringify(r2.json, null, 2)); const responseConfig = r2.json; const emptyDiv = createDiv(); emptyDiv.innerHTML = ""; checkResultDiv.replaceChildren(...[emptyDiv]); const addResult = (msg, classes) => { const tmpDiv2 = createDiv(); tmpDiv2.addClass("ob-btn-config-fix"); if (classes) { tmpDiv2.addClasses(classes); } tmpDiv2.innerHTML = `${msg}`; checkResultDiv.appendChild(tmpDiv2); }; const addConfigFixButton = (title, key, value) => { const tmpDiv2 = createDiv(); tmpDiv2.addClass("ob-btn-config-fix"); tmpDiv2.innerHTML = ``; const x = checkResultDiv.appendChild(tmpDiv2); x.querySelector("button").addEventListener("click", async () => { console.dir({ key, value }); const res = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, void 0, key, value); console.dir(res); if (res.status == 200) { Logger(`${title} successfully updated`, LOG_LEVEL.NOTICE); checkResultDiv.removeChild(x); checkConfig(); } else { Logger(`${title} failed`, LOG_LEVEL.NOTICE); Logger(res.text); } }); }; addResult("---Notice---", ["ob-btn-config-head"]); addResult("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"]); addResult("Your configuration is dumped to Log", ["ob-btn-config-info"]); addResult("--Config check--", ["ob-btn-config-head"]); if (!(this.plugin.settings.couchDB_USER in responseConfig.admins)) { addResult(`\u26A0 You do not have administrative privileges.`); } else { addResult("\u2714 You have administrative privileges."); } if (((_a = responseConfig == null ? void 0 : responseConfig.chttpd) == null ? void 0 : _a.require_valid_user) != "true") { addResult("\u2757 chttpd.require_valid_user looks like wrong."); addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true"); } else { addResult("\u2714 chttpd.require_valid_user is ok."); } if (((_b = responseConfig == null ? void 0 : responseConfig.chttpd_auth) == null ? void 0 : _b.require_valid_user) != "true") { addResult("\u2757 chttpd_auth.require_valid_user looks like wrong."); addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true"); } else { addResult("\u2714 chttpd_auth.require_valid_user is ok."); } if (!(responseConfig == null ? void 0 : responseConfig.httpd["WWW-Authenticate"])) { addResult("\u2757 httpd.WWW-Authenticate is missing"); addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"'); } else { addResult("\u2714 httpd.WWW-Authenticate is ok."); } if (((_c = responseConfig == null ? void 0 : responseConfig.httpd) == null ? void 0 : _c.enable_cors) != "true") { addResult("\u2757 httpd.enable_cors is wrong"); addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true"); } else { addResult("\u2714 httpd.enable_cors is ok."); } if (!isCloudantURI(this.plugin.settings.couchDB_URI)) { if (Number((_e = (_d = responseConfig == null ? void 0 : responseConfig.chttpd) == null ? void 0 : _d.max_http_request_size) != null ? _e : 0) < 4294967296) { addResult("\u2757 chttpd.max_http_request_size is low)"); addConfigFixButton("Set chttpd.max_http_request_size", "chttpd/max_http_request_size", "4294967296"); } else { addResult("\u2714 chttpd.max_http_request_size is ok."); } if (Number((_g = (_f = responseConfig == null ? void 0 : responseConfig.couchdb) == null ? void 0 : _f.max_document_size) != null ? _g : 0) < 5e7) { addResult("\u2757 couchdb.max_document_size is low)"); addConfigFixButton("Set couchdb.max_document_size", "couchdb/max_document_size", "50000000"); } else { addResult("\u2714 couchdb.max_document_size is ok."); } } if (((_h = responseConfig == null ? void 0 : responseConfig.cors) == null ? void 0 : _h.credentials) != "true") { addResult("\u2757 cors.credentials is wrong"); addConfigFixButton("Set cors.credentials", "cors/credentials", "true"); } else { addResult("\u2714 cors.credentials is ok."); } const ConfiguredOrigins = (((_j = (_i = responseConfig == null ? void 0 : responseConfig.cors) == null ? void 0 : _i.origins) != null ? _j : "") + "").split(","); if (((_k = responseConfig == null ? void 0 : responseConfig.cors) == null ? void 0 : _k.origins) == "*" || ConfiguredOrigins.indexOf("app://obsidian.md") !== -1 && ConfiguredOrigins.indexOf("capacitor://localhost") !== -1 && ConfiguredOrigins.indexOf("http://localhost") !== -1) { addResult("\u2714 cors.origins is ok."); } else { addResult("\u2757 cors.origins is wrong"); addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost"); } addResult("--Connection check--", ["ob-btn-config-head"]); addResult(`Current origin:${window.location.origin}`); const origins = ["app://obsidian.md", "capacitor://localhost", "http://localhost"]; for (const org of origins) { const rr = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, org); const responseHeaders = Object.entries(rr.headers).map((e3) => { e3[0] = (e3[0] + "").toLowerCase(); return e3; }).reduce((obj, [key, val]) => { obj[key] = val; return obj; }, {}); addResult(`Origin check:${org}`); if (responseHeaders["access-control-allow-credentials"] != "true") { addResult("\u2757 CORS is not allowing credential"); } else { addResult("\u2714 CORS credential OK"); } if (responseHeaders["access-control-allow-origin"] != org) { addResult(`\u2757 CORS Origin is unmatched:${origin}->${responseHeaders["access-control-allow-origin"]}`); } else { addResult("\u2714 CORS origin OK"); } } addResult("--Done--", ["ob-btn-config-head"]); addResult("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"]); } catch (ex) { Logger(`Checking configuration failed`, LOG_LEVEL.NOTICE); Logger(ex); } }; await checkConfig(); })); const checkResultDiv = containerRemoteDatabaseEl.createEl("div", { text: "" }); new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("Lock remote database").setDesc("Lock remote database to prevent synchronization with other devices.").setClass("wizardHidden").addButton((button) => button.setButtonText("Lock").setDisabled(false).setWarning().onClick(async () => { await this.plugin.markRemoteLocked(); })); let rebuildRemote = false; new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("").setClass("wizardOnly").addButton((button) => button.setButtonText("Next").setClass("mod-cta").setDisabled(false).onClick(async () => { if (!this.plugin.settings.encrypt) { this.plugin.settings.passphrase = ""; } if (isCloudantURI(this.plugin.settings.couchDB_URI)) { this.plugin.settings.customChunkSize = 0; } else { this.plugin.settings.customChunkSize = 100; } rebuildRemote = false; changeDisplay("10"); })); new import_obsidian5.Setting(containerRemoteDatabaseEl).setName("").setClass("wizardOnly").addButton((button) => button.setButtonText("Discard exist database and proceed").setDisabled(false).setWarning().onClick(async () => { if (!this.plugin.settings.encrypt) { this.plugin.settings.passphrase = ""; } if (isCloudantURI(this.plugin.settings.couchDB_URI)) { this.plugin.settings.customChunkSize = 0; } else { this.plugin.settings.customChunkSize = 100; } rebuildRemote = true; changeDisplay("10"); })); addScreenElement("0", containerRemoteDatabaseEl); const containerLocalDatabaseEl = containerEl.createDiv(); containerLocalDatabaseEl.createEl("h3", { text: "Local Database configuration" }); new import_obsidian5.Setting(containerLocalDatabaseEl).setName("Batch database update").setDesc("Delay all changes, save once before replication or opening another file.").setClass("wizardHidden").addToggle((toggle) => toggle.setValue(this.plugin.settings.batchSave).onChange(async (value) => { if (value && this.plugin.settings.liveSync) { Logger("LiveSync and Batch database update cannot be used at the same time.", LOG_LEVEL.NOTICE); toggle.setValue(false); return; } this.plugin.settings.batchSave = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerLocalDatabaseEl).setName("Fetch rebuilt DB").setDesc("Restore or reconstruct local database from remote database.").setClass("wizardHidden").addButton((button) => button.setButtonText("Fetch").setWarning().setDisabled(false).setClass("sls-btn-left").onClick(async () => { await rebuildDB("localOnly"); })); let newDatabaseName = this.plugin.settings.additionalSuffixOfDatabaseName + ""; new import_obsidian5.Setting(containerLocalDatabaseEl).setName("Database suffix").setDesc("Optional: Set unique name for using same vault name on different directory.").addText((text2) => { text2.setPlaceholder("").setValue(newDatabaseName).onChange((value) => { newDatabaseName = value; }); }).addButton((button) => { button.setButtonText("Change").onClick(async () => { if (this.plugin.settings.additionalSuffixOfDatabaseName == newDatabaseName) { Logger("Suffix was not changed.", LOG_LEVEL.NOTICE); return; } this.plugin.settings.additionalSuffixOfDatabaseName = newDatabaseName; await this.plugin.saveSettings(); Logger("Suffix has been changed. Reopening database...", LOG_LEVEL.NOTICE); await this.plugin.initializeDatabase(); }); }); new import_obsidian5.Setting(containerLocalDatabaseEl).setName("").setClass("wizardOnly").addButton((button) => button.setButtonText("Next").setDisabled(false).onClick(async () => { changeDisplay("40"); })); addScreenElement("10", containerLocalDatabaseEl); const containerGeneralSettingsEl = containerEl.createDiv(); containerGeneralSettingsEl.createEl("h3", { text: "General Settings" }); new import_obsidian5.Setting(containerGeneralSettingsEl).setName("Do not show low-priority Log").setDesc("Reduce log information").addToggle((toggle) => toggle.setValue(this.plugin.settings.lessInformationInLog).onChange(async (value) => { this.plugin.settings.lessInformationInLog = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerGeneralSettingsEl).setName("Verbose Log").setDesc("Show verbose log").addToggle((toggle) => toggle.setValue(this.plugin.settings.showVerboseLog).onChange(async (value) => { this.plugin.settings.showVerboseLog = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerGeneralSettingsEl).setName("Delete metadata of deleted files.").setClass("wizardHidden").addToggle((toggle) => { toggle.setValue(this.plugin.settings.deleteMetadataOfDeletedFiles).onChange(async (value) => { this.plugin.settings.deleteMetadataOfDeletedFiles = value; await this.plugin.saveSettings(); }); }); new import_obsidian5.Setting(containerGeneralSettingsEl).setName("Delete old metadata of deleted files on start-up").setClass("wizardHidden").setDesc("(Days passed, 0 to disable automatic-deletion)").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles + "").onChange(async (value) => { let v = Number(value); if (isNaN(v)) { v = 0; } this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles = v; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "number"); }); addScreenElement("20", containerGeneralSettingsEl); const containerSyncSettingEl = containerEl.createDiv(); containerSyncSettingEl.createEl("h3", { text: "Sync Settings" }); containerSyncSettingEl.addClass("wizardHidden"); if (this.plugin.settings.versionUpFlash != "") { const c = containerSyncSettingEl.createEl("div", { text: this.plugin.settings.versionUpFlash }); c.createEl("button", { text: "I got it and updated." }, (e3) => { e3.addClass("mod-cta"); e3.addEventListener("click", async () => { this.plugin.settings.versionUpFlash = ""; await this.plugin.saveSettings(); applyDisplayEnabled(); c.remove(); }); }); c.addClass("op-warn"); } const syncLive = []; const syncNonLive = []; syncLive.push(new import_obsidian5.Setting(containerSyncSettingEl).setName("LiveSync").setDesc("Sync realtime").addToggle((toggle) => toggle.setValue(this.plugin.settings.liveSync).onChange(async (value) => { if (value && this.plugin.settings.batchSave) { Logger("LiveSync and Batch database update cannot be used at the same time.", LOG_LEVEL.NOTICE); toggle.setValue(false); return; } this.plugin.settings.liveSync = value; await this.plugin.saveSettings(); applyDisplayEnabled(); await this.plugin.realizeSettingSyncMode(); }))); syncNonLive.push(new import_obsidian5.Setting(containerSyncSettingEl).setName("Periodic Sync").setDesc("Sync periodically").addToggle((toggle) => toggle.setValue(this.plugin.settings.periodicReplication).onChange(async (value) => { this.plugin.settings.periodicReplication = value; await this.plugin.saveSettings(); applyDisplayEnabled(); })), new import_obsidian5.Setting(containerSyncSettingEl).setName("Periodic Sync interval").setDesc("Interval (sec)").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.periodicReplicationInterval + "").onChange(async (value) => { let v = Number(value); if (isNaN(v) || v > 5e3) { v = 0; } this.plugin.settings.periodicReplicationInterval = v; await this.plugin.saveSettings(); applyDisplayEnabled(); }); text2.inputEl.setAttribute("type", "number"); }), new import_obsidian5.Setting(containerSyncSettingEl).setName("Sync on Save").setDesc("When you save file, sync automatically").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnSave).onChange(async (value) => { this.plugin.settings.syncOnSave = value; await this.plugin.saveSettings(); applyDisplayEnabled(); })), new import_obsidian5.Setting(containerSyncSettingEl).setName("Sync on File Open").setDesc("When you open file, sync automatically").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnFileOpen).onChange(async (value) => { this.plugin.settings.syncOnFileOpen = value; await this.plugin.saveSettings(); applyDisplayEnabled(); })), new import_obsidian5.Setting(containerSyncSettingEl).setName("Sync on Start").setDesc("Start synchronization after launching Obsidian.").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnStart).onChange(async (value) => { this.plugin.settings.syncOnStart = value; await this.plugin.saveSettings(); applyDisplayEnabled(); }))); new import_obsidian5.Setting(containerSyncSettingEl).setName("Use Trash for deleted files").setDesc("Do not delete files that are deleted in remote, just move to trash.").addToggle((toggle) => toggle.setValue(this.plugin.settings.trashInsteadDelete).onChange(async (value) => { this.plugin.settings.trashInsteadDelete = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Do not delete empty folder").setDesc("Normally, a folder is deleted when it becomes empty after a replication. Enabling this will prevent it from getting deleted").addToggle((toggle) => toggle.setValue(this.plugin.settings.doNotDeleteFolder).onChange(async (value) => { this.plugin.settings.doNotDeleteFolder = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Use newer file if conflicted (beta)").setDesc("Resolve conflicts by newer files automatically.").addToggle((toggle) => toggle.setValue(this.plugin.settings.resolveConflictsByNewerFile).onChange(async (value) => { this.plugin.settings.resolveConflictsByNewerFile = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Check conflict only on opened files").setDesc("Do not check conflict for replication").addToggle((toggle) => toggle.setValue(this.plugin.settings.checkConflictOnlyOnOpen).onChange(async (value) => { this.plugin.settings.checkConflictOnlyOnOpen = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Sync hidden files").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncInternalFiles).onChange(async (value) => { this.plugin.settings.syncInternalFiles = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Monitor changes to internal files").addToggle((toggle) => toggle.setValue(this.plugin.settings.watchInternalFileChanges).onChange(async (value) => { this.plugin.settings.watchInternalFileChanges = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Scan for hidden files before replication").setDesc("This configuration will be ignored if monitoring changes is enabled.").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncInternalFilesBeforeReplication).onChange(async (value) => { this.plugin.settings.syncInternalFilesBeforeReplication = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerSyncSettingEl).setName("Scan hidden files periodically").setDesc("Seconds, 0 to disable. This configuration will be ignored if monitoring changes is enabled.").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.syncInternalFilesInterval + "").onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10) { v = 10; } this.plugin.settings.syncInternalFilesInterval = v; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "number"); }); let skipPatternTextArea = null; const defaultSkipPattern = "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/"; const defaultSkipPatternXPlat = defaultSkipPattern + ",\\/workspace$ ,\\/workspace.json$"; new import_obsidian5.Setting(containerSyncSettingEl).setName("Skip patterns").setDesc("Regular expression, If you use hidden file sync between desktop and mobile, adding `workspace$` is recommended.").addTextArea((text2) => { text2.setValue(this.plugin.settings.syncInternalFilesIgnorePatterns).setPlaceholder("\\/node_modules\\/, \\/\\.git\\/").onChange(async (value) => { this.plugin.settings.syncInternalFilesIgnorePatterns = value; await this.plugin.saveSettings(); }); skipPatternTextArea = text2; return text2; }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Restore the skip pattern to default").addButton((button) => { button.setButtonText("Default").onClick(async () => { skipPatternTextArea.setValue(defaultSkipPattern); this.plugin.settings.syncInternalFilesIgnorePatterns = defaultSkipPattern; await this.plugin.saveSettings(); }); }).addButton((button) => { button.setButtonText("Cross-platform").onClick(async () => { skipPatternTextArea.setValue(defaultSkipPatternXPlat); this.plugin.settings.syncInternalFilesIgnorePatterns = defaultSkipPatternXPlat; await this.plugin.saveSettings(); }); }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Touch hidden files").setDesc("Update the modified time of all hidden files to the current time.").addButton((button) => button.setButtonText("Touch").setWarning().setDisabled(false).setClass("sls-btn-left").onClick(async () => { const filesAll = await this.plugin.scanInternalFiles(); const targetFiles = await this.plugin.filterTargetFiles(filesAll); const now = Date.now(); const newFiles = targetFiles.map((e3) => ({ ...e3, mtime: now })); let i2 = 0; const maxFiles = newFiles.length; for (const file of newFiles) { i2++; Logger(`Touched:${file.path} (${i2}/${maxFiles})`, LOG_LEVEL.NOTICE, "touch-files"); await this.plugin.applyMTimeToFile(file); } })); containerSyncSettingEl.createEl("h3", { text: (0, import_obsidian5.sanitizeHTMLToDom)(`Experimental`) }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Regular expression to ignore files").setDesc("If this is set, any changes to local and remote files that match this will be skipped.").addTextArea((text2) => { text2.setValue(this.plugin.settings.syncIgnoreRegEx).setPlaceholder("\\.pdf$").onChange(async (value) => { let isValidRegExp = false; try { new RegExp(value); isValidRegExp = true; } catch (_) { } if (isValidRegExp || value.trim() == "") { this.plugin.settings.syncIgnoreRegEx = value; await this.plugin.saveSettings(); } }); return text2; }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Regular expression for restricting synchronization targets").setDesc("If this is set, changes to local and remote files that only match this will be processed.").addTextArea((text2) => { text2.setValue(this.plugin.settings.syncOnlyRegEx).setPlaceholder("\\.md$|\\.txt").onChange(async (value) => { let isValidRegExp = false; try { new RegExp(value); isValidRegExp = true; } catch (_) { } if (isValidRegExp || value.trim() == "") { this.plugin.settings.syncOnlyRegEx = value; await this.plugin.saveSettings(); } }); return text2; }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Chunk size").setDesc("Customize chunk size for binary files (0.1MBytes). This cannot be increased when using IBM Cloudant.").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.customChunkSize + "").onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 100) { v = 100; } this.plugin.settings.customChunkSize = v; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "number"); }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Read chunks online.").setDesc("If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.").addToggle((toggle) => { toggle.setValue(this.plugin.settings.readChunksOnline).onChange(async (value) => { this.plugin.settings.readChunksOnline = value; await this.plugin.saveSettings(); }); return toggle; }); containerSyncSettingEl.createEl("h3", { text: (0, import_obsidian5.sanitizeHTMLToDom)(`Advanced settings`) }); containerSyncSettingEl.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.` }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Batch size").setDesc("Number of change feed items to process at a time. Defaults to 250.").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.batch_size + "").onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10) { v = 10; } this.plugin.settings.batch_size = v; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "number"); }); new import_obsidian5.Setting(containerSyncSettingEl).setName("Batch limit").setDesc("Number of batches to process at a time. Defaults to 40. This along with batch size controls how many docs are kept in memory at a time.").addText((text2) => { text2.setPlaceholder("").setValue(this.plugin.settings.batches_limit + "").onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10) { v = 10; } this.plugin.settings.batches_limit = v; await this.plugin.saveSettings(); }); text2.inputEl.setAttribute("type", "number"); }); addScreenElement("30", containerSyncSettingEl); const containerMiscellaneousEl = containerEl.createDiv(); containerMiscellaneousEl.createEl("h3", { text: "Miscellaneous" }); new import_obsidian5.Setting(containerMiscellaneousEl).setName("Show status inside editor").setDesc("").addToggle((toggle) => toggle.setValue(this.plugin.settings.showStatusOnEditor).onChange(async (value) => { this.plugin.settings.showStatusOnEditor = value; await this.plugin.saveSettings(); })); let currentPreset = "NONE"; new import_obsidian5.Setting(containerMiscellaneousEl).setName("Presets").setDesc("Apply preset configuration").addDropdown((dropdown) => dropdown.addOptions({ NONE: "", LIVESYNC: "LiveSync", PERIODIC: "Periodic w/ batch", DISABLE: "Disable all sync" }).setValue(currentPreset).onChange((value) => currentPreset = value)).addButton((button) => button.setButtonText("Apply").setDisabled(false).setCta().onClick(async () => { if (currentPreset == "") { Logger("Select any preset.", LOG_LEVEL.NOTICE); return; } this.plugin.settings.batchSave = false; this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; if (currentPreset == "LIVESYNC") { this.plugin.settings.liveSync = true; Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL.NOTICE); } else if (currentPreset == "PERIODIC") { this.plugin.settings.batchSave = true; this.plugin.settings.periodicReplication = true; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = true; this.plugin.settings.syncOnFileOpen = true; Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL.NOTICE); } else { Logger("All synchronization disabled.", LOG_LEVEL.NOTICE); } this.plugin.saveSettings(); await this.plugin.realizeSettingSyncMode(); if (inWizard) { this.plugin.app.setting.close(); await this.plugin.resetLocalDatabase(); await this.plugin.initializeDatabase(true); if (rebuildRemote) { await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.markRemoteResolved(); } await this.plugin.replicate(true); Logger("All done! Please set up subsequent devices with 'Copy setup URI' and 'Open setup URI'.", LOG_LEVEL.NOTICE); this.plugin.app.commands.executeCommandById("obsidian-livesync:livesync-copysetupuri"); } })); const infoApply = containerMiscellaneousEl.createEl("div", { text: `To finish setup, please select one of the presets` }); infoApply.addClass("op-warn-info"); infoApply.addClass("wizardOnly"); addScreenElement("40", containerMiscellaneousEl); const containerHatchEl = containerEl.createDiv(); containerHatchEl.createEl("h3", { text: "Hatch" }); new import_obsidian5.Setting(containerHatchEl).setName("Make report to inform the issue").setDesc("Verify and repair all files and update database without restoring").addButton((button) => button.setButtonText("Make report").setDisabled(false).onClick(async () => { let responseConfig = {}; const REDACTED = "\u{1D445}\u{1D438}\u{1D437}\u{1D434}\u{1D436}\u{1D447}\u{1D438}\u{1D437}"; try { const r2 = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin); Logger(JSON.stringify(r2.json, null, 2)); responseConfig = r2.json; responseConfig["couch_httpd_auth"].secret = REDACTED; responseConfig["couch_httpd_auth"].authentication_db = REDACTED; responseConfig["couch_httpd_auth"].authentication_redirect = REDACTED; responseConfig["couchdb"].uuid = REDACTED; responseConfig["admins"] = REDACTED; } catch (ex) { responseConfig = "Requesting information to the remote CouchDB has been failed. If you are using IBM Cloudant, it is the normal behaviour."; } const pluginConfig = JSON.parse(JSON.stringify(this.plugin.settings)); pluginConfig.couchDB_DBNAME = REDACTED; pluginConfig.couchDB_PASSWORD = REDACTED; pluginConfig.couchDB_URI = isCloudantURI(pluginConfig.couchDB_URI) ? "cloudant" : "self-hosted"; pluginConfig.couchDB_USER = REDACTED; pluginConfig.passphrase = REDACTED; pluginConfig.workingPassphrase = REDACTED; const msgConfig = `----remote config---- ${(0, import_obsidian5.stringifyYaml)(responseConfig)} ---- Plug-in config --- ${(0, import_obsidian5.stringifyYaml)(pluginConfig)}`; console.log(msgConfig); await navigator.clipboard.writeText(msgConfig); Logger(`Information has been copied to clipboard`, LOG_LEVEL.NOTICE); })); if (this.plugin.localDatabase.remoteLockedAndDeviceNotAccepted) { const c = containerHatchEl.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'. " }); c.createEl("button", { text: "I'm ready, mark this device 'resolved'" }, (e3) => { e3.addClass("mod-warning"); e3.addEventListener("click", async () => { await this.plugin.markRemoteResolved(); c.remove(); }); }); c.addClass("op-warn"); } else { if (this.plugin.localDatabase.remoteLocked) { const c = containerHatchEl.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." }); c.createEl("button", { text: "I'm ready, unlock the database" }, (e3) => { e3.addClass("mod-warning"); e3.addEventListener("click", async () => { await this.plugin.markRemoteUnlocked(); c.remove(); }); }); c.addClass("op-warn"); } } const hatchWarn = containerHatchEl.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).` }); hatchWarn.addClass("op-warn-info"); new import_obsidian5.Setting(containerHatchEl).setName("Verify and repair all files").setDesc("Verify and repair all files and update database without restoring").addButton((button) => button.setButtonText("Verify and repair").setDisabled(false).setWarning().onClick(async () => { const files = this.app.vault.getFiles(); Logger("Verify and repair all files started", LOG_LEVEL.NOTICE, "verify"); let i2 = 0; for (const file of files) { i2++; Logger(`Update into ${file.path}`); Logger(`${i2}/${files.length} ${file.path}`, LOG_LEVEL.NOTICE, "verify"); try { await this.plugin.updateIntoDB(file); } catch (ex) { Logger("could not update:"); Logger(ex); } } Logger("done", LOG_LEVEL.NOTICE, "verify"); })); new import_obsidian5.Setting(containerHatchEl).setName("Suspend file watching").setDesc("Stop watching for file change.").addToggle((toggle) => toggle.setValue(this.plugin.settings.suspendFileWatching).onChange(async (value) => { this.plugin.settings.suspendFileWatching = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerHatchEl).setName("Discard local database to reset or uninstall Self-hosted LiveSync").addButton((button) => button.setButtonText("Discard").setWarning().setDisabled(false).onClick(async () => { await this.plugin.resetLocalDatabase(); await this.plugin.initializeDatabase(); })); addScreenElement("50", containerHatchEl); const containerPluginSettings = containerEl.createDiv(); containerPluginSettings.createEl("h3", { text: "Plugins and settings (beta)" }); const updateDisabledOfDeviceAndVaultName = () => { vaultName.setDisabled(this.plugin.settings.autoSweepPlugins || this.plugin.settings.autoSweepPluginsPeriodic); vaultName.setTooltip(this.plugin.settings.autoSweepPlugins || this.plugin.settings.autoSweepPluginsPeriodic ? "You could not change when you enabling auto scan." : ""); }; new import_obsidian5.Setting(containerPluginSettings).setName("Enable plugin synchronization").addToggle((toggle) => toggle.setValue(this.plugin.settings.usePluginSync).onChange(async (value) => { this.plugin.settings.usePluginSync = value; await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerPluginSettings).setName("Scan plugins automatically").setDesc("Scan plugins before replicating.").addToggle((toggle) => toggle.setValue(this.plugin.settings.autoSweepPlugins).onChange(async (value) => { this.plugin.settings.autoSweepPlugins = value; updateDisabledOfDeviceAndVaultName(); await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerPluginSettings).setName("Scan plugins periodically").setDesc("Scan plugins every 1 minute.").addToggle((toggle) => toggle.setValue(this.plugin.settings.autoSweepPluginsPeriodic).onChange(async (value) => { this.plugin.settings.autoSweepPluginsPeriodic = value; updateDisabledOfDeviceAndVaultName(); await this.plugin.saveSettings(); })); new import_obsidian5.Setting(containerPluginSettings).setName("Notify updates").setDesc("Notify when any device has a newer plugin or its setting.").addToggle((toggle) => toggle.setValue(this.plugin.settings.notifyPluginOrSettingUpdated).onChange(async (value) => { this.plugin.settings.notifyPluginOrSettingUpdated = value; await this.plugin.saveSettings(); })); const vaultName = new import_obsidian5.Setting(containerPluginSettings).setName("Device and Vault name").setDesc("").addText((text2) => { text2.setPlaceholder("desktop-main").setValue(this.plugin.deviceAndVaultName).onChange(async (value) => { this.plugin.deviceAndVaultName = value; await this.plugin.saveSettings(); }); }); new import_obsidian5.Setting(containerPluginSettings).setName("Open").setDesc("Open the plugin dialog").addButton((button) => { button.setButtonText("Open").setDisabled(false).onClick(() => { this.plugin.showPluginSyncModal(); }); }); updateDisabledOfDeviceAndVaultName(); addScreenElement("60", containerPluginSettings); const containerCorruptedDataEl = containerEl.createDiv(); containerCorruptedDataEl.createEl("h3", { text: "Corrupted or missing data" }); containerCorruptedDataEl.createEl("h4", { text: "Corrupted" }); if (Object.keys(this.plugin.localDatabase.corruptedEntries).length > 0) { const cx = containerCorruptedDataEl.createEl("div", { text: "If you have a copy of these files on any device, simply edit them once and sync. If not, there's nothing we can do except deleting them. sorry.." }); for (const k in this.plugin.localDatabase.corruptedEntries) { const xx = cx.createEl("div", { text: `${k}` }); const ba = xx.createEl("button", { text: `Delete this` }, (e3) => { e3.addEventListener("click", async () => { await this.plugin.localDatabase.deleteDBEntry(k); xx.remove(); }); }); ba.addClass("mod-warning"); xx.createEl("button", { text: `Restore from file` }, (e3) => { e3.addEventListener("click", async () => { const f = await this.app.vault.getFiles().filter((e4) => path2id(e4.path) == k); if (f.length == 0) { Logger("Not found in vault", LOG_LEVEL.NOTICE); return; } await this.plugin.updateIntoDB(f[0]); xx.remove(); }); }); xx.addClass("mod-warning"); } } else { containerCorruptedDataEl.createEl("div", { text: "There is no corrupted data." }); } containerCorruptedDataEl.createEl("h4", { text: "Missing or waiting" }); if (Object.keys(this.plugin.queuedFiles).length > 0) { const cx = containerCorruptedDataEl.createEl("div", { text: "These files have missing or waiting chunks. Perhaps these chunks will arrive in a while after replication. But if they don't, you have to restore it's database entry from a existing local file by hitting the button below." }); const files = [...new Set([...this.plugin.queuedFiles.map((e3) => e3.entry._id)])]; for (const k of files) { const xx = cx.createEl("div", { text: `${id2path(k)}` }); const ba = xx.createEl("button", { text: `Delete this` }, (e3) => { e3.addEventListener("click", async () => { await this.plugin.localDatabase.deleteDBEntry(k); xx.remove(); }); }); ba.addClass("mod-warning"); xx.createEl("button", { text: `Restore from file` }, (e3) => { e3.addEventListener("click", async () => { const f = await this.app.vault.getFiles().filter((e4) => path2id(e4.path) == k); if (f.length == 0) { Logger("Not found in vault", LOG_LEVEL.NOTICE); return; } await this.plugin.updateIntoDB(f[0]); xx.remove(); }); }); xx.addClass("mod-warning"); } } else { containerCorruptedDataEl.createEl("div", { text: "There is no missing or waiting chunk." }); } applyDisplayEnabled(); addScreenElement("70", containerCorruptedDataEl); if (lastVersion != this.plugin.settings.lastReadUpdates) { if (JSON.stringify(this.plugin.settings) != JSON.stringify(DEFAULT_SETTINGS)) { changeDisplay("100"); } else { changeDisplay("110"); } } else { if (isAnySyncEnabled()) { changeDisplay("0"); } else { changeDisplay("110"); } } } }; // src/DocumentHistoryModal.ts var import_obsidian6 = __toModule(require("obsidian")); var import_diff_match_patch2 = __toModule(require_diff_match_patch()); var DocumentHistoryModal = class extends import_obsidian6.Modal { constructor(app2, plugin, file) { super(app2); this.showDiff = false; this.revs_info = []; this.currentText = ""; this.currentDeleted = false; this.plugin = plugin; this.file = file instanceof import_obsidian6.TFile ? file.path : file; if (localStorage.getItem("ols-history-highlightdiff") == "1") { this.showDiff = true; } } async loadFile() { const db = this.plugin.localDatabase; try { const w = await db.localDatabase.get(path2id(this.file), { revs_info: true }); this.revs_info = w._revs_info.filter((e3) => e3.status == "available"); this.range.max = `${this.revs_info.length - 1}`; this.range.value = this.range.max; this.fileInfo.setText(`${this.file} / ${this.revs_info.length} revisions`); await this.loadRevs(); } catch (ex) { if (ex.status && ex.status == 404) { this.range.max = "0"; this.range.value = ""; this.range.disabled = true; this.showDiff; this.contentView.setText(`History of this file was not recorded.`); } } } async loadRevs() { if (this.revs_info.length == 0) return; const db = this.plugin.localDatabase; const index = this.revs_info.length - 1 - this.range.value / 1; const rev = this.revs_info[index]; const w = await db.getDBEntry(path2id(this.file), { rev: rev.rev }, false, false, true); this.currentText = ""; this.currentDeleted = false; if (w === false) { this.currentDeleted = true; this.info.innerHTML = ""; this.contentView.innerHTML = `Could not read this revision
(${rev.rev})`; } else { this.currentDoc = w; this.info.innerHTML = `Modified:${new Date(w.mtime).toLocaleString()}`; let result = ""; const w1data = w.datatype == "plain" ? w.data : base64ToString(w.data); this.currentDeleted = w.deleted; this.currentText = w1data; if (this.showDiff) { const prevRevIdx = this.revs_info.length - 1 - (this.range.value / 1 - 1); if (prevRevIdx >= 0 && prevRevIdx < this.revs_info.length) { const oldRev = this.revs_info[prevRevIdx].rev; const w2 = await db.getDBEntry(path2id(this.file), { rev: oldRev }, false, false, true); if (w2 != false) { const dmp = new import_diff_match_patch2.diff_match_patch(); const w2data = w2.datatype == "plain" ? w2.data : base64ToString(w2.data); const diff = dmp.diff_main(w2data, w1data); dmp.diff_cleanupSemantic(diff); for (const v of diff) { const x1 = v[0]; const x2 = v[1]; if (x1 == import_diff_match_patch2.DIFF_DELETE) { result += "" + escapeStringToHTML(x2) + ""; } else if (x1 == import_diff_match_patch2.DIFF_EQUAL) { result += "" + escapeStringToHTML(x2) + ""; } else if (x1 == import_diff_match_patch2.DIFF_INSERT) { result += "" + escapeStringToHTML(x2) + ""; } } result = result.replace(/\n/g, "
"); } else { result = escapeStringToHTML(w1data); } } else { result = escapeStringToHTML(w1data); } } else { result = escapeStringToHTML(w1data); } this.contentView.innerHTML = (this.currentDeleted ? "(At this revision, the file has been deleted)\n" : "") + result; } } onOpen() { const { contentEl } = this; contentEl.empty(); contentEl.createEl("h2", { text: "Document History" }); this.fileInfo = contentEl.createDiv(""); this.fileInfo.addClass("op-info"); const divView = contentEl.createDiv(""); divView.addClass("op-flex"); divView.createEl("input", { type: "range" }, (e3) => { this.range = e3; e3.addEventListener("change", (e4) => { this.loadRevs(); }); e3.addEventListener("input", (e4) => { this.loadRevs(); }); }); contentEl.createDiv("", (e3) => { e3.createEl("label", {}, (label) => { label.appendChild(createEl("input", { type: "checkbox" }, (checkbox) => { if (this.showDiff) { checkbox.checked = true; } checkbox.addEventListener("input", (evt) => { this.showDiff = checkbox.checked; localStorage.setItem("ols-history-highlightdiff", this.showDiff == true ? "1" : ""); this.loadRevs(); }); })); label.appendText("Highlight diff"); }); }).addClass("op-info"); this.info = contentEl.createDiv(""); this.info.addClass("op-info"); this.loadFile(); const div = contentEl.createDiv({ text: "Loading old revisions..." }); this.contentView = div; div.addClass("op-scrollable"); div.addClass("op-pre"); const buttons = contentEl.createDiv(""); buttons.createEl("button", { text: "Copy to clipboard" }, (e3) => { e3.addClass("mod-cta"); e3.addEventListener("click", async () => { await navigator.clipboard.writeText(this.currentText); Logger(`Old content copied to clipboard`, LOG_LEVEL.NOTICE); }); }); async function focusFile(path) { const targetFile = app.vault.getFiles().find((f) => f.path === path); if (targetFile) { const leaf = app.workspace.getLeaf(false); await leaf.openFile(targetFile); } else { Logger("The file could not view on the editor", LOG_LEVEL.NOTICE); } } buttons.createEl("button", { text: "Back to this revision" }, (e3) => { e3.addClass("mod-cta"); e3.addEventListener("click", async () => { var _a, _b; const pathToWrite = this.file.startsWith("i:") ? this.file.substring("i:".length) : this.file; if (!isValidPath(pathToWrite)) { Logger("Path is not valid to write content.", LOG_LEVEL.INFO); } if (((_a = this.currentDoc) == null ? void 0 : _a.datatype) == "plain") { await this.app.vault.adapter.write(pathToWrite, this.currentDoc.data); await focusFile(pathToWrite); this.close(); } else if (((_b = this.currentDoc) == null ? void 0 : _b.datatype) == "newnote") { await this.app.vault.adapter.writeBinary(pathToWrite, base64ToArrayBuffer(this.currentDoc.data)); await focusFile(pathToWrite); this.close(); } else { Logger(`Could not parse entry`, LOG_LEVEL.NOTICE); } }); }); } onClose() { const { contentEl } = this; contentEl.empty(); } }; // src/dialogs.ts var import_obsidian7 = __toModule(require("obsidian")); // node_modules/svelte/internal/index.mjs function noop() { } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === "function"; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function"); } function is_empty(obj) { return Object.keys(obj).length === 0; } var tasks = new Set(); var is_hydrating = false; function start_hydrating() { is_hydrating = true; } function end_hydrating() { is_hydrating = false; } function append(target, node) { target.appendChild(node); } function append_styles(target, style_sheet_id, styles) { const append_styles_to = get_root_for_style(target); if (!append_styles_to.getElementById(style_sheet_id)) { const style = element("style"); style.id = style_sheet_id; style.textContent = styles; append_stylesheet(append_styles_to, style); } } function get_root_for_style(node) { if (!node) return document; const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; if (root && root.host) { return root; } return node.ownerDocument; } function append_stylesheet(node, style) { append(node.head || node, style); } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { node.parentNode.removeChild(node); } function destroy_each(iterations, detaching) { for (let i2 = 0; i2 < iterations.length; i2 += 1) { if (iterations[i2]) iterations[i2].d(detaching); } } function element(name) { return document.createElement(name); } function text(data) { return document.createTextNode(data); } function space() { return text(" "); } function empty() { return text(""); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value); } function children(element2) { return Array.from(element2.childNodes); } function set_data(text2, data) { data = "" + data; if (text2.wholeText !== data) text2.data = data; } function set_style(node, key, value, important) { if (value === null) { node.style.removeProperty(key); } else { node.style.setProperty(key, value, important ? "important" : ""); } } function toggle_class(element2, name, toggle) { element2.classList[toggle ? "add" : "remove"](name); } var managed_styles = new Map(); var current_component; function set_current_component(component) { current_component = component; } function get_current_component() { if (!current_component) throw new Error("Function called outside component initialization"); return current_component; } function onMount(fn) { get_current_component().$$.on_mount.push(fn); } var dirty_components = []; var binding_callbacks = []; var render_callbacks = []; var flush_callbacks = []; var resolved_promise = Promise.resolve(); var update_scheduled = false; function schedule_update() { if (!update_scheduled) { update_scheduled = true; resolved_promise.then(flush); } } function add_render_callback(fn) { render_callbacks.push(fn); } var seen_callbacks = new Set(); var flushidx = 0; function flush() { const saved_component = current_component; do { while (flushidx < dirty_components.length) { const component = dirty_components[flushidx]; flushidx++; set_current_component(component); update(component.$$); } set_current_component(null); dirty_components.length = 0; flushidx = 0; while (binding_callbacks.length) binding_callbacks.pop()(); for (let i2 = 0; i2 < render_callbacks.length; i2 += 1) { const callback = render_callbacks[i2]; if (!seen_callbacks.has(callback)) { seen_callbacks.add(callback); callback(); } } render_callbacks.length = 0; } while (dirty_components.length); while (flush_callbacks.length) { flush_callbacks.pop()(); } update_scheduled = false; seen_callbacks.clear(); set_current_component(saved_component); } function update($$) { if ($$.fragment !== null) { $$.update(); run_all($$.before_update); const dirty = $$.dirty; $$.dirty = [-1]; $$.fragment && $$.fragment.p($$.ctx, dirty); $$.after_update.forEach(add_render_callback); } } var outroing = new Set(); function transition_in(block, local) { if (block && block.i) { outroing.delete(block); block.i(local); } } var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global; var boolean_attributes = new Set([ "allowfullscreen", "allowpaymentrequest", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled", "formnovalidate", "hidden", "ismap", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected" ]); function mount_component(component, target, anchor, customElement) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment && fragment.m(target, anchor); if (!customElement) { add_render_callback(() => { const new_on_destroy = on_mount.map(run).filter(is_function); if (on_destroy) { on_destroy.push(...new_on_destroy); } else { run_all(new_on_destroy); } component.$$.on_mount = []; }); } after_update.forEach(add_render_callback); } function destroy_component(component, detaching) { const $$ = component.$$; if ($$.fragment !== null) { run_all($$.on_destroy); $$.fragment && $$.fragment.d(detaching); $$.on_destroy = $$.fragment = null; $$.ctx = []; } } function make_dirty(component, i2) { if (component.$$.dirty[0] === -1) { dirty_components.push(component); schedule_update(); component.$$.dirty.fill(0); } component.$$.dirty[i2 / 31 | 0] |= 1 << i2 % 31; } function init(component, options, instance2, create_fragment2, not_equal, props, append_styles2, dirty = [-1]) { const parent_component = current_component; set_current_component(component); const $$ = component.$$ = { fragment: null, ctx: null, props, update: noop, not_equal, bound: blank_object(), on_mount: [], on_destroy: [], on_disconnect: [], before_update: [], after_update: [], context: new Map(options.context || (parent_component ? parent_component.$$.context : [])), callbacks: blank_object(), dirty, skip_bound: false, root: options.target || parent_component.$$.root }; append_styles2 && append_styles2($$.root); let ready = false; $$.ctx = instance2 ? instance2(component, options.props || {}, (i2, ret, ...rest) => { const value = rest.length ? rest[0] : ret; if ($$.ctx && not_equal($$.ctx[i2], $$.ctx[i2] = value)) { if (!$$.skip_bound && $$.bound[i2]) $$.bound[i2](value); if (ready) make_dirty(component, i2); } return ret; }) : []; $$.update(); ready = true; run_all($$.before_update); $$.fragment = create_fragment2 ? create_fragment2($$.ctx) : false; if (options.target) { if (options.hydrate) { start_hydrating(); const nodes = children(options.target); $$.fragment && $$.fragment.l(nodes); nodes.forEach(detach); } else { $$.fragment && $$.fragment.c(); } if (options.intro) transition_in(component.$$.fragment); mount_component(component, options.target, options.anchor, options.customElement); end_hydrating(); flush(); } set_current_component(parent_component); } var SvelteElement; if (typeof HTMLElement === "function") { SvelteElement = class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { const { on_mount } = this.$$; this.$$.on_disconnect = on_mount.map(run).filter(is_function); for (const key in this.$$.slotted) { this.appendChild(this.$$.slotted[key]); } } attributeChangedCallback(attr2, _oldValue, newValue) { this[attr2] = newValue; } disconnectedCallback() { run_all(this.$$.on_disconnect); } $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }; } var SvelteComponent = class { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }; // src/PluginPane.svelte function add_css(target) { append_styles(target, "svelte-1907s6a", ".ols-plugins-div-buttons.svelte-1907s6a{display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px}.wrapToggle.svelte-1907s6a{display:flex;justify-content:center;align-content:center}"); } function get_each_context(ctx, list, i2) { const child_ctx = ctx.slice(); child_ctx[25] = list[i2][0]; child_ctx[26] = list[i2][1]; return child_ctx; } function get_each_context_1(ctx, list, i2) { const child_ctx = ctx.slice(); child_ctx[0] = list[i2]; return child_ctx; } function create_else_block(ctx) { let each_1_anchor; let each_value = ctx[2]; let each_blocks = []; for (let i2 = 0; i2 < each_value.length; i2 += 1) { each_blocks[i2] = create_each_block(get_each_context(ctx, each_value, i2)); } return { c() { for (let i2 = 0; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].c(); } each_1_anchor = empty(); }, m(target, anchor) { for (let i2 = 0; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].m(target, anchor); } insert(target, each_1_anchor, anchor); }, p(ctx2, dirty) { if (dirty & 204) { each_value = ctx2[2]; let i2; for (i2 = 0; i2 < each_value.length; i2 += 1) { const child_ctx = get_each_context(ctx2, each_value, i2); if (each_blocks[i2]) { each_blocks[i2].p(child_ctx, dirty); } else { each_blocks[i2] = create_each_block(child_ctx); each_blocks[i2].c(); each_blocks[i2].m(each_1_anchor.parentNode, each_1_anchor); } } for (; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].d(1); } each_blocks.length = each_value.length; } }, d(detaching) { destroy_each(each_blocks, detaching); if (detaching) detach(each_1_anchor); } }; } function create_if_block_1(ctx) { let tr; return { c() { tr = element("tr"); tr.innerHTML = `No plugins found.`; }, m(target, anchor) { insert(target, tr, anchor); }, p: noop, d(detaching) { if (detaching) detach(tr); } }; } function create_if_block(ctx) { let tr; return { c() { tr = element("tr"); tr.innerHTML = `Retrieving...`; }, m(target, anchor) { insert(target, tr, anchor); }, p: noop, d(detaching) { if (detaching) detach(tr); } }; } function create_else_block_2(ctx) { let div1; let div0; let mounted; let dispose; function click_handler_1() { return ctx[20](ctx[0]); } return { c() { div1 = element("div"); div0 = element("div"); attr(div0, "class", "checkbox-container"); toggle_class(div0, "is-enabled", ctx[3][ctx[0].deviceVaultName + "---" + ctx[0].manifest.id + "---plugin"]); attr(div1, "class", "wrapToggle svelte-1907s6a"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); if (!mounted) { dispose = listen(div0, "click", click_handler_1); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & 12) { toggle_class(div0, "is-enabled", ctx[3][ctx[0].deviceVaultName + "---" + ctx[0].manifest.id + "---plugin"]); } }, d(detaching) { if (detaching) detach(div1); mounted = false; dispose(); } }; } function create_if_block_3(ctx) { let t3; return { c() { t3 = text("-"); }, m(target, anchor) { insert(target, t3, anchor); }, p: noop, d(detaching) { if (detaching) detach(t3); } }; } function create_else_block_1(ctx) { let div1; let div0; let mounted; let dispose; function click_handler_2() { return ctx[21](ctx[0]); } return { c() { div1 = element("div"); div0 = element("div"); attr(div0, "class", "checkbox-container"); toggle_class(div0, "is-enabled", ctx[3][ctx[0].deviceVaultName + "---" + ctx[0].manifest.id + "---setting"]); attr(div1, "class", "wrapToggle svelte-1907s6a"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); if (!mounted) { dispose = listen(div0, "click", click_handler_2); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & 12) { toggle_class(div0, "is-enabled", ctx[3][ctx[0].deviceVaultName + "---" + ctx[0].manifest.id + "---setting"]); } }, d(detaching) { if (detaching) detach(div1); mounted = false; dispose(); } }; } function create_if_block_2(ctx) { let t3; return { c() { t3 = text("-"); }, m(target, anchor) { insert(target, t3, anchor); }, p: noop, d(detaching) { if (detaching) detach(t3); } }; } function create_each_block_1(ctx) { let tr0; let td0; let t0_value = ctx[0].manifest.name + ""; let t0; let t1; let td1; let t2_value = ctx[0].versionInfo + ""; let t22; let t3_value = getDispString(ctx[0].versionFlag) + ""; let t3; let t4; let td2; let t5; let tr1; let td3; let t7; let td4; let t8_value = ctx[0].mtimeInfo + ""; let t8; let t9_value = getDispString(ctx[0].mtimeFlag) + ""; let t9; let t10; let td5; let t11; let tr2; function select_block_type_1(ctx2, dirty) { if (ctx2[0].versionFlag === "EVEN" || ctx2[0].versionFlag === "") return create_if_block_3; return create_else_block_2; } let current_block_type = select_block_type_1(ctx, -1); let if_block0 = current_block_type(ctx); function select_block_type_2(ctx2, dirty) { if (ctx2[0].mtimeFlag === "EVEN" || ctx2[0].mtimeFlag === "") return create_if_block_2; return create_else_block_1; } let current_block_type_1 = select_block_type_2(ctx, -1); let if_block1 = current_block_type_1(ctx); return { c() { tr0 = element("tr"); td0 = element("td"); t0 = text(t0_value); t1 = space(); td1 = element("td"); t22 = text(t2_value); t3 = text(t3_value); t4 = space(); td2 = element("td"); if_block0.c(); t5 = space(); tr1 = element("tr"); td3 = element("td"); td3.textContent = "Settings"; t7 = space(); td4 = element("td"); t8 = text(t8_value); t9 = text(t9_value); t10 = space(); td5 = element("td"); if_block1.c(); t11 = space(); tr2 = element("tr"); tr2.innerHTML = ` `; attr(td0, "class", "sls-table-head"); attr(td1, "class", "sls-table-tail tcenter"); attr(td2, "class", "sls-table-tail tcenter"); attr(td3, "class", "sls-table-head"); attr(td4, "class", "sls-table-tail tcenter"); attr(td5, "class", "sls-table-tail tcenter"); attr(tr2, "class", "divider"); }, m(target, anchor) { insert(target, tr0, anchor); append(tr0, td0); append(td0, t0); append(tr0, t1); append(tr0, td1); append(td1, t22); append(td1, t3); append(tr0, t4); append(tr0, td2); if_block0.m(td2, null); insert(target, t5, anchor); insert(target, tr1, anchor); append(tr1, td3); append(tr1, t7); append(tr1, td4); append(td4, t8); append(td4, t9); append(tr1, t10); append(tr1, td5); if_block1.m(td5, null); insert(target, t11, anchor); insert(target, tr2, anchor); }, p(ctx2, dirty) { if (dirty & 4 && t0_value !== (t0_value = ctx2[0].manifest.name + "")) set_data(t0, t0_value); if (dirty & 4 && t2_value !== (t2_value = ctx2[0].versionInfo + "")) set_data(t22, t2_value); if (dirty & 4 && t3_value !== (t3_value = getDispString(ctx2[0].versionFlag) + "")) set_data(t3, t3_value); if (current_block_type === (current_block_type = select_block_type_1(ctx2, dirty)) && if_block0) { if_block0.p(ctx2, dirty); } else { if_block0.d(1); if_block0 = current_block_type(ctx2); if (if_block0) { if_block0.c(); if_block0.m(td2, null); } } if (dirty & 4 && t8_value !== (t8_value = ctx2[0].mtimeInfo + "")) set_data(t8, t8_value); if (dirty & 4 && t9_value !== (t9_value = getDispString(ctx2[0].mtimeFlag) + "")) set_data(t9, t9_value); if (current_block_type_1 === (current_block_type_1 = select_block_type_2(ctx2, dirty)) && if_block1) { if_block1.p(ctx2, dirty); } else { if_block1.d(1); if_block1 = current_block_type_1(ctx2); if (if_block1) { if_block1.c(); if_block1.m(td5, null); } } }, d(detaching) { if (detaching) detach(tr0); if_block0.d(); if (detaching) detach(t5); if (detaching) detach(tr1); if_block1.d(); if (detaching) detach(t11); if (detaching) detach(tr2); } }; } function create_each_block(ctx) { let tr; let th0; let t0_value = ctx[25] + ""; let t0; let t1; let th1; let button; let t3; let each_1_anchor; let mounted; let dispose; function click_handler() { return ctx[19](ctx[25]); } let each_value_1 = ctx[26]; let each_blocks = []; for (let i2 = 0; i2 < each_value_1.length; i2 += 1) { each_blocks[i2] = create_each_block_1(get_each_context_1(ctx, each_value_1, i2)); } return { c() { tr = element("tr"); th0 = element("th"); t0 = text(t0_value); t1 = space(); th1 = element("th"); button = element("button"); button.textContent = "\u2714"; t3 = space(); for (let i2 = 0; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].c(); } each_1_anchor = empty(); attr(th0, "colspan", "2"); attr(th0, "class", "sls-plugins-tbl-device-head"); attr(button, "class", "mod-cta"); attr(th1, "class", "sls-plugins-tbl-device-head"); }, m(target, anchor) { insert(target, tr, anchor); append(tr, th0); append(th0, t0); append(tr, t1); append(tr, th1); append(th1, button); insert(target, t3, anchor); for (let i2 = 0; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].m(target, anchor); } insert(target, each_1_anchor, anchor); if (!mounted) { dispose = listen(button, "click", click_handler); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; if (dirty & 4 && t0_value !== (t0_value = ctx[25] + "")) set_data(t0, t0_value); if (dirty & 76) { each_value_1 = ctx[26]; let i2; for (i2 = 0; i2 < each_value_1.length; i2 += 1) { const child_ctx = get_each_context_1(ctx, each_value_1, i2); if (each_blocks[i2]) { each_blocks[i2].p(child_ctx, dirty); } else { each_blocks[i2] = create_each_block_1(child_ctx); each_blocks[i2].c(); each_blocks[i2].m(each_1_anchor.parentNode, each_1_anchor); } } for (; i2 < each_blocks.length; i2 += 1) { each_blocks[i2].d(1); } each_blocks.length = each_value_1.length; } }, d(detaching) { if (detaching) detach(tr); if (detaching) detach(t3); destroy_each(each_blocks, detaching); if (detaching) detach(each_1_anchor); mounted = false; dispose(); } }; } function create_fragment(ctx) { let div5; let h1; let t1; let div1; let t22; let div0; let t3; let div2; let table; let tr; let t9; let t10; let div3; let button0; let t12; let button1; let t14; let div4; let button2; let t16; let button3; let t18; let button4; let mounted; let dispose; function select_block_type(ctx2, dirty) { if (!ctx2[2]) return create_if_block; if (ctx2[2].length == 0) return create_if_block_1; return create_else_block; } let current_block_type = select_block_type(ctx, -1); let if_block = current_block_type(ctx); return { c() { div5 = element("div"); h1 = element("h1"); h1.textContent = "Plugins and their settings"; t1 = space(); div1 = element("div"); t22 = text("Show own items\n "); div0 = element("div"); t3 = space(); div2 = element("div"); table = element("table"); tr = element("tr"); tr.innerHTML = `Name Info Target`; t9 = space(); if_block.c(); t10 = space(); div3 = element("div"); button0 = element("button"); button0.textContent = "Replicate and refresh"; t12 = space(); button1 = element("button"); button1.textContent = "Clear Selection"; t14 = space(); div4 = element("div"); button2 = element("button"); button2.textContent = "Check Updates"; t16 = space(); button3 = element("button"); button3.textContent = "Scan installed"; t18 = space(); button4 = element("button"); button4.textContent = "Apply all"; attr(div0, "class", "checkbox-container"); toggle_class(div0, "is-enabled", ctx[1]); attr(div1, "class", "ols-plugins-div-buttons svelte-1907s6a"); set_style(tr, "position", "sticky"); attr(table, "class", "sls-plugins-tbl"); attr(div2, "class", "sls-plugins-wrap"); attr(button0, "class", ""); attr(button1, "class", ""); attr(div3, "class", "ols-plugins-div-buttons svelte-1907s6a"); attr(button2, "class", "mod-cta"); attr(button3, "class", "mod-cta"); attr(button4, "class", "mod-cta"); attr(div4, "class", "ols-plugins-div-buttons svelte-1907s6a"); }, m(target, anchor) { insert(target, div5, anchor); append(div5, h1); append(div5, t1); append(div5, div1); append(div1, t22); append(div1, div0); append(div5, t3); append(div5, div2); append(div2, table); append(table, tr); append(table, t9); if_block.m(table, null); append(div5, t10); append(div5, div3); append(div3, button0); append(div3, t12); append(div3, button1); append(div5, t14); append(div5, div4); append(div4, button2); append(div4, t16); append(div4, button3); append(div4, t18); append(div4, button4); if (!mounted) { dispose = [ listen(div0, "click", ctx[5]), listen(button0, "click", ctx[11]), listen(button1, "click", ctx[4]), listen(button2, "click", ctx[10]), listen(button3, "click", ctx[8]), listen(button4, "click", ctx[9]) ]; mounted = true; } }, p(ctx2, [dirty]) { if (dirty & 2) { toggle_class(div0, "is-enabled", ctx2[1]); } if (current_block_type === (current_block_type = select_block_type(ctx2, dirty)) && if_block) { if_block.p(ctx2, dirty); } else { if_block.d(1); if_block = current_block_type(ctx2); if (if_block) { if_block.c(); if_block.m(table, null); } } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div5); if_block.d(); mounted = false; run_all(dispose); } }; } function getDispString(stat) { if (stat == "") return ""; if (stat == "NEWER") return " (Newer)"; if (stat == "OLDER") return " (Older)"; if (stat == "EVEN") return " (Even)"; if (stat == "EVEN_BUT_DIFFERENT") return " (Even but different)"; if (stat == "REMOTE_ONLY") return " (Remote Only)"; return ""; } function instance($$self, $$props, $$invalidate) { var _a, _b, _c, _d; let { plugin } = $$props; let plugins = []; let deviceAndPlugins = {}; let devicePluginList = null; let ownPlugins = null; let showOwnPlugins = false; let targetList = {}; function saveTargetList() { window.localStorage.setItem("ols-plugin-targetlist", JSON.stringify(targetList)); } function loadTargetList() { let e3 = window.localStorage.getItem("ols-plugin-targetlist") || "{}"; try { $$invalidate(3, targetList = JSON.parse(e3)); } catch (_) { } } function clearSelection() { $$invalidate(3, targetList = {}); } async function updateList() { let x = await plugin.getPluginList(); $$invalidate(18, ownPlugins = x.thisDevicePlugins); $$invalidate(16, plugins = Object.values(x.allPlugins)); let targetListItems = Array.from(new Set(plugins.map((e3) => e3.deviceVaultName + "---" + e3.manifest.id))); let newTargetList = {}; for (const id of targetListItems) { for (const tag of ["---plugin", "---setting"]) { newTargetList[id + tag] = id + tag in targetList && targetList[id + tag]; } } $$invalidate(3, targetList = newTargetList); saveTargetList(); } onMount(async () => { loadTargetList(); await updateList(); }); function toggleShowOwnPlugins() { $$invalidate(1, showOwnPlugins = !showOwnPlugins); } function toggleTarget(key) { $$invalidate(3, targetList[key] = !targetList[key], targetList); saveTargetList(); } function toggleAll(devicename) { for (const c in targetList) { if (c.startsWith(devicename)) { $$invalidate(3, targetList[c] = true, targetList); } } } async function sweepPlugins() { await plugin.app.plugins.loadManifests(); await plugin.sweepPlugin(true); updateList(); } async function applyPlugins() { for (const c in targetList) { if (targetList[c] == true) { const [deviceAndVault, id, opt] = c.split("---"); if (deviceAndVault in deviceAndPlugins) { const entry = deviceAndPlugins[deviceAndVault].find((e3) => e3.manifest.id == id); if (entry) { if (opt == "plugin") { if (entry.versionFlag != "EVEN") await plugin.applyPlugin(entry); } else if (opt == "setting") { if (entry.mtimeFlag != "EVEN") await plugin.applyPluginData(entry); } } } } } await plugin.app.plugins.loadManifests(); await plugin.sweepPlugin(true); updateList(); } async function checkUpdates() { await plugin.checkPluginUpdate(); } async function replicateAndRefresh() { await plugin.replicate(true); updateList(); } const click_handler = (deviceName) => toggleAll(deviceName); const click_handler_1 = (plugin2) => toggleTarget(plugin2.deviceVaultName + "---" + plugin2.manifest.id + "---plugin"); const click_handler_2 = (plugin2) => toggleTarget(plugin2.deviceVaultName + "---" + plugin2.manifest.id + "---setting"); $$self.$$set = ($$props2) => { if ("plugin" in $$props2) $$invalidate(0, plugin = $$props2.plugin); }; $$self.$$.update = () => { if ($$self.$$.dirty & 520195) { $: { $$invalidate(17, deviceAndPlugins = {}); for (const p of plugins) { if (p.deviceVaultName == plugin.deviceAndVaultName && !showOwnPlugins) { continue; } if (!(p.deviceVaultName in deviceAndPlugins)) { $$invalidate(17, deviceAndPlugins[p.deviceVaultName] = [], deviceAndPlugins); } let dispInfo = { ...p, versionInfo: "", mtimeInfo: "", versionFlag: "", mtimeFlag: "" }; dispInfo.versionInfo = p.manifest.version; let x = new Date().getTime() / 1e3; let mtime = p.mtime / 1e3; let diff = (x - mtime) / 60; if (p.mtime == 0) { dispInfo.mtimeInfo = `-`; } else if (diff < 60) { dispInfo.mtimeInfo = `${diff | 0} Mins ago`; } else if (diff < 60 * 24) { dispInfo.mtimeInfo = `${diff / 60 | 0} Hours ago`; } else if (diff < 60 * 24 * 10) { dispInfo.mtimeInfo = `${diff / (60 * 24) | 0} Days ago`; } else { dispInfo.mtimeInfo = new Date(dispInfo.mtime).toLocaleString(); } let id = p.manifest.id; if (id in ownPlugins) { const ownPlugin = ownPlugins[id]; let localVer = versionNumberString2Number(ownPlugin.manifest.version); let pluginVer = versionNumberString2Number(p.manifest.version); if (localVer > pluginVer) { dispInfo.versionFlag = "OLDER"; } else if (localVer == pluginVer) { if (ownPlugin.manifestJson + ($$invalidate(12, _a = ownPlugin.styleCss) !== null && _a !== void 0 ? _a : "") + ownPlugin.mainJs != p.manifestJson + ($$invalidate(13, _b = p.styleCss) !== null && _b !== void 0 ? _b : "") + p.mainJs) { dispInfo.versionFlag = "EVEN_BUT_DIFFERENT"; } else { dispInfo.versionFlag = "EVEN"; } } else if (localVer < pluginVer) { dispInfo.versionFlag = "NEWER"; } if (($$invalidate(14, _c = ownPlugin.dataJson) !== null && _c !== void 0 ? _c : "") == ($$invalidate(15, _d = p.dataJson) !== null && _d !== void 0 ? _d : "")) { if (ownPlugin.mtime == 0 && p.mtime == 0) { dispInfo.mtimeFlag = ""; } else { dispInfo.mtimeFlag = "EVEN"; } } else { if ((ownPlugin.mtime / 1e3 | 0) > (p.mtime / 1e3 | 0)) { dispInfo.mtimeFlag = "OLDER"; } else if ((ownPlugin.mtime / 1e3 | 0) == (p.mtime / 1e3 | 0)) { dispInfo.mtimeFlag = "EVEN_BUT_DIFFERENT"; } else if ((ownPlugin.mtime / 1e3 | 0) < (p.mtime / 1e3 | 0)) { dispInfo.mtimeFlag = "NEWER"; } } } else { dispInfo.versionFlag = "REMOTE_ONLY"; dispInfo.mtimeFlag = "REMOTE_ONLY"; } deviceAndPlugins[p.deviceVaultName].push(dispInfo); } $$invalidate(2, devicePluginList = Object.entries(deviceAndPlugins)); } } }; return [ plugin, showOwnPlugins, devicePluginList, targetList, clearSelection, toggleShowOwnPlugins, toggleTarget, toggleAll, sweepPlugins, applyPlugins, checkUpdates, replicateAndRefresh, _a, _b, _c, _d, plugins, deviceAndPlugins, ownPlugins, click_handler, click_handler_1, click_handler_2 ]; } var PluginPane = class extends SvelteComponent { constructor(options) { super(); init(this, options, instance, create_fragment, safe_not_equal, { plugin: 0 }, add_css); } }; var PluginPane_default = PluginPane; // src/dialogs.ts var PluginDialogModal = class extends import_obsidian7.Modal { constructor(app2, plugin) { super(app2); this.component = null; this.plugin = plugin; } onOpen() { const { contentEl } = this; if (this.component == null) { this.component = new PluginPane_default({ target: contentEl, props: { plugin: this.plugin } }); } } onClose() { if (this.component != null) { this.component.$destroy(); this.component = null; } } }; var InputStringDialog = class extends import_obsidian7.Modal { constructor(app2, title, key, placeholder, onSubmit) { super(app2); this.result = false; this.isManuallyClosed = false; this.onSubmit = onSubmit; this.title = title; this.placeholder = placeholder; this.key = key; } onOpen() { const { contentEl } = this; contentEl.createEl("h1", { text: this.title }); new import_obsidian7.Setting(contentEl).setName(this.key).addText((text2) => text2.onChange((value) => { this.result = value; })); new import_obsidian7.Setting(contentEl).addButton((btn) => btn.setButtonText("Ok").setCta().onClick(() => { this.isManuallyClosed = true; this.close(); })).addButton((btn) => btn.setButtonText("Cancel").setCta().onClick(() => { this.close(); })); } onClose() { const { contentEl } = this; contentEl.empty(); if (this.isManuallyClosed) { this.onSubmit(this.result); } else { this.onSubmit(false); } } }; var PopoverSelectString = class extends import_obsidian7.FuzzySuggestModal { constructor(app2, note, placeholder, getItemsFun, callback) { super(app2); this.callback = () => { }; this.getItemsFun = () => { return ["yes", "no"]; }; this.app = app2; this.setPlaceholder((placeholder != null ? placeholder : "y/n) ") + note); if (getItemsFun) this.getItemsFun = getItemsFun; this.callback = callback; } getItems() { return this.getItemsFun(); } getItemText(item) { return item; } onChooseItem(item, evt) { this.callback(item); this.callback = null; } onClose() { setTimeout(() => { if (this.callback != null) { this.callback(""); } }, 100); } }; // src/main.ts var isDebug = false; setNoticeClass(import_obsidian8.Notice); var ICHeader = "i:"; var ICHeaderEnd = "i;"; var ICHeaderLength = ICHeader.length; var FileWatchEventQueueMax = 10; function getAbstractFileByPath(path) { var _a, _b; if ("getAbstractFileByPathInsensitive" in app.vault && ((_b = (_a = app.vault.adapter) == null ? void 0 : _a.insensitive) != null ? _b : false)) { return app.vault.getAbstractFileByPathInsensitive(path); } else { return app.vault.getAbstractFileByPath(path); } } function isInternalChunk(str) { return str.startsWith(ICHeader); } function id2filenameInternalChunk(str) { return str.substring(ICHeaderLength); } function filename2idInternalChunk(str) { return ICHeader + str; } var CHeader = "h:"; var CHeaderEnd = "h;"; function isChunk(str) { return str.startsWith(CHeader); } var PSCHeader = "ps:"; var PSCHeaderEnd = "ps;"; function isPluginChunk(str) { return str.startsWith(PSCHeader); } var askYesNo = (app2, message) => { return new Promise((res) => { const popover = new PopoverSelectString(app2, message, null, null, (result) => res(result)); popover.open(); }); }; var askSelectString = (app2, message, items) => { const getItemsFun = () => items; return new Promise((res) => { const popover = new PopoverSelectString(app2, message, "", getItemsFun, (result) => res(result)); popover.open(); }); }; var askString = (app2, title, key, placeholder) => { return new Promise((res) => { const dialog = new InputStringDialog(app2, title, key, placeholder, (result) => res(result)); dialog.open(); }); }; var touchedFiles = []; function touch(file) { const f = file instanceof import_obsidian8.TFile ? file : getAbstractFileByPath(file); const key = `${f.path}-${f.stat.mtime}-${f.stat.size}`; touchedFiles.unshift(key); touchedFiles = touchedFiles.slice(0, 100); } function recentlyTouched(file) { const key = `${file.path}-${file.stat.mtime}-${file.stat.size}`; if (touchedFiles.indexOf(key) == -1) return false; return true; } function clearTouched() { touchedFiles = []; } var ObsidianLiveSyncPlugin = class extends import_obsidian8.Plugin { constructor() { super(...arguments); this.logMessage = []; this.isMobile = false; this.isReady = false; this.watchedFileEventQueue = []; this.pluginDialog = null; this.gcTimerHandler = null; this.recentProcessedInternalFiles = []; this.addLogHook = null; this.notifies = {}; this.lastLog = ""; this.queuedEntries = []; this.queuedFiles = []; this.chunkWaitTimeout = 6e4; this.procInternalFiles = []; this.periodicSyncHandler = null; this.periodicPluginSweepHandler = null; this.lastMessage = ""; this.logHideTimer = null; this.conflictedCheckFiles = []; this.periodicInternalFileScanHandler = null; this.confirmPopup = null; } getVaultName() { var _a; return this.app.vault.getName() + (((_a = this.settings) == null ? void 0 : _a.additionalSuffixOfDatabaseName) ? "-" + this.settings.additionalSuffixOfDatabaseName : ""); } setInterval(handler, timeout) { const timer = window.setInterval(handler, timeout); this.registerInterval(timer); return timer; } isRedFlagRaised() { const redflag = getAbstractFileByPath((0, import_obsidian8.normalizePath)(FLAGMD_REDFLAG)); if (redflag != null) { return true; } return false; } showHistory(file) { if (!this.settings.useHistory) { Logger("You have to enable Use History in misc.", LOG_LEVEL.NOTICE); } else { new DocumentHistoryModal(this.app, this, file).open(); } } async fileHistory() { const pageLimit = 1e3; let nextKey = ""; const notes = []; do { const docs = await this.localDatabase.localDatabase.allDocs({ limit: pageLimit, startkey: nextKey, include_docs: true }); nextKey = ""; for (const row of docs.rows) { const doc = row.doc; nextKey = `${row.id}\u{10FFFF}`; if (!("type" in doc)) continue; if (doc.type == "newnote" || doc.type == "plain") { notes.push({ path: id2path(doc._id), mtime: doc.mtime }); } if (isChunk(nextKey)) { nextKey = CHeaderEnd; } } } while (nextKey != ""); notes.sort((a, b) => b.mtime - a.mtime); const notesList = notes.map((e3) => e3.path); const target = await askSelectString(this.app, "File to view History", notesList); if (target) { this.showHistory(target); } } async pickFileForResolve() { const pageLimit = 1e3; let nextKey = ""; const notes = []; do { const docs = await this.localDatabase.localDatabase.allDocs({ limit: pageLimit, startkey: nextKey, conflicts: true, include_docs: true }); nextKey = ""; for (const row of docs.rows) { const doc = row.doc; nextKey = `${row.id}\u{10FFFF}`; if (!("_conflicts" in doc)) continue; if (isInternalChunk(row.id)) continue; if (doc.type == "newnote" || doc.type == "plain") { notes.push({ path: id2path(doc._id), mtime: doc.mtime }); } if (isChunk(nextKey)) { nextKey = CHeaderEnd; } } } while (nextKey != ""); notes.sort((a, b) => b.mtime - a.mtime); const notesList = notes.map((e3) => e3.path); if (notesList.length == 0) { Logger("There are no conflicted documents", LOG_LEVEL.NOTICE); return; } const target = await askSelectString(this.app, "File to view History", notesList); if (target) { if (isInternalChunk(target)) { } else { await this.showIfConflicted(target); } } } async collectDeletedFiles() { const pageLimit = 1e3; let nextKey = ""; const limitDays = this.settings.automaticallyDeleteMetadataOfDeletedFiles; if (limitDays <= 0) return; Logger(`Checking expired file history`); const limit = Date.now() - 86400 * 1e3 * limitDays; const notes = []; do { const docs = await this.localDatabase.localDatabase.allDocs({ limit: pageLimit, startkey: nextKey, conflicts: true, include_docs: true }); nextKey = ""; for (const row of docs.rows) { const doc = row.doc; nextKey = `${row.id}\u{10FFFF}`; if (doc.type == "newnote" || doc.type == "plain") { if (doc.deleted && doc.mtime - limit < 0) { notes.push({ path: id2path(doc._id), mtime: doc.mtime, ttl: (doc.mtime - limit) / 1e3 / 86400, doc }); } } if (isChunk(nextKey)) { nextKey = CHeaderEnd; } } } while (nextKey != ""); if (notes.length == 0) { Logger("There are no old documents"); Logger(`Checking expired file history done`); return; } for (const v of notes) { Logger(`Deletion history expired: ${v.path}`); const delDoc = v.doc; delDoc._deleted = true; await this.localDatabase.localDatabase.put(delDoc); } Logger(`Checking expired file history done`); } async onload() { setLogger(this.addLog.bind(this)); Logger("loading plugin"); const manifestVersion = "0.16.6"; const packageVersion = "0.16.6"; Logger(`Self-hosted LiveSync v${manifestVersion} ${packageVersion} `); const lsKey = "obsidian-live-sync-ver" + this.getVaultName(); const last_version = localStorage.getItem(lsKey); await this.loadSettings(); const lastVersion = ~~(versionNumberString2Number(manifestVersion) / 1e3); if (lastVersion > this.settings.lastReadUpdates) { Logger("Self-hosted LiveSync has undergone a major upgrade. Please open the setting dialog, and check the information pane.", LOG_LEVEL.NOTICE); } if (this.app.isMobile) { this.isMobile = true; this.settings.disableRequestURI = true; } if (last_version && Number(last_version) < VER) { this.settings.liveSync = false; this.settings.syncOnSave = false; this.settings.syncOnStart = false; this.settings.syncOnFileOpen = false; this.settings.periodicReplication = false; this.settings.versionUpFlash = "Self-hosted LiveSync has been upgraded and some behaviors have changed incompatibly. All automatic synchronization is now disabled temporary. Ensure that other devices are also upgraded, and enable synchronization again."; this.saveSettings(); } localStorage.setItem(lsKey, `${VER}`); await this.openDatabase(); (0, import_obsidian8.addIcon)("replicate", ` `); (0, import_obsidian8.addIcon)("view-log", ` `); this.addRibbonIcon("replicate", "Replicate", async () => { await this.replicate(true); }); this.addRibbonIcon("view-log", "Show log", () => { new LogDisplayModal(this.app, this).open(); }); this.statusBar = this.addStatusBarItem(); this.statusBar.addClass("syncstatusbar"); this.refreshStatusText = this.refreshStatusText.bind(this); this.statusBar2 = this.addStatusBarItem(); this.watchVaultChange = this.watchVaultChange.bind(this); this.watchVaultCreate = this.watchVaultCreate.bind(this); this.watchVaultDelete = this.watchVaultDelete.bind(this); this.watchVaultRename = this.watchVaultRename.bind(this); this.watchVaultRawEvents = this.watchVaultRawEvents.bind(this); this.watchWorkspaceOpen = (0, import_obsidian8.debounce)(this.watchWorkspaceOpen.bind(this), 1e3, false); this.watchWindowVisibility = (0, import_obsidian8.debounce)(this.watchWindowVisibility.bind(this), 1e3, false); this.watchOnline = (0, import_obsidian8.debounce)(this.watchOnline.bind(this), 500, false); this.parseReplicationResult = this.parseReplicationResult.bind(this); this.setPeriodicSync = this.setPeriodicSync.bind(this); this.periodicSync = this.periodicSync.bind(this); this.loadQueuedFiles = this.loadQueuedFiles.bind(this); this.getPluginList = this.getPluginList.bind(this); this.addSettingTab(new ObsidianLiveSyncSettingTab(this.app, this)); this.app.workspace.onLayoutReady(async () => { this.registerFileWatchEvents(); if (this.localDatabase.isReady) try { if (this.isRedFlagRaised()) { this.settings.batchSave = false; this.settings.liveSync = false; this.settings.periodicReplication = false; this.settings.syncOnSave = false; this.settings.syncOnStart = false; this.settings.syncOnFileOpen = false; this.settings.autoSweepPlugins = false; this.settings.usePluginSync = false; this.settings.suspendFileWatching = true; this.settings.syncInternalFiles = false; await this.saveSettings(); await this.openDatabase(); const warningMessage = "The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured."; Logger(warningMessage, LOG_LEVEL.NOTICE); this.setStatusBarText(warningMessage); } else { if (this.settings.suspendFileWatching) { Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL.NOTICE); } const isInitialized = await this.initializeDatabase(); if (!isInitialized) { return false; } } await this.realizeSettingSyncMode(); this.registerWatchEvents(); if (this.settings.syncOnStart) { this.localDatabase.openReplication(this.settings, false, false, this.parseReplicationResult); } } catch (ex) { Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.VERBOSE); } }); const configURIBase = "obsidian://setuplivesync?settings="; this.addCommand({ id: "livesync-copysetupuri", name: "Copy setup URI", callback: async () => { const encryptingPassphrase = await askString(this.app, "Encrypt your settings", "Passphrase", ""); if (encryptingPassphrase === false) return; const setting = { ...this.settings }; const keys = Object.keys(setting); for (const k of keys) { if (JSON.stringify(k in setting ? setting[k] : "") == JSON.stringify(k in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[k] : "*")) { delete setting[k]; } } const encryptedSetting = encodeURIComponent(await encrypt(JSON.stringify(setting), encryptingPassphrase)); const uri = `${configURIBase}${encryptedSetting}`; await navigator.clipboard.writeText(uri); Logger("Setup URI copied to clipboard", LOG_LEVEL.NOTICE); } }); this.addCommand({ id: "livesync-copysetupurifull", name: "Copy setup URI (Full)", callback: async () => { const encryptingPassphrase = await askString(this.app, "Encrypt your settings", "Passphrase", ""); if (encryptingPassphrase === false) return; const setting = { ...this.settings }; const encryptedSetting = encodeURIComponent(await encrypt(JSON.stringify(setting), encryptingPassphrase)); const uri = `${configURIBase}${encryptedSetting}`; await navigator.clipboard.writeText(uri); Logger("Setup URI copied to clipboard", LOG_LEVEL.NOTICE); } }); this.addCommand({ id: "livesync-opensetupuri", name: "Open setup URI", callback: async () => { const setupURI = await askString(this.app, "Easy setup", "Set up URI", `${configURIBase}aaaaa`); if (setupURI === false) return; if (!setupURI.startsWith(`${configURIBase}`)) { Logger("Set up URI looks wrong.", LOG_LEVEL.NOTICE); return; } const config = decodeURIComponent(setupURI.substring(configURIBase.length)); console.dir(config); await setupWizard(config); } }); const setupWizard = async (confString) => { try { const oldConf = JSON.parse(JSON.stringify(this.settings)); const encryptingPassphrase = await askString(this.app, "Passphrase", "Passphrase for your settings", ""); if (encryptingPassphrase === false) return; const newConf = await JSON.parse(await decrypt(confString, encryptingPassphrase)); if (newConf) { const result = await askYesNo(this.app, "Importing LiveSync's conf, OK?"); if (result == "yes") { const newSettingW = Object.assign({}, DEFAULT_SETTINGS, newConf); this.localDatabase.closeReplication(); this.settings.suspendFileWatching = true; console.dir(newSettingW); const setupJustImport = "Just import setting"; const setupAsNew = "Set it up as secondary or subsequent device"; const setupAgain = "Reconfigure and reconstitute the data"; const setupManually = "Leave everything to me"; const setupType = await askSelectString(this.app, "How would you like to set it up?", [setupAsNew, setupAgain, setupJustImport, setupManually]); if (setupType == setupJustImport) { this.settings = newSettingW; await this.saveSettings(); } else if (setupType == setupAsNew) { this.settings = newSettingW; await this.saveSettings(); await this.resetLocalOldDatabase(); await this.resetLocalDatabase(); await this.localDatabase.initializeDatabase(); await this.markRemoteResolved(); await this.replicate(true); } else if (setupType == setupAgain) { const confirm = "I know this operation will rebuild all my databases with files on this device, and files that are on the remote database and I didn't synchronize to any other devices will be lost and want to proceed indeed."; if (await askSelectString(this.app, "Do you really want to do this?", ["Cancel", confirm]) != confirm) { return; } await this.saveSettings(); await this.resetLocalOldDatabase(); await this.resetLocalDatabase(); await this.localDatabase.initializeDatabase(); await this.initializeDatabase(true); await this.tryResetRemoteDatabase(); await this.markRemoteLocked(); await this.markRemoteResolved(); await this.replicate(true); } else if (setupType == setupManually) { const keepLocalDB = await askYesNo(this.app, "Keep local DB?"); const keepRemoteDB = await askYesNo(this.app, "Keep remote DB?"); if (keepLocalDB == "yes" && keepRemoteDB == "yes") { this.settings = newSettingW; await this.saveSettings(); const replicate = await askYesNo(this.app, "Unlock and replicate?"); if (replicate == "yes") { await this.replicate(true); await this.markRemoteUnlocked(); } Logger("Configuration loaded.", LOG_LEVEL.NOTICE); return; } if (keepLocalDB == "no" && keepRemoteDB == "no") { const reset = await askYesNo(this.app, "Drop everything?"); if (reset != "yes") { Logger("Cancelled", LOG_LEVEL.NOTICE); this.settings = oldConf; return; } } let initDB; this.settings = newSettingW; await this.saveSettings(); if (keepLocalDB == "no") { this.resetLocalOldDatabase(); this.resetLocalDatabase(); this.localDatabase.initializeDatabase(); const rebuild = await askYesNo(this.app, "Rebuild the database?"); if (rebuild == "yes") { initDB = this.initializeDatabase(true); } else { this.markRemoteResolved(); } } if (keepRemoteDB == "no") { await this.tryResetRemoteDatabase(); await this.markRemoteLocked(); } if (keepLocalDB == "no" || keepRemoteDB == "no") { const replicate = await askYesNo(this.app, "Replicate once?"); if (replicate == "yes") { if (initDB != null) { await initDB; } await this.replicate(true); } } } } Logger("Configuration loaded.", LOG_LEVEL.NOTICE); } else { Logger("Cancelled.", LOG_LEVEL.NOTICE); } } catch (ex) { Logger("Couldn't parse or decrypt configuration uri.", LOG_LEVEL.NOTICE); } }; this.registerObsidianProtocolHandler("setuplivesync", async (conf) => { await setupWizard(conf.settings); }); this.addCommand({ id: "livesync-replicate", name: "Replicate now", callback: async () => { await this.replicate(); } }); this.addCommand({ id: "livesync-dump", name: "Dump information of this doc ", editorCallback: (editor, view) => { this.localDatabase.getDBEntry(view.file.path, {}, true, false); } }); this.addCommand({ id: "livesync-checkdoc-conflicted", name: "Resolve if conflicted.", editorCallback: async (editor, view) => { await this.showIfConflicted(view.file.path); } }); this.addCommand({ id: "livesync-toggle", name: "Toggle LiveSync", callback: async () => { if (this.settings.liveSync) { this.settings.liveSync = false; Logger("LiveSync Disabled.", LOG_LEVEL.NOTICE); } else { this.settings.liveSync = true; Logger("LiveSync Enabled.", LOG_LEVEL.NOTICE); } await this.realizeSettingSyncMode(); this.saveSettings(); } }); this.addCommand({ id: "livesync-suspendall", name: "Toggle All Sync.", callback: async () => { if (this.suspended) { this.suspended = false; Logger("Self-hosted LiveSync resumed", LOG_LEVEL.NOTICE); } else { this.suspended = true; Logger("Self-hosted LiveSync suspended", LOG_LEVEL.NOTICE); } await this.realizeSettingSyncMode(); this.saveSettings(); } }); this.addCommand({ id: "livesync-history", name: "Show history", editorCallback: (editor, view) => { this.showHistory(view.file); } }); this.addCommand({ id: "livesync-scan-files", name: "Scan storage and database again", callback: async () => { await this.syncAllFiles(true); } }); this.triggerRealizeSettingSyncMode = (0, import_obsidian8.debounce)(this.triggerRealizeSettingSyncMode.bind(this), 1e3); this.triggerCheckPluginUpdate = (0, import_obsidian8.debounce)(this.triggerCheckPluginUpdate.bind(this), 3e3); setLockNotifier(() => { this.refreshStatusText(); }); this.addCommand({ id: "livesync-plugin-dialog", name: "Show Plugins and their settings", callback: () => { this.showPluginSyncModal(); } }); this.addCommand({ id: "livesync-scaninternal", name: "Sync hidden files", callback: () => { this.syncInternalFilesAndDatabase("safe", true); } }); this.addCommand({ id: "livesync-filehistory", name: "Pick a file to show history", callback: () => { this.fileHistory(); } }); this.addCommand({ id: "livesync-conflictcheck", name: "Pick a file to resolve conflict", callback: () => { this.pickFileForResolve(); } }); this.addCommand({ id: "livesync-runbatch", name: "Run pended batch processes", callback: async () => { await this.applyBatchChange(); } }); } showPluginSyncModal() { if (this.pluginDialog != null) { this.pluginDialog.open(); } else { this.pluginDialog = new PluginDialogModal(this.app, this); this.pluginDialog.open(); } } hidePluginSyncModal() { if (this.pluginDialog != null) { this.pluginDialog.close(); this.pluginDialog = null; } } onunload() { this.hidePluginSyncModal(); if (this.localDatabase != null) { this.localDatabase.onunload(); } if (this.gcTimerHandler != null) { clearTimeout(this.gcTimerHandler); this.gcTimerHandler = null; } this.clearPeriodicSync(); this.clearPluginSweep(); this.clearInternalFileScan(); if (this.localDatabase != null) { this.localDatabase.closeReplication(); this.localDatabase.close(); } clearAllPeriodic(); clearAllTriggers(); window.removeEventListener("visibilitychange", this.watchWindowVisibility); window.removeEventListener("online", this.watchOnline); Logger("unloading plugin"); } async openDatabase() { if (this.localDatabase != null) { this.localDatabase.close(); } const vaultName = this.getVaultName(); Logger("Open Database..."); const isMobile = this.app.isMobile; this.localDatabase = new LocalPouchDB(this.settings, vaultName, isMobile); this.localDatabase.updateInfo = () => { this.refreshStatusText(); }; return await this.localDatabase.initializeDatabase(); } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); this.settings.workingEncrypt = this.settings.encrypt; this.settings.workingPassphrase = this.settings.passphrase; this.settings.disableRequestURI = true; this.settings.gcDelay = 0; this.settings.useHistory = true; const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName(); if (this.settings.deviceAndVaultName != "") { if (!localStorage.getItem(lsKey)) { this.deviceAndVaultName = this.settings.deviceAndVaultName; localStorage.setItem(lsKey, this.deviceAndVaultName); this.settings.deviceAndVaultName = ""; } } if (isCloudantURI(this.settings.couchDB_URI) && this.settings.customChunkSize != 0) { Logger("Configuration verification founds problems with your configuration. This has been fixed automatically. But you may already have data that cannot be synchronised. If this is the case, please rebuild everything.", LOG_LEVEL.NOTICE); this.settings.customChunkSize = 0; } this.deviceAndVaultName = localStorage.getItem(lsKey) || ""; } triggerRealizeSettingSyncMode() { (async () => await this.realizeSettingSyncMode())(); } async saveSettings() { const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName(); localStorage.setItem(lsKey, this.deviceAndVaultName || ""); await this.saveData(this.settings); this.localDatabase.settings = this.settings; this.triggerRealizeSettingSyncMode(); } registerFileWatchEvents() { this.registerEvent(this.app.vault.on("modify", this.watchVaultChange)); this.registerEvent(this.app.vault.on("delete", this.watchVaultDelete)); this.registerEvent(this.app.vault.on("rename", this.watchVaultRename)); this.registerEvent(this.app.vault.on("create", this.watchVaultCreate)); this.registerEvent(this.app.vault.on("raw", this.watchVaultRawEvents)); } registerWatchEvents() { this.registerEvent(this.app.workspace.on("file-open", this.watchWorkspaceOpen)); window.addEventListener("visibilitychange", this.watchWindowVisibility); window.addEventListener("online", this.watchOnline); } watchOnline() { this.watchOnlineAsync(); } async watchOnlineAsync() { if (navigator.onLine && this.localDatabase.needScanning) { this.localDatabase.needScanning = false; await this.syncAllFiles(); } } watchWindowVisibility() { this.watchWindowVisibilityAsync(); } async watchWindowVisibilityAsync() { if (this.settings.suspendFileWatching) return; if (!this.isReady) return; const isHidden = document.hidden; await this.applyBatchChange(); if (isHidden) { this.localDatabase.closeReplication(); this.clearPeriodicSync(); } else { if (this.suspended) return; if (this.settings.autoSweepPlugins) { await this.sweepPlugin(false); } if (this.settings.liveSync) { this.localDatabase.openReplication(this.settings, true, false, this.parseReplicationResult); } if (this.settings.syncOnStart) { this.localDatabase.openReplication(this.settings, false, false, this.parseReplicationResult); } if (this.settings.periodicReplication) { this.setPeriodicSync(); } } } async appendWatchEvent(type, file, oldPath, ctx) { if (file instanceof import_obsidian8.TFile && !this.isTargetFile(file)) return; if (this.settings.suspendFileWatching) return; let cache; if (file instanceof import_obsidian8.TFile && (type == "CREATE" || type == "CHANGED")) { if (recentlyTouched(file)) { return; } if (!isPlainText(file.name)) { cache = await this.app.vault.readBinary(file); } else { cache = await this.app.vault.cachedRead(file); if (!cache) cache = await this.app.vault.read(file); } } if (this.settings.batchSave) { let i2 = this.watchedFileEventQueue.length; while (i2 >= 0) { i2--; if (i2 < 0) break; if (this.watchedFileEventQueue[i2].args.file.path != file.path) { continue; } if (this.watchedFileEventQueue[i2].type != type) break; this.watchedFileEventQueue.remove(this.watchedFileEventQueue[i2]); } } this.watchedFileEventQueue.push({ type, args: { file, oldPath, cache, ctx } }); this.refreshStatusText(); if (this.isReady) { await this.procFileEvent(); } } async procFileEvent(applyBatch) { if (!this.isReady) return; if (this.settings.batchSave) { if (!applyBatch && this.watchedFileEventQueue.length < FileWatchEventQueueMax) { setTrigger("applyBatchAuto", 3e4, () => { this.procFileEvent(true); }); return; } } clearTrigger("applyBatchAuto"); const ret = await runWithLock("procFiles", true, async () => { do { const procs = [...this.watchedFileEventQueue]; this.watchedFileEventQueue = []; for (const queue of procs) { const file = queue.args.file; const key = `file-last-proc-${queue.type}-${file.path}`; const last = Number(await this.localDatabase.kvDB.get(key) || 0); if (file instanceof import_obsidian8.TFile && file.stat.mtime == last) { Logger(`File has been already scanned on ${queue.type}, skip: ${file.path}`, LOG_LEVEL.VERBOSE); continue; } const cache = queue.args.cache; if ((queue.type == "CREATE" || queue.type == "CHANGED") && file instanceof import_obsidian8.TFile) { await this.updateIntoDB(file, false, cache); } if (queue.type == "DELETE") { if (file instanceof import_obsidian8.TFile) { await this.deleteFromDB(file); } else if (file instanceof import_obsidian8.TFolder) { await this.deleteFolderOnDB(file); } } if (queue.type == "RENAME") { if (file instanceof import_obsidian8.TFile) { await this.watchVaultRenameAsync(file, queue.args.oldPath); } } if (queue.type == "INTERNAL") { await this.watchVaultRawEventsAsync(file.path); } if (file instanceof import_obsidian8.TFile) { await this.localDatabase.kvDB.set(key, file.stat.mtime); } } this.refreshStatusText(); } while (this.watchedFileEventQueue.length != 0); return true; }); this.refreshStatusText(); return ret; } watchVaultCreate(file, ctx) { this.appendWatchEvent("CREATE", file, null, ctx); } watchVaultChange(file, ctx) { this.appendWatchEvent("CHANGED", file, null, ctx); } watchVaultDelete(file, ctx) { this.appendWatchEvent("DELETE", file, null, ctx); } watchVaultRename(file, oldFile, ctx) { this.appendWatchEvent("RENAME", file, oldFile, ctx); } watchWorkspaceOpen(file) { if (this.settings.suspendFileWatching) return; if (!this.isReady) return; this.watchWorkspaceOpenAsync(file); } async watchWorkspaceOpenAsync(file) { if (this.settings.suspendFileWatching) return; if (!this.isReady) return; await this.applyBatchChange(); if (file == null) { return; } if (this.settings.syncOnFileOpen && !this.suspended) { await this.replicate(); } await this.showIfConflicted(file.path); } async applyBatchChange() { if (this.settings.batchSave) { return await this.procFileEvent(true); } } watchVaultRawEvents(path) { if (!this.settings.syncInternalFiles) return; if (!this.settings.watchInternalFileChanges) return; if (!path.startsWith(this.app.vault.configDir)) return; const ignorePatterns = this.settings.syncInternalFilesIgnorePatterns.toLocaleLowerCase().replace(/\n| /g, "").split(",").filter((e3) => e3).map((e3) => new RegExp(e3)); if (ignorePatterns.some((e3) => path.match(e3))) return; this.appendWatchEvent("INTERNAL", { path, mtime: 0, ctime: 0, size: 0 }, "", null); } async watchVaultRawEventsAsync(path) { const stat = await this.app.vault.adapter.stat(path); if (stat && stat.type != "file") return; const storageMTime = ~~((stat && stat.mtime || 0) / 1e3); const key = `${path}-${storageMTime}`; if (this.recentProcessedInternalFiles.contains(key)) { return; } this.recentProcessedInternalFiles = [key, ...this.recentProcessedInternalFiles].slice(0, 100); const id = filename2idInternalChunk(path); const filesOnDB = await this.localDatabase.getDBEntryMeta(id); const dbMTime = ~~((filesOnDB && filesOnDB.mtime || 0) / 1e3); if (dbMTime == storageMTime) { return; } if (storageMTime == 0) { await this.deleteInternalFileOnDatabase(path); } else { await this.storeInternalFileToDatabase({ path, ...stat }); } } GetAllFilesRecursively(file) { if (file instanceof import_obsidian8.TFile) { return [file]; } else if (file instanceof import_obsidian8.TFolder) { const result = []; for (const v of file.children) { result.push(...this.GetAllFilesRecursively(v)); } return result; } else { Logger(`Filetype error:${file.path}`, LOG_LEVEL.NOTICE); throw new Error(`Filetype error:${file.path}`); } } getFilePath(file) { if (file instanceof import_obsidian8.TFolder) { if (file.isRoot()) return ""; return this.getFilePath(file.parent) + "/" + file.name; } if (file instanceof import_obsidian8.TFile) { return this.getFilePath(file.parent) + "/" + file.name; } return this.getFilePath(file.parent) + "/" + file.name; } async watchVaultRenameAsync(file, oldFile, cache) { Logger(`${oldFile} renamed to ${file.path}`, LOG_LEVEL.VERBOSE); if (file instanceof import_obsidian8.TFolder) { const newFiles = this.GetAllFilesRecursively(file); for (const i2 of newFiles) { try { const newFilePath = (0, import_obsidian8.normalizePath)(this.getFilePath(i2)); const newFile = getAbstractFileByPath(newFilePath); if (newFile instanceof import_obsidian8.TFile) { Logger(`save ${newFile.path} into db`); await this.updateIntoDB(newFile); } } catch (ex) { Logger(ex); } } Logger(`delete below ${oldFile} from db`); await this.deleteFromDBbyPath(oldFile); } else if (file instanceof import_obsidian8.TFile) { try { Logger(`file save ${file.path} into db`); await this.updateIntoDB(file, false, cache); Logger(`deleted ${oldFile} from db`); await this.deleteFromDBbyPath(oldFile); } catch (ex) { Logger(ex); } } } async addLog(message, level = LOG_LEVEL.INFO, key = "") { var _a; if (level == LOG_LEVEL.DEBUG && !isDebug) { return; } if (level < LOG_LEVEL.INFO && this.settings && this.settings.lessInformationInLog) { return; } if (this.settings && !this.settings.showVerboseLog && level == LOG_LEVEL.VERBOSE) { return; } const vaultName = this.getVaultName(); const timestamp = new Date().toLocaleString(); const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2); const newMessage = timestamp + "->" + messageContent; this.logMessage = [].concat(this.logMessage).concat([newMessage]).slice(-100); console.log(vaultName + ":" + newMessage); this.setStatusBarText(null, messageContent.substring(0, 30)); if (level >= LOG_LEVEL.NOTICE) { if (!key) key = messageContent; if (key in this.notifies) { const isShown = (_a = this.notifies[key].notice.noticeEl) == null ? void 0 : _a.isShown(); if (!isShown) { this.notifies[key].notice = new import_obsidian8.Notice(messageContent, 0); } clearTimeout(this.notifies[key].timer); if (key == messageContent) { this.notifies[key].count++; this.notifies[key].notice.setMessage(`(${this.notifies[key].count}):${messageContent}`); } else { this.notifies[key].notice.setMessage(`${messageContent}`); } this.notifies[key].timer = setTimeout(() => { const notify = this.notifies[key].notice; delete this.notifies[key]; try { notify.hide(); } catch (ex) { } }, 5e3); } else { const notify = new import_obsidian8.Notice(messageContent, 0); this.notifies[key] = { count: 0, notice: notify, timer: setTimeout(() => { delete this.notifies[key]; notify.hide(); }, 5e3) }; } } if (this.addLogHook != null) this.addLogHook(); } async ensureDirectory(fullPath) { const pathElements = fullPath.split("/"); pathElements.pop(); let c = ""; for (const v of pathElements) { c += v; try { await this.app.vault.createFolder(c); } catch (ex) { if (ex.message && ex.message == "Folder already exists.") { } else { Logger("Folder Create Error"); Logger(ex); } } c += "/"; } } async doc2storage_create(docEntry, force) { const pathSrc = id2path(docEntry._id); if (shouldBeIgnored(pathSrc)) { return; } if (!this.isTargetFile(pathSrc)) return; const doc = await this.localDatabase.getDBEntry(pathSrc, { rev: docEntry._rev }); if (doc === false) return; const msg = `DB -> STORAGE (create${force ? ",force" : ""},${doc.datatype}) `; const path = id2path(doc._id); if (doc.datatype == "newnote") { const bin = base64ToArrayBuffer(doc.data); if (bin != null) { if (!isValidPath(path)) { Logger(msg + "ERROR, invalid path: " + path, LOG_LEVEL.NOTICE); return; } await this.ensureDirectory(path); try { const newFile = await this.app.vault.createBinary((0, import_obsidian8.normalizePath)(path), bin, { ctime: doc.ctime, mtime: doc.mtime }); Logger(msg + path); touch(newFile); this.app.vault.trigger("create", newFile); } catch (ex) { Logger(msg + "ERROR, Could not write: " + path, LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.VERBOSE); } } } else if (doc.datatype == "plain") { if (!isValidPath(path)) { Logger(msg + "ERROR, invalid path: " + path, LOG_LEVEL.NOTICE); return; } await this.ensureDirectory(path); try { const newFile = await this.app.vault.create((0, import_obsidian8.normalizePath)(path), doc.data, { ctime: doc.ctime, mtime: doc.mtime }); Logger(msg + path); touch(newFile); this.app.vault.trigger("create", newFile); } catch (ex) { Logger(msg + "ERROR, Could not create: " + path + "(" + doc.datatype + ")", LOG_LEVEL.NOTICE); Logger(ex, LOG_LEVEL.VERBOSE); } } else { Logger(msg + "ERROR, Could not parse: " + path + "(" + doc.datatype + ")", LOG_LEVEL.NOTICE); } } async deleteVaultItem(file) { if (file instanceof import_obsidian8.TFile) { if (!this.isTargetFile(file)) return; } const dir = file.parent; if (this.settings.trashInsteadDelete) { await this.app.vault.trash(file, false); } else { await this.app.vault.delete(file); } Logger(`deleted:${file.path}`); Logger(`other items:${dir.children.length}`); if (dir.children.length == 0) { if (!this.settings.doNotDeleteFolder) { Logger(`all files deleted by replication, so delete dir`); await this.deleteVaultItem(dir); } } } async doc2storage_modify(docEntry, file, force) { const pathSrc = id2path(docEntry._id); if (shouldBeIgnored(pathSrc)) { return; } if (!this.isTargetFile(pathSrc)) return; if (docEntry._deleted || docEntry.deleted) { const lastDocs = await this.localDatabase.getDBEntry(pathSrc); if (lastDocs === false) { await this.deleteVaultItem(file); } else { await this.pullFile(pathSrc, null, true); Logger(`delete skipped:${lastDocs._id}`, LOG_LEVEL.VERBOSE); } return; } const localMtime = ~~(file.stat.mtime / 1e3); const docMtime = ~~(docEntry.mtime / 1e3); if (localMtime < docMtime || force) { const doc = await this.localDatabase.getDBEntry(pathSrc); if (doc === false) return; const msg = `DB -> STORAGE (modify${force ? ",force" : ""},${doc.datatype}) `; const path = id2path(doc._id); if (doc.datatype == "newnote") { const bin = base64ToArrayBuffer(doc.data); if (bin != null) { if (!isValidPath(path)) { Logger(msg + "ERROR, invalid path: " + path, LOG_LEVEL.NOTICE); return; } await this.ensureDirectory(path); try { await this.app.vault.modifyBinary(file, bin, { ctime: doc.ctime, mtime: doc.mtime }); Logger(msg + path); const xf = getAbstractFileByPath(file.path); touch(xf); this.app.vault.trigger("modify", xf); } catch (ex) { Logger(msg + "ERROR, Could not write: " + path, LOG_LEVEL.NOTICE); } } } else if (doc.datatype == "plain") { if (!isValidPath(path)) { Logger(msg + "ERROR, invalid path: " + path, LOG_LEVEL.NOTICE); return; } await this.ensureDirectory(path); try { await this.app.vault.modify(file, doc.data, { ctime: doc.ctime, mtime: doc.mtime }); Logger(msg + path); const xf = getAbstractFileByPath(file.path); touch(xf); this.app.vault.trigger("modify", xf); } catch (ex) { Logger(msg + "ERROR, Could not write: " + path, LOG_LEVEL.NOTICE); } } else { Logger(msg + "ERROR, Could not parse: " + path + "(" + doc.datatype + ")", LOG_LEVEL.NOTICE); } } else if (localMtime > docMtime) { } else { } } handleDBChanged(change) { this.queuedEntries.remove(this.queuedEntries.find((e3) => e3._id == change._id)); const af = app.workspace.getActiveFile(); if (af && af.path == id2path(change._id)) { return this.handleDBChangedAsync(change); } this.queuedEntries.push(change); if (this.queuedEntries.length > 50) { clearTrigger("dbchanged"); this.execDBchanged(); } setTrigger("dbchanged", 500, () => this.execDBchanged()); } async execDBchanged() { await runWithLock("dbchanged", false, async () => { const w = [...this.queuedEntries]; this.queuedEntries = []; Logger(`Applying ${w.length} files`); for (const entry of w) { Logger(`Applying ${entry._id} (${entry._rev}) change...`, LOG_LEVEL.VERBOSE); await this.handleDBChangedAsync(entry); Logger(`Applied ${entry._id} (${entry._rev}) change...`); } }); this.refreshStatusText(); } async handleDBChangedAsync(change) { const targetFile = getAbstractFileByPath(id2path(change._id)); if (targetFile == null) { if (change._deleted || change.deleted) { return; } const doc = change; await this.doc2storage_create(doc); } else if (targetFile instanceof import_obsidian8.TFile) { const doc = change; const file = targetFile; await this.doc2storage_modify(doc, file); if (!this.settings.checkConflictOnlyOnOpen) { this.queueConflictedCheck(file); } else { const af = app.workspace.getActiveFile(); if (af && af.path == file.path) { this.queueConflictedCheck(file); } } } else { Logger(`${id2path(change._id)} is already exist as the folder`); } } saveQueuedFiles() { const saveData = JSON.stringify(this.queuedFiles.filter((e3) => !e3.done).map((e3) => e3.entry._id)); const lsKey = "obsidian-livesync-queuefiles-" + this.getVaultName(); localStorage.setItem(lsKey, saveData); } async loadQueuedFiles() { const lsKey = "obsidian-livesync-queuefiles-" + this.getVaultName(); const ids = JSON.parse(localStorage.getItem(lsKey) || "[]"); const ret = await this.localDatabase.localDatabase.allDocs({ keys: ids, include_docs: true }); for (const doc of ret.rows) { if (doc.doc && !this.queuedFiles.some((e3) => e3.entry._id == doc.doc._id)) { await this.parseIncomingDoc(doc.doc); } } } async execInternalFile() { await runWithLock("execinternal", false, async () => { const w = [...this.procInternalFiles]; this.procInternalFiles = []; Logger(`Applying hidden ${w.length} files change...`); await this.syncInternalFilesAndDatabase("pull", false, false, w); Logger(`Applying hidden ${w.length} files changed`); }); this.refreshStatusText(); } procInternalFile(filename) { this.procInternalFiles.push(filename); setTrigger("procInternal", 500, async () => { await this.execInternalFile(); }); } procQueuedFiles() { this.saveQueuedFiles(); for (const queue of this.queuedFiles) { if (queue.done) continue; const now = new Date().getTime(); if (queue.missingChildren.length == 0) { queue.done = true; if (isInternalChunk(queue.entry._id)) { const filename = id2path(id2filenameInternalChunk(queue.entry._id)); this.procInternalFile(filename); } if (isValidPath(id2path(queue.entry._id))) { this.handleDBChanged(queue.entry); } } else if (now > queue.timeout) { if (!queue.warned) Logger(`Timed out: ${queue.entry._id} could not collect ${queue.missingChildren.length} chunks. plugin keeps watching, but you have to check the file after the replication.`, LOG_LEVEL.NOTICE); queue.warned = true; continue; } } this.queuedFiles = this.queuedFiles.filter((e3) => !e3.done); this.saveQueuedFiles(); } parseIncomingChunk(chunk) { const now = new Date().getTime(); let isNewFileCompleted = false; for (const queue of this.queuedFiles) { if (queue.done) continue; if (queue.missingChildren.indexOf(chunk._id) !== -1) { queue.missingChildren = queue.missingChildren.filter((e3) => e3 != chunk._id); queue.timeout = now + this.chunkWaitTimeout; } if (queue.missingChildren.length == 0) { for (const e3 of this.queuedFiles) { if (e3.entry._id == queue.entry._id && e3.entry.mtime < queue.entry.mtime) { e3.done = true; } } isNewFileCompleted = true; } } if (isNewFileCompleted) this.procQueuedFiles(); } async parseIncomingDoc(doc) { if (!this.isTargetFile(id2path(doc._id))) return; const skipOldFile = this.settings.skipOlderFilesOnSync && false; if (!isInternalChunk(doc._id) && skipOldFile) { const info = getAbstractFileByPath(id2path(doc._id)); if (info && info instanceof import_obsidian8.TFile) { const localMtime = ~~(info.stat.mtime / 1e3); const docMtime = ~~(doc.mtime / 1e3); if (localMtime >= docMtime) { Logger(`${doc._id} Skipped, older than storage.`, LOG_LEVEL.VERBOSE); return; } } } const now = new Date().getTime(); const newQueue = { entry: doc, missingChildren: [], timeout: now + this.chunkWaitTimeout }; if (!this.settings.readChunksOnline && "children" in doc) { const c = await this.localDatabase.localDatabase.allDocs({ keys: doc.children, include_docs: false }); const missing = c.rows.filter((e3) => "error" in e3).map((e3) => e3.key); if (missing.length > 0) Logger(`${doc._id}(${doc._rev}) Queued (waiting ${missing.length} items)`, LOG_LEVEL.VERBOSE); newQueue.missingChildren = missing; this.queuedFiles.push(newQueue); } else { this.queuedFiles.push(newQueue); } this.saveQueuedFiles(); this.procQueuedFiles(); } async parseReplicationResult(docs) { this.refreshStatusText(); for (const change of docs) { if (isPluginChunk(change._id)) { if (this.settings.notifyPluginOrSettingUpdated) { this.triggerCheckPluginUpdate(); } continue; } if (isChunk(change._id)) { await this.parseIncomingChunk(change); continue; } if (change._id == SYNCINFO_ID) { continue; } if (change.type != "leaf" && change.type != "versioninfo" && change.type != "milestoneinfo" && change.type != "nodeinfo") { await this.parseIncomingDoc(change); continue; } if (change.type == "versioninfo") { if (change.version > VER) { this.localDatabase.closeReplication(); Logger(`Remote database updated to incompatible version. update your self-hosted-livesync plugin.`, LOG_LEVEL.NOTICE); } } } } triggerCheckPluginUpdate() { (async () => await this.checkPluginUpdate())(); } async checkPluginUpdate() { var _a, _b; if (!this.settings.usePluginSync) return; await this.sweepPlugin(false); const { allPlugins, thisDevicePlugins } = await this.getPluginList(); const arrPlugins = Object.values(allPlugins); let updateFound = false; for (const plugin of arrPlugins) { const ownPlugin = thisDevicePlugins[plugin.manifest.id]; if (ownPlugin) { const remoteVersion = versionNumberString2Number(plugin.manifest.version); const ownVersion = versionNumberString2Number(ownPlugin.manifest.version); if (remoteVersion > ownVersion) { updateFound = true; } if ((plugin.mtime / 1e3 | 0) > (ownPlugin.mtime / 1e3 | 0) && ((_a = plugin.dataJson) != null ? _a : "") != ((_b = ownPlugin.dataJson) != null ? _b : "")) { updateFound = true; } } } if (updateFound) { const fragment = createFragment((doc) => { doc.createEl("a", null, (a) => { a.text = "There're some new plugins or their settings"; a.addEventListener("click", () => this.showPluginSyncModal()); }); }); NewNotice(fragment, 1e4); } else { Logger("Everything is up to date.", LOG_LEVEL.NOTICE); } } clearPeriodicSync() { if (this.periodicSyncHandler != null) { clearInterval(this.periodicSyncHandler); this.periodicSyncHandler = null; } } setPeriodicSync() { if (this.settings.periodicReplication && this.settings.periodicReplicationInterval > 0) { this.clearPeriodicSync(); this.periodicSyncHandler = this.setInterval(async () => await this.periodicSync(), Math.max(this.settings.periodicReplicationInterval, 30) * 1e3); } } async periodicSync() { await this.replicate(); } clearPluginSweep() { if (this.periodicPluginSweepHandler != null) { clearInterval(this.periodicPluginSweepHandler); this.periodicPluginSweepHandler = null; } } setPluginSweep() { if (this.settings.autoSweepPluginsPeriodic) { this.clearPluginSweep(); this.periodicPluginSweepHandler = this.setInterval(async () => await this.periodicPluginSweep(), PERIODIC_PLUGIN_SWEEP * 1e3); } } async periodicPluginSweep() { await this.sweepPlugin(false); } async realizeSettingSyncMode() { this.localDatabase.closeReplication(); this.clearPeriodicSync(); this.clearPluginSweep(); this.clearInternalFileScan(); await this.applyBatchChange(); if (this.suspended) return; if (this.settings.autoSweepPlugins) { await this.sweepPlugin(false); } if (this.settings.liveSync) { this.localDatabase.openReplication(this.settings, true, false, this.parseReplicationResult); this.refreshStatusText(); } if (this.settings.syncInternalFiles) { await this.syncInternalFilesAndDatabase("safe", false); } this.setPeriodicSync(); this.setPluginSweep(); this.setPeriodicInternalFileScan(); } refreshStatusText() { const sent = this.localDatabase.docSent; const arrived = this.localDatabase.docArrived; let w = ""; switch (this.localDatabase.syncStatus) { case "CLOSED": case "COMPLETED": case "NOT_CONNECTED": w = "\u23F9"; break; case "STARTED": w = "\u{1F300}"; break; case "PAUSED": w = "\u{1F4A4}"; break; case "CONNECTED": w = "\u26A1"; break; case "ERRORED": w = "\u26A0"; break; default: w = "?"; } this.statusBar.title = this.localDatabase.syncStatus; let waiting = ""; if (this.settings.batchSave) { waiting = " " + this.watchedFileEventQueue.map((e3) => "\u{1F6EB}").join(""); waiting = waiting.replace(/(🛫){10}/g, "\u{1F680}"); } let queued = ""; const queue = Object.entries(this.queuedFiles).filter((e3) => !e3[1].warned); const queuedCount = queue.length; if (queuedCount) { const pieces = queue.map((e3) => e3[1].missingChildren).reduce((prev, cur) => prev + cur.length, 0); queued = ` \u{1F9E9} ${queuedCount} (${pieces})`; } const processes = getProcessingCounts(); const processesDisp = processes == 0 ? "" : ` \u23F3${processes}`; const message = `Sync: ${w} \u2191${sent} \u2193${arrived}${waiting}${processesDisp}${queued}`; const locks = getLocks(); const pendingTask = locks.pending.length ? "\nPending: " + Object.entries(locks.pending.reduce((p, c) => { var _a; return { ...p, [c]: ((_a = p[c]) != null ? _a : 0) + 1 }; }, {})).map((e3) => `${e3[0]}${e3[1] == 1 ? "" : `(${e3[1]})`}`).join(", ") : ""; const runningTask = locks.running.length ? "\nRunning: " + Object.entries(locks.running.reduce((p, c) => { var _a; return { ...p, [c]: ((_a = p[c]) != null ? _a : 0) + 1 }; }, {})).map((e3) => `${e3[0]}${e3[1] == 1 ? "" : `(${e3[1]})`}`).join(", ") : ""; this.setStatusBarText(message + pendingTask + runningTask); } setStatusBarText(message = null, log = null) { if (!this.statusBar) return; const newMsg = typeof message == "string" ? message : this.lastMessage; const newLog = typeof log == "string" ? log : this.lastLog; if (`${this.lastMessage}-${this.lastLog}` != `${newMsg}-${newLog}`) { this.statusBar.setText(newMsg.split("\n")[0]); if (this.settings.showStatusOnEditor) { const root = activeDocument.documentElement; root.style.setProperty("--slsmessage", '"' + (newMsg + "\n" + newLog).split("\n").join("\\a ") + '"'); } else { const root = activeDocument.documentElement; root.style.setProperty("--slsmessage", '""'); } if (this.logHideTimer != null) { clearTimeout(this.logHideTimer); } this.logHideTimer = setTimeout(() => this.setStatusBarText(null, ""), 3e3); this.lastMessage = newMsg; this.lastLog = newLog; } } updateStatusBarText() { } async replicate(showMessage) { if (!this.isReady) return; if (this.settings.versionUpFlash != "") { Logger("Open settings and check message, please.", LOG_LEVEL.NOTICE); return; } await this.applyBatchChange(); if (this.settings.autoSweepPlugins) { await this.sweepPlugin(false); } await this.loadQueuedFiles(); if (this.settings.syncInternalFiles && this.settings.syncInternalFilesBeforeReplication && !this.settings.watchInternalFileChanges) { await this.syncInternalFilesAndDatabase("push", showMessage); } this.localDatabase.openReplication(this.settings, false, showMessage, this.parseReplicationResult); } async initializeDatabase(showingNotice) { this.isReady = false; if (await this.openDatabase()) { if (this.localDatabase.isReady) { await this.syncAllFiles(showingNotice); } this.isReady = true; await this.procFileEvent(true); return true; } else { this.isReady = false; return false; } } async replicateAllToServer(showingNotice) { if (!this.isReady) return false; if (this.settings.autoSweepPlugins) { await this.sweepPlugin(showingNotice); } return await this.localDatabase.replicateAllToServer(this.settings, showingNotice); } async markRemoteLocked() { return await this.localDatabase.markRemoteLocked(this.settings, true); } async markRemoteUnlocked() { return await this.localDatabase.markRemoteLocked(this.settings, false); } async markRemoteResolved() { return await this.localDatabase.markRemoteResolved(this.settings); } async syncAllFiles(showingNotice) { let initialScan = false; if (showingNotice) { Logger("Initializing", LOG_LEVEL.NOTICE, "syncAll"); } await this.collectDeletedFiles(); const filesStorage = this.app.vault.getFiles().filter((e3) => this.isTargetFile(e3)); const filesStorageName = filesStorage.map((e3) => e3.path); const wf = await this.localDatabase.localDatabase.allDocs(); const filesDatabase = wf.rows.filter((e3) => !isChunk(e3.id) && !isPluginChunk(e3.id) && e3.id != "obsydian_livesync_version" && e3.id != "_design/replicate").filter((e3) => isValidPath(e3.id)).map((e3) => id2path(e3.id)).filter((e3) => this.isTargetFile(e3)); const isInitialized = await this.localDatabase.kvDB.get("initialized") || false; if (filesDatabase.length == 0 && !isInitialized) { initialScan = true; Logger("Database looks empty, save files as initial sync data"); } const onlyInStorage = filesStorage.filter((e3) => filesDatabase.indexOf(e3.path) == -1); const onlyInDatabase = filesDatabase.filter((e3) => filesStorageName.indexOf(e3) == -1); const onlyInStorageNames = onlyInStorage.map((e3) => e3.path); const syncFiles = filesStorage.filter((e3) => onlyInStorageNames.indexOf(e3.path) == -1); Logger("Initialize and checking database files"); Logger("Updating database by new files"); this.setStatusBarText(`UPDATE DATABASE`); const runAll = async (procedureName, objects, callback) => { Logger(procedureName); const semaphore = Semaphore(10); if (!this.localDatabase.isReady) throw Error("Database is not ready!"); const processes = objects.map((e3) => (async (v) => { const releaser = await semaphore.acquire(1, procedureName); try { await callback(v); } catch (ex) { Logger(`Error while ${procedureName}`, LOG_LEVEL.NOTICE); Logger(ex); } finally { releaser(); } })(e3)); await Promise.all(processes); Logger(`${procedureName} done.`); }; await runAll("UPDATE DATABASE", onlyInStorage, async (e3) => { Logger(`Update into ${e3.path}`); await this.updateIntoDB(e3, initialScan); }); if (!initialScan) { await runAll("UPDATE STORAGE", onlyInDatabase, async (e3) => { const w = await this.localDatabase.getDBEntryMeta(e3, {}, true); if (w && !(w.deleted || w._deleted)) { Logger(`Check or pull from db:${e3}`); await this.pullFile(e3, filesStorage, false, null, false); Logger(`Check or pull from db:${e3} OK`); } else if (w) { Logger(`Deletion history skipped: ${e3}`, LOG_LEVEL.VERBOSE); } else { Logger(`entry not found: ${e3}`); } }); } if (!initialScan) { let caches = {}; caches = await this.localDatabase.kvDB.get("diff-caches") || {}; const docsCount = syncFiles.length; do { const syncFilesX = syncFiles.splice(0, 100); const docs = await this.localDatabase.localDatabase.allDocs({ keys: syncFilesX.map((e3) => path2id(e3.path)), include_docs: true }); const syncFilesToSync = syncFilesX.map((e3) => ({ file: e3, doc: docs.rows.find((ee) => ee.id == path2id(e3.path)).doc })); await runAll(`CHECK FILE STATUS:${syncFiles.length}/${docsCount}`, syncFilesToSync, async (e3) => { caches = await this.syncFileBetweenDBandStorage(e3.file, e3.doc, initialScan, caches); }); } while (syncFiles.length > 0); await this.localDatabase.kvDB.set("diff-caches", caches); } this.setStatusBarText(`NOW TRACKING!`); Logger("Initialized, NOW TRACKING!"); if (!isInitialized) { await this.localDatabase.kvDB.set("initialized", true); } if (showingNotice) { Logger("Initialize done!", LOG_LEVEL.NOTICE, "syncAll"); } } async deleteFolderOnDB(folder) { Logger(`delete folder:${folder.path}`); await this.localDatabase.deleteDBEntryPrefix(folder.path + "/"); for (const v of folder.children) { const entry = v; Logger(`->entry:${entry.path}`, LOG_LEVEL.VERBOSE); if (entry.children) { Logger(`->is dir`, LOG_LEVEL.VERBOSE); await this.deleteFolderOnDB(entry); try { if (this.settings.trashInsteadDelete) { await this.app.vault.trash(entry, false); } else { await this.app.vault.delete(entry); } } catch (ex) { if (ex.code && ex.code == "ENOENT") { } else { Logger(`error while delete folder:${entry.path}`, LOG_LEVEL.NOTICE); Logger(ex); } } } else { Logger(`->is file`, LOG_LEVEL.VERBOSE); await this.deleteFromDB(entry); } } try { if (this.settings.trashInsteadDelete) { await this.app.vault.trash(folder, false); } else { await this.app.vault.delete(folder); } } catch (ex) { if (ex.code && ex.code == "ENOENT") { } else { Logger(`error while delete folder:${folder.path}`, LOG_LEVEL.NOTICE); Logger(ex); } } } async getConflictedDoc(path, rev) { try { const doc = await this.localDatabase.getDBEntry(path, { rev }, false, false, true); if (doc === false) return false; let data = doc.data; if (doc.datatype == "newnote") { data = base64ToString(doc.data); } else if (doc.datatype == "plain") { data = doc.data; } return { deleted: doc.deleted || doc._deleted, ctime: doc.ctime, mtime: doc.mtime, rev, data }; } catch (ex) { if (ex.status && ex.status == 404) { return false; } } return false; } async getConflictedStatus(path) { const test = await this.localDatabase.getDBEntry(path, { conflicts: true }, false, false, true); if (test === false) return false; if (test == null) return false; if (!test._conflicts) return false; if (test._conflicts.length == 0) return false; const leftLeaf = await this.getConflictedDoc(path, test._rev); const rightLeaf = await this.getConflictedDoc(path, test._conflicts[0]); if (leftLeaf == false) { Logger(`could not get current revisions:${path}`, LOG_LEVEL.NOTICE); return false; } if (rightLeaf == false) { await this.localDatabase.deleteDBEntry(path, { rev: test._conflicts[0] }); await this.pullFile(path, null, true); Logger(`could not get old revisions, automatically used newer one:${path}`, LOG_LEVEL.NOTICE); return true; } if (leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted) { let leaf = leftLeaf; if (leftLeaf.mtime > rightLeaf.mtime) { leaf = rightLeaf; } await this.localDatabase.deleteDBEntry(path, { rev: leaf.rev }); await this.pullFile(path, null, true); Logger(`automatically merged:${path}`); return true; } if (this.settings.resolveConflictsByNewerFile) { const lMtime = ~~(leftLeaf.mtime / 1e3); const rMtime = ~~(rightLeaf.mtime / 1e3); let loser = leftLeaf; if (lMtime > rMtime) { loser = rightLeaf; } await this.localDatabase.deleteDBEntry(path, { rev: loser.rev }); await this.pullFile(path, null, true); Logger(`Automatically merged (newerFileResolve) :${path}`, LOG_LEVEL.NOTICE); return true; } const dmp = new import_diff_match_patch3.diff_match_patch(); const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data); dmp.diff_cleanupSemantic(diff); Logger(`conflict(s) found:${path}`); return { left: leftLeaf, right: rightLeaf, diff }; } showMergeDialog(filename, conflictCheckResult) { return new Promise((res, rej) => { Logger("open conflict dialog", LOG_LEVEL.VERBOSE); new ConflictResolveModal(this.app, conflictCheckResult, async (selected) => { const testDoc = await this.localDatabase.getDBEntry(filename, { conflicts: true }, false, false, true); if (testDoc === false) { Logger("Missing file..", LOG_LEVEL.VERBOSE); return res(true); } if (!testDoc._conflicts) { Logger("Nothing have to do with this conflict", LOG_LEVEL.VERBOSE); return res(true); } const toDelete = selected; const toKeep = conflictCheckResult.left.rev != toDelete ? conflictCheckResult.left.rev : conflictCheckResult.right.rev; if (toDelete == "") { const p = conflictCheckResult.diff.map((e3) => e3[1]).join(""); await this.localDatabase.deleteDBEntry(filename, { rev: conflictCheckResult.left.rev }); await this.localDatabase.deleteDBEntry(filename, { rev: conflictCheckResult.right.rev }); const file = getAbstractFileByPath(filename); if (file) { await this.app.vault.modify(file, p); await this.updateIntoDB(file); } else { const newFile = await this.app.vault.create(filename, p); await this.updateIntoDB(newFile); } await this.pullFile(filename); Logger("concat both file"); setTimeout(() => { this.showIfConflicted(filename); }, 500); } else if (toDelete == null) { Logger("Leave it still conflicted"); } else { Logger(`Conflict resolved:${filename}`); await this.localDatabase.deleteDBEntry(filename, { rev: toDelete }); await this.pullFile(filename, null, true, toKeep); setTimeout(() => { this.showIfConflicted(filename); }, 500); } return res(true); }).open(); }); } queueConflictedCheck(file) { this.conflictedCheckFiles = this.conflictedCheckFiles.filter((e3) => e3 != file.path); this.conflictedCheckFiles.push(file.path); if (this.conflictedCheckTimer != null) { window.clearTimeout(this.conflictedCheckTimer); } this.conflictedCheckTimer = window.setTimeout(async () => { this.conflictedCheckTimer = null; const checkFiles = JSON.parse(JSON.stringify(this.conflictedCheckFiles)); for (const filename of checkFiles) { try { const file2 = getAbstractFileByPath(filename); if (file2 != null && file2 instanceof import_obsidian8.TFile) { await this.showIfConflicted(file2.path); } } catch (ex) { Logger(ex); } } }, 1e3); } async showIfConflicted(filename) { await runWithLock("conflicted", false, async () => { const conflictCheckResult = await this.getConflictedStatus(filename); if (conflictCheckResult === false) { return; } if (conflictCheckResult === true) { Logger("conflict:Automatically merged, but we have to check it again"); setTimeout(() => { this.showIfConflicted(filename); }, 500); return; } await this.showMergeDialog(filename, conflictCheckResult); }); } async pullFile(filename, fileList, force, rev, waitForReady = true) { const targetFile = getAbstractFileByPath(id2path(filename)); if (!this.isTargetFile(id2path(filename))) return; if (targetFile == null) { const doc = await this.localDatabase.getDBEntry(filename, rev ? { rev } : null, false, waitForReady); if (doc === false) { Logger(`${filename} Skipped`); return; } await this.doc2storage_create(doc, force); } else if (targetFile instanceof import_obsidian8.TFile) { const file = targetFile; const doc = await this.localDatabase.getDBEntry(filename, rev ? { rev } : null, false, waitForReady); if (doc === false) { Logger(`${filename} Skipped`); return; } await this.doc2storage_modify(doc, file, force); } else { Logger(`target files:${filename} is exists as the folder`); } } async syncFileBetweenDBandStorage(file, doc, initialScan, caches) { if (!doc) { throw new Error(`Missing doc:${file.path}`); } if (!(file instanceof import_obsidian8.TFile) && "path" in file) { const w = getAbstractFileByPath(file.path); if (w instanceof import_obsidian8.TFile) { file = w; } else { throw new Error(`Missing file:${file.path}`); } } const storageMtime = ~~(file.stat.mtime / 1e3); const docMtime = ~~(doc.mtime / 1e3); const dK = `${file.path}-diff`; const isLastDiff = dK in caches ? caches[dK] : { storageMtime: 0, docMtime: 0 }; if (isLastDiff.docMtime == docMtime && isLastDiff.storageMtime == storageMtime) { caches[dK] = { storageMtime, docMtime }; return caches; } if (storageMtime > docMtime) { Logger("STORAGE -> DB :" + file.path); Logger(`${storageMtime} > ${docMtime}`); await this.updateIntoDB(file, initialScan); caches[dK] = { storageMtime, docMtime }; return caches; } else if (storageMtime < docMtime) { Logger("STORAGE <- DB :" + file.path); Logger(`${storageMtime} < ${docMtime}`); const docx = await this.localDatabase.getDBEntry(file.path, null, false, false); if (docx != false) { await this.doc2storage_modify(docx, file); } else { Logger("STORAGE <- DB :" + file.path + " Skipped"); } caches[dK] = { storageMtime, docMtime }; return caches; } else { } caches[dK] = { storageMtime, docMtime }; return caches; } async updateIntoDB(file, initialScan, cache) { if (!this.isTargetFile(file)) return; if (shouldBeIgnored(file.path)) { return; } let content = ""; let datatype = "newnote"; if (!cache) { if (!isPlainText(file.name)) { const contentBin = await this.app.vault.readBinary(file); content = await arrayBufferToBase64(contentBin); datatype = "newnote"; } else { content = await this.app.vault.read(file); datatype = "plain"; } } else { if (cache instanceof ArrayBuffer) { content = await arrayBufferToBase64(cache); datatype = "newnote"; } else { content = cache; datatype = "plain"; } } const fullPath = path2id(file.path); const d = { _id: fullPath, data: content, ctime: file.stat.ctime, mtime: file.stat.mtime, size: file.stat.size, children: [], datatype, type: datatype }; const msg = `DB <- STORAGE (${datatype}) `; const isNotChanged = await runWithLock("file:" + fullPath, false, async () => { if (recentlyTouched(file)) { return true; } const old = await this.localDatabase.getDBEntry(fullPath, null, false, false); if (old !== false) { const oldData = { data: old.data, deleted: old._deleted || old.deleted }; const newData = { data: d.data, deleted: d._deleted || d.deleted }; if (JSON.stringify(oldData) == JSON.stringify(newData)) { Logger(msg + "Skipped (not changed) " + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""), LOG_LEVEL.VERBOSE); return true; } } return false; }); if (isNotChanged) return; await this.localDatabase.putDBEntry(d, initialScan); this.queuedFiles = this.queuedFiles.map((e3) => ({ ...e3, ...e3.entry._id == d._id ? { done: true } : {} })); Logger(msg + fullPath); if (this.settings.syncOnSave && !this.suspended) { await this.replicate(); } } async deleteFromDB(file) { if (!this.isTargetFile(file)) return; const fullPath = file.path; Logger(`deleteDB By path:${fullPath}`); await this.deleteFromDBbyPath(fullPath); if (this.settings.syncOnSave && !this.suspended) { await this.replicate(); } } async deleteFromDBbyPath(fullPath) { await this.localDatabase.deleteDBEntry(fullPath); if (this.settings.syncOnSave && !this.suspended) { await this.replicate(); } } async resetLocalDatabase() { clearTouched(); await this.localDatabase.resetDatabase(); await this.localDatabase.resetLocalOldDatabase(); } async resetLocalOldDatabase() { clearTouched(); await this.localDatabase.resetLocalOldDatabase(); } async tryResetRemoteDatabase() { await this.localDatabase.tryResetRemoteDatabase(this.settings); } async tryCreateRemoteDatabase() { await this.localDatabase.tryCreateRemoteDatabase(this.settings); } async getPluginList() { const db = this.localDatabase.localDatabase; const docList = await db.allDocs({ startkey: PSCHeader, endkey: PSCHeaderEnd, include_docs: false }); const oldDocs = (await Promise.all(docList.rows.map(async (e3) => await this.localDatabase.getDBEntry(e3.id)))).filter((e3) => e3 !== false).map((e3) => JSON.parse(e3.data)); const plugins = {}; const allPlugins = {}; const thisDevicePlugins = {}; for (const v of oldDocs) { if (typeof plugins[v.deviceVaultName] === "undefined") { plugins[v.deviceVaultName] = []; } plugins[v.deviceVaultName].push(v); allPlugins[v._id] = v; if (v.deviceVaultName == this.deviceAndVaultName) { thisDevicePlugins[v.manifest.id] = v; } } return { plugins, allPlugins, thisDevicePlugins }; } async sweepPlugin(showMessage = false) { if (!this.settings.usePluginSync) return; if (!this.localDatabase.isReady) return; await runWithLock("sweepplugin", true, async () => { const logLevel = showMessage ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO; if (!this.deviceAndVaultName) { Logger("You have to set your device and vault name.", LOG_LEVEL.NOTICE); return; } Logger("Scanning plugins", logLevel); const db = this.localDatabase.localDatabase; const oldDocs = await db.allDocs({ startkey: `ps:${this.deviceAndVaultName}-`, endkey: `ps:${this.deviceAndVaultName}.`, include_docs: true }); const pl = this.app.plugins; const manifests = Object.values(pl.manifests); for (const m of manifests) { Logger(`Reading plugin:${m.name}(${m.id})`, LOG_LEVEL.VERBOSE); const path = (0, import_obsidian8.normalizePath)(m.dir) + "/"; const adapter = this.app.vault.adapter; const files = ["manifest.json", "main.js", "styles.css", "data.json"]; const pluginData = {}; for (const file of files) { const thePath = path + file; if (await adapter.exists(thePath)) { pluginData[file] = await adapter.read(thePath); } } let mtime = 0; if (await adapter.exists(path + "/data.json")) { mtime = (await adapter.stat(path + "/data.json")).mtime; } const p = { _id: `ps:${this.deviceAndVaultName}-${m.id}`, dataJson: pluginData["data.json"], deviceVaultName: this.deviceAndVaultName, mainJs: pluginData["main.js"], styleCss: pluginData["styles.css"], manifest: m, manifestJson: pluginData["manifest.json"], mtime, type: "plugin" }; const d = { _id: p._id, data: JSON.stringify(p), ctime: mtime, mtime, size: 0, children: [], datatype: "plain", type: "plain" }; Logger(`check diff:${m.name}(${m.id})`, LOG_LEVEL.VERBOSE); await runWithLock("plugin-" + m.id, false, async () => { const old = await this.localDatabase.getDBEntry(p._id, null, false, false); if (old !== false) { const oldData = { data: old.data, deleted: old._deleted }; const newData = { data: d.data, deleted: d._deleted }; if (JSON.stringify(oldData) == JSON.stringify(newData)) { oldDocs.rows = oldDocs.rows.filter((e3) => e3.id != d._id); Logger(`Nothing changed:${m.name}`); return; } } await this.localDatabase.putDBEntry(d); oldDocs.rows = oldDocs.rows.filter((e3) => e3.id != d._id); Logger(`Plugin saved:${m.name}`, logLevel); }); } Logger(`Deleting old plugins`, LOG_LEVEL.VERBOSE); const delDocs = oldDocs.rows.map((e3) => { if (e3.doc.type == "newnote" || e3.doc.type == "plain") { e3.doc.deleted = true; if (this.settings.deleteMetadataOfDeletedFiles) { e3.doc._deleted = true; } } else { e3.doc._deleted = true; } return e3.doc; }); await db.bulkDocs(delDocs); Logger(`Scan plugin done.`, logLevel); }); } async applyPluginData(plugin) { await runWithLock("plugin-" + plugin.manifest.id, false, async () => { const pluginTargetFolderPath = (0, import_obsidian8.normalizePath)(plugin.manifest.dir) + "/"; const adapter = this.app.vault.adapter; const stat = this.app.plugins.enabledPlugins.has(plugin.manifest.id) == true; if (stat) { await this.app.plugins.unloadPlugin(plugin.manifest.id); Logger(`Unload plugin:${plugin.manifest.id}`, LOG_LEVEL.NOTICE); } if (plugin.dataJson) await adapter.write(pluginTargetFolderPath + "data.json", plugin.dataJson); Logger("wrote:" + pluginTargetFolderPath + "data.json", LOG_LEVEL.NOTICE); if (stat) { await this.app.plugins.loadPlugin(plugin.manifest.id); Logger(`Load plugin:${plugin.manifest.id}`, LOG_LEVEL.NOTICE); } }); } async applyPlugin(plugin) { await runWithLock("plugin-" + plugin.manifest.id, false, async () => { const stat = this.app.plugins.enabledPlugins.has(plugin.manifest.id) == true; if (stat) { await this.app.plugins.unloadPlugin(plugin.manifest.id); Logger(`Unload plugin:${plugin.manifest.id}`, LOG_LEVEL.NOTICE); } const pluginTargetFolderPath = (0, import_obsidian8.normalizePath)(plugin.manifest.dir) + "/"; const adapter = this.app.vault.adapter; if (await adapter.exists(pluginTargetFolderPath) === false) { await adapter.mkdir(pluginTargetFolderPath); } await adapter.write(pluginTargetFolderPath + "main.js", plugin.mainJs); await adapter.write(pluginTargetFolderPath + "manifest.json", plugin.manifestJson); if (plugin.styleCss) await adapter.write(pluginTargetFolderPath + "styles.css", plugin.styleCss); if (stat) { await this.app.plugins.loadPlugin(plugin.manifest.id); Logger(`Load plugin:${plugin.manifest.id}`, LOG_LEVEL.NOTICE); } }); } clearInternalFileScan() { if (this.periodicInternalFileScanHandler != null) { clearInterval(this.periodicInternalFileScanHandler); this.periodicInternalFileScanHandler = null; } } setPeriodicInternalFileScan() { if (this.periodicInternalFileScanHandler != null) { this.clearInternalFileScan(); } if (this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval > 0 && !this.settings.watchInternalFileChanges) { this.periodicPluginSweepHandler = this.setInterval(async () => await this.periodicInternalFileScan(), this.settings.syncInternalFilesInterval * 1e3); } } async periodicInternalFileScan() { await this.syncInternalFilesAndDatabase("push", false); } async getFiles(path, ignoreList, filter, ignoreFilter) { const w = await this.app.vault.adapter.list(path); let files = [ ...w.files.filter((e3) => !ignoreList.some((ee) => e3.endsWith(ee))).filter((e3) => !filter || filter.some((ee) => e3.match(ee))).filter((e3) => !ignoreFilter || ignoreFilter.every((ee) => !e3.match(ee))) ]; L1: for (const v of w.folders) { for (const ignore of ignoreList) { if (v.endsWith(ignore)) { continue L1; } } if (ignoreFilter && ignoreFilter.some((e3) => v.match(e3))) { continue L1; } files = files.concat(await this.getFiles(v, ignoreList, filter, ignoreFilter)); } return files; } async scanInternalFiles() { const ignoreFilter = this.settings.syncInternalFilesIgnorePatterns.toLocaleLowerCase().replace(/\n| /g, "").split(",").filter((e3) => e3).map((e3) => new RegExp(e3)); const root = this.app.vault.getRoot(); const findRoot = root.path; const filenames = (await this.getFiles(findRoot, [], null, ignoreFilter)).filter((e3) => e3.startsWith(".")).filter((e3) => !e3.startsWith(".trash")); const files = filenames.map(async (e3) => { return { path: e3, stat: await this.app.vault.adapter.stat(e3) }; }); const result = []; for (const f of files) { const w = await f; result.push({ ...w, ...w.stat }); } return result; } async storeInternalFileToDatabase(file, forceWrite = false) { const id = filename2idInternalChunk(path2id(file.path)); const contentBin = await this.app.vault.adapter.readBinary(file.path); const content = await arrayBufferToBase64(contentBin); const mtime = file.mtime; await runWithLock("file-" + id, false, async () => { const old = await this.localDatabase.getDBEntry(id, null, false, false); let saveData; if (old === false) { saveData = { _id: id, data: content, mtime, ctime: mtime, datatype: "newnote", size: file.size, children: [], deleted: false, type: "newnote" }; } else { if (old.data == content && !forceWrite) { return; } saveData = { ...old, data: content, mtime, size: file.size, datatype: "newnote", children: [], deleted: false, type: "newnote" }; } await this.localDatabase.putDBEntry(saveData, true); Logger(`STORAGE --> DB:${file.path}: (hidden) Done`); }); } async deleteInternalFileOnDatabase(filename, forceWrite = false) { const id = filename2idInternalChunk(path2id(filename)); const mtime = new Date().getTime(); await runWithLock("file-" + id, false, async () => { const old = await this.localDatabase.getDBEntry(id, null, false, false); let saveData; if (old === false) { saveData = { _id: id, mtime, ctime: mtime, size: 0, children: [], deleted: true, type: "newnote" }; } else { if (old.deleted) { Logger(`STORAGE -x> DB:${filename}: (hidden) already deleted`); return; } saveData = { ...old, mtime, size: 0, children: [], deleted: true, type: "newnote" }; } await this.localDatabase.localDatabase.put(saveData); Logger(`STORAGE -x> DB:${filename}: (hidden) Done`); }); } async ensureDirectoryEx(fullPath) { const pathElements = fullPath.split("/"); pathElements.pop(); let c = ""; for (const v of pathElements) { c += v; try { await this.app.vault.adapter.mkdir(c); } catch (ex) { if (ex.message && ex.message == "Folder already exists.") { } else { Logger("Folder Create Error"); Logger(ex); } } c += "/"; } } async extractInternalFileFromDatabase(filename, force = false) { const isExists = await this.app.vault.adapter.exists(filename); const id = filename2idInternalChunk(path2id(filename)); return await runWithLock("file-" + id, false, async () => { const fileOnDB = await this.localDatabase.getDBEntry(id, null, false, false); if (fileOnDB === false) throw new Error(`File not found on database.:${id}`); const deleted = "deleted" in fileOnDB ? fileOnDB.deleted : false; if (deleted) { if (!isExists) { Logger(`STORAGE e3).map((e3) => new RegExp(e3)); return files.filter((file) => !ignorePatterns.some((e3) => file.path.match(e3))).filter((file) => !targetFiles || targetFiles && targetFiles.indexOf(file.path) !== -1); } async applyMTimeToFile(file) { await this.app.vault.adapter.append(file.path, "", { ctime: file.ctime, mtime: file.mtime }); } async resolveConflictOnInternalFiles() { const docs = await this.localDatabase.localDatabase.allDocs({ startkey: ICHeader, endkey: ICHeaderEnd, conflicts: true, include_docs: true }); for (const row of docs.rows) { const doc = row.doc; if (!("_conflicts" in doc)) continue; if (isInternalChunk(row.id)) { await this.resolveConflictOnInternalFile(row.id); } } } async resolveConflictOnInternalFile(id) { const doc = await this.localDatabase.localDatabase.get(id, { conflicts: true }); if (!("_conflicts" in doc)) return false; if (doc._conflicts.length == 0) return false; Logger(`Hidden file conflicted:${id2filenameInternalChunk(id)}`); const revA = doc._rev; const revB = doc._conflicts[0]; const revBDoc = await this.localDatabase.localDatabase.get(id, { rev: revB }); const mtimeA = "mtime" in doc && doc.mtime || 0; const mtimeB = "mtime" in revBDoc && revBDoc.mtime || 0; const delRev = mtimeA < mtimeB ? revA : revB; await this.localDatabase.localDatabase.remove(id, delRev); Logger(`Older one has been deleted:${id2filenameInternalChunk(id)}`); return this.resolveConflictOnInternalFile(id); } async syncInternalFilesAndDatabase(direction, showMessage, files = false, targetFiles = false) { await this.resolveConflictOnInternalFiles(); const logLevel = showMessage ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO; Logger("Scanning hidden files.", logLevel, "sync_internal"); const ignorePatterns = this.settings.syncInternalFilesIgnorePatterns.toLocaleLowerCase().replace(/\n| /g, "").split(",").filter((e3) => e3).map((e3) => new RegExp(e3)); if (!files) files = await this.scanInternalFiles(); const filesOnDB = (await this.localDatabase.localDatabase.allDocs({ startkey: ICHeader, endkey: ICHeaderEnd, include_docs: true })).rows.map((e3) => e3.doc).filter((e3) => !e3.deleted); const allFileNamesSrc = [...new Set([...files.map((e3) => (0, import_obsidian8.normalizePath)(e3.path)), ...filesOnDB.map((e3) => (0, import_obsidian8.normalizePath)(id2path(id2filenameInternalChunk(e3._id))))])]; const allFileNames = allFileNamesSrc.filter((filename) => !targetFiles || targetFiles && targetFiles.indexOf(filename) !== -1); function compareMTime(a, b) { const wa = ~~(a / 1e3); const wb = ~~(b / 1e3); const diff = wa - wb; return diff; } const fileCount = allFileNames.length; let processed = 0; let filesChanged = 0; const updatedFolders = {}; const countUpdatedFolder = (path) => { const pieces = path.split("/"); let c = pieces.shift(); let pathPieces = ""; filesChanged++; while (c) { pathPieces += (pathPieces != "" ? "/" : "") + c; pathPieces = (0, import_obsidian8.normalizePath)(pathPieces); if (!(pathPieces in updatedFolders)) { updatedFolders[pathPieces] = 0; } updatedFolders[pathPieces]++; c = pieces.shift(); } }; const p = []; const semaphore = Semaphore(15); let caches = {}; caches = await this.localDatabase.kvDB.get("diff-caches-internal") || {}; for (const filename of allFileNames) { processed++; if (processed % 100 == 0) Logger(`Hidden file: ${processed}/${fileCount}`, logLevel, "sync_internal"); if (ignorePatterns.some((e3) => filename.match(e3))) continue; const fileOnStorage = files.find((e3) => e3.path == filename); const fileOnDatabase = filesOnDB.find((e3) => e3._id == filename2idInternalChunk(id2path(filename))); const addProc = async (p2) => { const releaser = await semaphore.acquire(1); try { return p2(); } catch (ex) { Logger("Some process failed", logLevel); Logger(ex); } finally { releaser(); } }; const cache = filename in caches ? caches[filename] : { storageMtime: 0, docMtime: 0 }; p.push(addProc(async () => { if (fileOnStorage && fileOnDatabase) { if (fileOnDatabase.mtime == cache.docMtime && fileOnStorage.mtime == cache.storageMtime) { return; } const nw = compareMTime(fileOnStorage.mtime, fileOnDatabase.mtime); if (nw > 0) { await this.storeInternalFileToDatabase(fileOnStorage); } if (nw < 0) { if (!await this.extractInternalFileFromDatabase(filename)) return; } cache.docMtime = fileOnDatabase.mtime; cache.storageMtime = fileOnStorage.mtime; caches[filename] = cache; countUpdatedFolder(filename); } else if (!fileOnStorage && fileOnDatabase) { if (direction == "push") { if (fileOnDatabase.deleted) return; await this.deleteInternalFileOnDatabase(filename); } else if (direction == "pull") { if (await this.extractInternalFileFromDatabase(filename)) { countUpdatedFolder(filename); } } else if (direction == "safe") { if (fileOnDatabase.deleted) return; if (await this.extractInternalFileFromDatabase(filename)) { countUpdatedFolder(filename); } } } else if (fileOnStorage && !fileOnDatabase) { await this.storeInternalFileToDatabase(fileOnStorage); } else { throw new Error("Invalid state on hidden file sync"); } })); } await Promise.all(p); await this.localDatabase.kvDB.set("diff-caches-internal", caches); if (direction == "pull" && filesChanged != 0) { const configDir = (0, import_obsidian8.normalizePath)(this.app.vault.configDir); if (configDir in updatedFolders) { let updatedCount = updatedFolders[configDir]; try { const manifests = Object.values(this.app.plugins.manifests); const enabledPlugins = this.app.plugins.enabledPlugins; const enabledPluginManifests = manifests.filter((e3) => enabledPlugins.has(e3.id)); for (const manifest of enabledPluginManifests) { if (manifest.dir in updatedFolders) { updatedCount -= updatedFolders[manifest.dir]; const updatePluginId = manifest.id; const updatePluginName = manifest.name; const fragment = createFragment((doc) => { doc.createEl("span", null, (a) => { a.appendText(`Files in ${updatePluginName} has been updated, Press `); a.appendChild(a.createEl("a", null, (anchor) => { anchor.text = "HERE"; anchor.addEventListener("click", async () => { Logger(`Unloading plugin: ${updatePluginName}`, LOG_LEVEL.NOTICE, "plugin-reload-" + updatePluginId); await this.app.plugins.unloadPlugin(updatePluginId); await this.app.plugins.loadPlugin(updatePluginId); Logger(`Plugin reloaded: ${updatePluginName}`, LOG_LEVEL.NOTICE, "plugin-reload-" + updatePluginId); }); })); a.appendText(` to reload ${updatePluginName}, or press elsewhere to dismiss this message.`); }); }); const updatedPluginKey = "popupUpdated-" + updatePluginId; setTrigger(updatedPluginKey, 1e3, async () => { var _a; const popup = await memoIfNotExist(updatedPluginKey, () => new import_obsidian8.Notice(fragment, 0)); const isShown = (_a = popup == null ? void 0 : popup.noticeEl) == null ? void 0 : _a.isShown(); if (!isShown) { memoObject(updatedPluginKey, new import_obsidian8.Notice(fragment, 0)); } setTrigger(updatedPluginKey + "-close", 2e4, () => { var _a2; const popup2 = retrieveMemoObject(updatedPluginKey); if (!popup2) return; if ((_a2 = popup2 == null ? void 0 : popup2.noticeEl) == null ? void 0 : _a2.isShown()) { popup2.hide(); } disposeMemoObject(updatedPluginKey); }); }); } } } catch (ex) { Logger("Error on checking plugin status."); Logger(ex, LOG_LEVEL.VERBOSE); } if (updatedCount != 0) { const fragment = createFragment((doc) => { doc.createEl("span", null, (a) => { a.appendText(`Hidden files have been synchronized, Press `); a.appendChild(a.createEl("a", null, (anchor) => { anchor.text = "HERE"; anchor.addEventListener("click", () => { this.app.commands.executeCommandById("app:reload"); }); })); a.appendText(` to reload obsidian, or press elsewhere to dismiss this message.`); }); }); setTrigger("popupUpdated-" + configDir, 1e3, () => { var _a, _b; const isShown = (_b = (_a = this.confirmPopup) == null ? void 0 : _a.noticeEl) == null ? void 0 : _b.isShown(); if (!isShown) { this.confirmPopup = new import_obsidian8.Notice(fragment, 0); } setTrigger("popupClose" + configDir, 2e4, () => { var _a2; (_a2 = this.confirmPopup) == null ? void 0 : _a2.hide(); this.confirmPopup = null; }); }); } } } Logger(`Hidden files scanned: ${filesChanged} files had been modified`, logLevel, "sync_internal"); } isTargetFile(file) { if (file instanceof import_obsidian8.TFile) { return this.localDatabase.isTargetFile(file.path); } else if (typeof file == "string") { return this.localDatabase.isTargetFile(file); } } };