From f69dff2f144ff206b93379bb4d829ec83ec8fcb7 Mon Sep 17 00:00:00 2001 From: ArgentumCation Date: Thu, 5 Sep 2024 22:31:04 -0400 Subject: [PATCH] ??? --- eslint.config.js | 11 + eslint.config.mjs | 0 src/content/blog/.obsidian/app.json | 36 + src/content/blog/.obsidian/appearance.json | 10 + .../blog/.obsidian/community-plugins.json | 4 + .../.obsidian/core-plugins-migration.json | 30 + src/content/blog/.obsidian/core-plugins.json | 23 + src/content/blog/.obsidian/hotkeys.json | 11 + .../.obsidian/plugins/obsidian-git/data.json | 58 + .../.obsidian/plugins/obsidian-git/main.js | 45283 ++++++++++++++++ .../plugins/obsidian-git/manifest.json | 9 + .../.obsidian/plugins/obsidian-git/styles.css | 558 + .../plugins/obsidian-livesync/data.json | 70 + .../plugins/obsidian-livesync/main.js | 24242 +++++++++ .../plugins/obsidian-livesync/manifest.json | 10 + .../plugins/obsidian-livesync/styles.css | 254 + .../obsidian-markdown-file-suffix/main.js | 61 + .../manifest.json | 10 + .../obsidian-markdown-file-suffix/styles.css | 8 + .../plugins/templater-obsidian/data.json | 30 + .../plugins/templater-obsidian/main.js | 5624 ++ .../plugins/templater-obsidian/manifest.json | 11 + .../plugins/templater-obsidian/styles.css | 220 + src/content/blog/.obsidian/templates.json | 3 + src/content/blog/.obsidian/themes/Lunar Witch | 1 + .../blog/.obsidian/workspace-mobile.json | 189 + src/content/blog/.obsidian/workspace.json | 195 + src/content/blog/.trash/post-1.mdx | 41 + src/content/blog/.trash/traefik-setup.mdx | 143 + src/content/blog/Cluster(fuck).md | 37 + src/content/blog/_drafts/eigencode.md | 1 + src/content/blog/_drafts/luka_pona.md | 22 + src/content/blog/_drafts/olc-codes.md | 35 +- src/content/blog/_templates/post-template.md | 8 + src/content/blog/disorganized-notes.md | 95 +- src/content/blog/{ => images}/btrfs.md | 0 src/content/blog/images/image-7.png | Bin 0 -> 122983 bytes 37 files changed, 77324 insertions(+), 19 deletions(-) create mode 100644 eslint.config.js create mode 100644 eslint.config.mjs create mode 100644 src/content/blog/.obsidian/app.json create mode 100644 src/content/blog/.obsidian/appearance.json create mode 100644 src/content/blog/.obsidian/community-plugins.json create mode 100644 src/content/blog/.obsidian/core-plugins-migration.json create mode 100644 src/content/blog/.obsidian/core-plugins.json create mode 100644 src/content/blog/.obsidian/hotkeys.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-git/data.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-git/main.js create mode 100644 src/content/blog/.obsidian/plugins/obsidian-git/manifest.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-git/styles.css create mode 100644 src/content/blog/.obsidian/plugins/obsidian-livesync/data.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-livesync/main.js create mode 100644 src/content/blog/.obsidian/plugins/obsidian-livesync/manifest.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-livesync/styles.css create mode 100644 src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/main.js create mode 100644 src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/manifest.json create mode 100644 src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/styles.css create mode 100644 src/content/blog/.obsidian/plugins/templater-obsidian/data.json create mode 100644 src/content/blog/.obsidian/plugins/templater-obsidian/main.js create mode 100644 src/content/blog/.obsidian/plugins/templater-obsidian/manifest.json create mode 100644 src/content/blog/.obsidian/plugins/templater-obsidian/styles.css create mode 100644 src/content/blog/.obsidian/templates.json create mode 160000 src/content/blog/.obsidian/themes/Lunar Witch create mode 100644 src/content/blog/.obsidian/workspace-mobile.json create mode 100644 src/content/blog/.obsidian/workspace.json create mode 100644 src/content/blog/.trash/post-1.mdx create mode 100644 src/content/blog/.trash/traefik-setup.mdx create mode 100644 src/content/blog/Cluster(fuck).md create mode 100644 src/content/blog/_drafts/eigencode.md create mode 100644 src/content/blog/_drafts/luka_pona.md create mode 100644 src/content/blog/_templates/post-template.md rename src/content/blog/{ => images}/btrfs.md (100%) create mode 100644 src/content/blog/images/image-7.png diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..90d6f5e --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,11 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; +import tseslint from "typescript-eslint"; + + +export default [ + {files: ["**/*.{js,mjs,cjs,ts}"]}, + {languageOptions: { globals: globals.browser }}, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, +]; \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..e69de29 diff --git a/src/content/blog/.obsidian/app.json b/src/content/blog/.obsidian/app.json new file mode 100644 index 0000000..3e0c6c4 --- /dev/null +++ b/src/content/blog/.obsidian/app.json @@ -0,0 +1,36 @@ +{ + "useMarkdownLinks": true, + "attachmentFolderPath": "./images", + "vimMode": true, + "mobileToolbarCommands": [ + "editor:insert-wikilink", + "editor:insert-embed", + "editor:insert-tag", + "editor:attach-file", + "editor:set-heading", + "editor:toggle-bold", + "editor:toggle-italics", + "editor:toggle-strikethrough", + "editor:toggle-highlight", + "editor:toggle-code", + "editor:toggle-blockquote", + "editor:insert-link", + "editor:toggle-bullet-list", + "editor:toggle-numbered-list", + "editor:toggle-checklist-status", + "editor:indent-list", + "editor:unindent-list", + "editor:undo", + "editor:redo", + "editor:configure-toolbar", + "editor:insert-callout", + "editor:insert-table" + ], + "pdfExportSettings": { + "includeName": true, + "pageSize": "Letter", + "landscape": true, + "margin": "0", + "downscalePercent": 100 + } +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/appearance.json b/src/content/blog/.obsidian/appearance.json new file mode 100644 index 0000000..cee9a6a --- /dev/null +++ b/src/content/blog/.obsidian/appearance.json @@ -0,0 +1,10 @@ +{ + "accentColor": "#1a538d", + "interfaceFontFamily": "Atkinson Hyperlegible", + "textFontFamily": "Atkinson Hyperlegible", + "baseFontSize": 16, + "baseFontSizeAction": true, + "monospaceFontFamily": "Fairfax Hax HD", + "cssTheme": "Lunar Witch", + "theme": "obsidian" +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/community-plugins.json b/src/content/blog/.obsidian/community-plugins.json new file mode 100644 index 0000000..f2e5878 --- /dev/null +++ b/src/content/blog/.obsidian/community-plugins.json @@ -0,0 +1,4 @@ +[ + "obsidian-git", + "templater-obsidian" +] \ No newline at end of file diff --git a/src/content/blog/.obsidian/core-plugins-migration.json b/src/content/blog/.obsidian/core-plugins-migration.json new file mode 100644 index 0000000..55aad0f --- /dev/null +++ b/src/content/blog/.obsidian/core-plugins-migration.json @@ -0,0 +1,30 @@ +{ + "file-explorer": true, + "global-search": true, + "switcher": true, + "graph": true, + "backlink": true, + "canvas": true, + "outgoing-link": true, + "tag-pane": true, + "properties": true, + "page-preview": true, + "daily-notes": true, + "templates": true, + "note-composer": true, + "command-palette": true, + "slash-command": true, + "editor-status": true, + "bookmarks": true, + "markdown-importer": false, + "zk-prefixer": false, + "random-note": false, + "outline": true, + "word-count": true, + "slides": true, + "audio-recorder": false, + "workspaces": false, + "file-recovery": true, + "publish": false, + "sync": false +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/core-plugins.json b/src/content/blog/.obsidian/core-plugins.json new file mode 100644 index 0000000..56f6773 --- /dev/null +++ b/src/content/blog/.obsidian/core-plugins.json @@ -0,0 +1,23 @@ +[ + "file-explorer", + "global-search", + "switcher", + "graph", + "backlink", + "canvas", + "outgoing-link", + "tag-pane", + "properties", + "page-preview", + "daily-notes", + "templates", + "note-composer", + "command-palette", + "slash-command", + "editor-status", + "bookmarks", + "outline", + "word-count", + "slides", + "file-recovery" +] \ No newline at end of file diff --git a/src/content/blog/.obsidian/hotkeys.json b/src/content/blog/.obsidian/hotkeys.json new file mode 100644 index 0000000..8448588 --- /dev/null +++ b/src/content/blog/.obsidian/hotkeys.json @@ -0,0 +1,11 @@ +{ + "editor:toggle-source": [ + { + "modifiers": [ + "Mod" + ], + "key": "/" + } + ], + "editor:toggle-comments": [] +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/obsidian-git/data.json b/src/content/blog/.obsidian/plugins/obsidian-git/data.json new file mode 100644 index 0000000..198aad0 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-git/data.json @@ -0,0 +1,58 @@ +{ + "commitMessage": "vault backup: {{date}}", + "commitDateFormat": "YYYY-MM-DD HH:mm:ss", + "autoSaveInterval": 0, + "autoPushInterval": 10, + "autoPullInterval": 10, + "autoPullOnBoot": true, + "disablePush": false, + "pullBeforePush": true, + "disablePopups": false, + "disablePopupsForNoChanges": true, + "listChangedFilesInMessageBody": false, + "showStatusBar": true, + "updateSubmodules": false, + "syncMethod": "rebase", + "customMessageOnAutoBackup": false, + "autoBackupAfterFileChange": false, + "treeStructure": false, + "refreshSourceControl": true, + "basePath": "", + "differentIntervalCommitAndPush": true, + "changedFilesInStatusBar": false, + "showedMobileNotice": true, + "refreshSourceControlTimer": 7000, + "showBranchStatusBar": true, + "setLastSaveToLastCommit": false, + "submoduleRecurseCheckout": false, + "gitDir": "", + "showFileMenu": true, + "authorInHistoryView": "hide", + "dateInHistoryView": false, + "lineAuthor": { + "show": false, + "followMovement": "inactive", + "authorDisplay": "initials", + "showCommitHash": false, + "dateTimeFormatOptions": "date", + "dateTimeFormatCustomString": "YYYY-MM-DD HH:mm", + "dateTimeTimezone": "viewer-local", + "coloringMaxAge": "1y", + "colorNew": { + "r": 255, + "g": 150, + "b": 150 + }, + "colorOld": { + "r": 120, + "g": 160, + "b": 255 + }, + "textColorCss": "var(--text-muted)", + "ignoreWhitespace": false, + "gutterSpacingFallbackLength": 5, + "lastShownAuthorDisplay": "initials", + "lastShownDateTimeFormatOptions": "date" + }, + "autoCommitMessage": "vault backup: {{date}}" +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/obsidian-git/main.js b/src/content/blog/.obsidian/plugins/obsidian-git/main.js new file mode 100644 index 0000000..9457262 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-git/main.js @@ -0,0 +1,45283 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source visit the plugins github repository (https://github.com/denolehov/obsidian-git) +*/ + +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 __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key2 of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key2) && key2 !== except) + __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key2, value) => { + __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value); + return value; +}; + +// node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js +var require_base64_js = __commonJS({ + "node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + exports2.byteLength = byteLength; + exports2.toByteArray = toByteArray; + exports2.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + var i; + var len; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) + validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0; i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + function tripletToBase64(num2) { + return lookup[num2 >> 18 & 63] + lookup[num2 >> 12 & 63] + lookup[num2 >> 6 & 63] + lookup[num2 & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start; i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + } +}); + +// node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js +var require_ieee754 = __commonJS({ + "node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js"(exports2) { + init_polyfill_buffer(); + exports2.read = function(buffer2, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer2[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) { + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + exports2.write = function(buffer2, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer2[offset + i - d] |= s * 128; + }; + } +}); + +// node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js +var require_buffer = __commonJS({ + "node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var base64 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { + console.error( + "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." + ); + } + function typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.byteOffset; + } + }); + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length); + } + Buffer2.poolSize = 8192; + function from(value, encodingOrOffset, length) { + if (typeof value === "string") { + return fromString2(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length); + } + const b = fromObject(value); + if (b) + return b; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe(size); + }; + function fromString2(string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length = byteLength(string, encoding) | 0; + let buf = createBuffer(length); + const actual = buf.write(string, encoding); + if (actual !== length) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy2 = new Uint8Array(arrayView); + return fromArrayBuffer(copy2.buffer, copy2.byteOffset, copy2.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length === void 0) { + buf = new Uint8Array(array); + } else if (length === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length) { + if (length >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length | 0; + } + function SlowBuffer(length) { + if (+length != length) { + length = 0; + } + return Buffer2.alloc(+length); + } + Buffer2.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer2.prototype; + }; + Buffer2.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) + a = Buffer2.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) + b = Buffer2.from(b, b.offset, b.byteLength); + if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a === b) + return 0; + let x = a.length; + let y = b.length; + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) + return -1; + if (y < x) + return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + Buffer2.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + let i; + if (length === void 0) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + const buffer2 = Buffer2.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer2.length) { + if (!Buffer2.isBuffer(buf)) + buf = Buffer2.from(buf); + buf.copy(buffer2, pos); + } else { + Uint8Array.prototype.set.call( + buffer2, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer2, pos); + } + pos += buf.length; + } + return buffer2; + }; + function byteLength(string, encoding) { + if (Buffer2.isBuffer(string)) { + return string.length; + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string + ); + } + const len = string.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) + return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) + encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; + } + Buffer2.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString() { + const length = this.length; + if (length === 0) + return ""; + if (arguments.length === 0) + return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals3(b) { + if (!Buffer2.isBuffer(b)) + throw new TypeError("Argument must be a Buffer"); + if (this === b) + return true; + return Buffer2.compare(this, b) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + let str = ""; + const max = exports2.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) + str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) + return 0; + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) + return -1; + if (y < x) + return 1; + return 0; + }; + function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) { + if (buffer2.length === 0) + return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer2.length - 1; + } + if (byteOffset < 0) + byteOffset = buffer2.length + byteOffset; + if (byteOffset >= buffer2.length) { + if (dir) + return -1; + else + byteOffset = buffer2.length - 1; + } else if (byteOffset < 0) { + if (dir) + byteOffset = 0; + else + return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer2, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); + } + } + return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read(buf, i2) { + if (indexSize === 1) { + return buf[i2]; + } else { + return buf.readUInt16BE(i2 * indexSize); + } + } + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) + foundIndex = i; + if (i - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) + i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) + return i; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + const strLen = string.length; + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) + return i; + buf[offset + i] = parsed; + } + return i; + } + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + Buffer2.prototype.write = function write(string, offset, length, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length = this.length; + offset = 0; + } else if (length === void 0 && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === void 0) + encoding = "utf8"; + } else { + encoding = length; + length = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset; + if (length === void 0 || length > remaining) + length = remaining; + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) + encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string, offset, length); + case "base64": + return base64Write(this, string, offset, length); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) + start = 0; + if (!end || end < 0 || end > len) + end = len; + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) + start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) + end = 0; + } else if (end > len) { + end = len; + } + if (end < start) + end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length) + throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset + i] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + let val = this[offset + --byteLength2]; + let mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first2 = this[offset]; + const last2 = this[offset + 7]; + if (first2 === void 0 || last2 === void 0) { + boundsError(offset, this.length - 8); + } + const lo = first2 + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last2 * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }); + Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first2 = this[offset]; + const last2 = this[offset + 7]; + if (first2 === void 0 || last2 === void 0) { + boundsError(offset, this.length - 8); + } + const hi = first2 * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last2; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }); + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset + i] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let i = byteLength2; + let mul = 1; + let val = this[offset + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset + --i] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) + return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first2 = this[offset]; + const last2 = this[offset + 7]; + if (first2 === void 0 || last2 === void 0) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last2 << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first2 + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); + }); + Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first2 = this[offset]; + const last2 = this[offset + 7]; + if (first2 === void 0 || last2 === void 0) { + boundsError(offset, this.length - 8); + } + const val = (first2 << 24) + // Overflow + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last2); + }); + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let mul = 1; + let i = 0; + this[offset] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let i = byteLength2 - 1; + let mul = 1; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function wrtBigUInt64LE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; + } + function wrtBigUInt64BE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; + } + Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i = byteLength2 - 1; + let mul = 1; + let sub = 0; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 127, -128); + if (value < 0) + value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) + value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) + throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy2(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) + throw new TypeError("argument should be a Buffer"); + if (!start) + start = 0; + if (!end && end !== 0) + end = this.length; + if (targetStart >= target.length) + targetStart = target.length; + if (!targetStart) + targetStart = 0; + if (end > 0 && end < start) + end = start; + if (end === start) + return 0; + if (target.length === 0 || this.length === 0) + return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("Index out of range"); + if (end < 0) + throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) + end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code = val.charCodeAt(0); + if (encoding === "utf8" && code < 128 || encoding === "latin1") { + val = code; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) + val = 0; + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; + }; + var errors = {}; + function E(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + E( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name) { + if (name) { + return `${name} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E( + "ERR_INVALID_ARG_TYPE", + function(name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E( + "ERR_OUT_OF_RANGE", + function(str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; + } + function checkBounds(buf, offset, byteLength2) { + validateNumber(offset, "offset"); + if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { + boundsError(offset, buf.length - (byteLength2 + 1)); + } + } + function checkIntBI(value, min, max, buf, offset, byteLength2) { + if (value > max || value < min) { + const n = typeof min === "bigint" ? "n" : ""; + let range; + if (byteLength2 > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; + } else { + range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`; + } + } else { + range = `>= ${min}${n} and <= ${max}${n}`; + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value); + } + checkBounds(buf, offset, byteLength2); + } + function validateNumber(value, name) { + if (typeof value !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); + } + } + function boundsError(value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); + } + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE( + type || "offset", + `>= ${type ? 1 : 0} and <= ${length}`, + value + ); + } + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) + return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string, units) { + units = units || Infinity; + let codePoint; + const length = string.length; + let leadSurrogate = null; + const bytes = []; + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } else if (i + 1 === length) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) + break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) + break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) + break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) + break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) + break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); + } + function blitBuffer(src, dst, offset, length) { + let i; + for (i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) + break; + dst[i + offset] = src[i]; + } + return i; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + var hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } + } +}); + +// polyfill_buffer.js +var import_obsidian, buffer, Buffer; +var init_polyfill_buffer = __esm({ + "polyfill_buffer.js"() { + import_obsidian = require("obsidian"); + if (import_obsidian.Platform.isMobileApp) { + buffer = require_buffer().Buffer; + } else { + buffer = global.Buffer; + } + Buffer = buffer; + } +}); + +// node_modules/.pnpm/async-lock@1.4.1/node_modules/async-lock/lib/index.js +var require_lib = __commonJS({ + "node_modules/.pnpm/async-lock@1.4.1/node_modules/async-lock/lib/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var AsyncLock2 = function(opts) { + opts = opts || {}; + this.Promise = opts.Promise || Promise; + this.queues = /* @__PURE__ */ Object.create(null); + this.domainReentrant = opts.domainReentrant || false; + if (this.domainReentrant) { + if (typeof process === "undefined" || typeof process.domain === "undefined") { + throw new Error( + "Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill." + ); + } + this.domains = /* @__PURE__ */ Object.create(null); + } + this.timeout = opts.timeout || AsyncLock2.DEFAULT_TIMEOUT; + this.maxOccupationTime = opts.maxOccupationTime || AsyncLock2.DEFAULT_MAX_OCCUPATION_TIME; + this.maxExecutionTime = opts.maxExecutionTime || AsyncLock2.DEFAULT_MAX_EXECUTION_TIME; + if (opts.maxPending === Infinity || Number.isInteger(opts.maxPending) && opts.maxPending >= 0) { + this.maxPending = opts.maxPending; + } else { + this.maxPending = AsyncLock2.DEFAULT_MAX_PENDING; + } + }; + AsyncLock2.DEFAULT_TIMEOUT = 0; + AsyncLock2.DEFAULT_MAX_OCCUPATION_TIME = 0; + AsyncLock2.DEFAULT_MAX_EXECUTION_TIME = 0; + AsyncLock2.DEFAULT_MAX_PENDING = 1e3; + AsyncLock2.prototype.acquire = function(key2, fn, cb, opts) { + if (Array.isArray(key2)) { + return this._acquireBatch(key2, fn, cb, opts); + } + if (typeof fn !== "function") { + throw new Error("You must pass a function to execute"); + } + var deferredResolve = null; + var deferredReject = null; + var deferred2 = null; + if (typeof cb !== "function") { + opts = cb; + cb = null; + deferred2 = new this.Promise(function(resolve, reject) { + deferredResolve = resolve; + deferredReject = reject; + }); + } + opts = opts || {}; + var resolved = false; + var timer = null; + var occupationTimer = null; + var executionTimer = null; + var self2 = this; + var done = function(locked, err, ret) { + if (occupationTimer) { + clearTimeout(occupationTimer); + occupationTimer = null; + } + if (executionTimer) { + clearTimeout(executionTimer); + executionTimer = null; + } + if (locked) { + if (!!self2.queues[key2] && self2.queues[key2].length === 0) { + delete self2.queues[key2]; + } + if (self2.domainReentrant) { + delete self2.domains[key2]; + } + } + if (!resolved) { + if (!deferred2) { + if (typeof cb === "function") { + cb(err, ret); + } + } else { + if (err) { + deferredReject(err); + } else { + deferredResolve(ret); + } + } + resolved = true; + } + if (locked) { + if (!!self2.queues[key2] && self2.queues[key2].length > 0) { + self2.queues[key2].shift()(); + } + } + }; + var exec = function(locked) { + if (resolved) { + return done(locked); + } + if (timer) { + clearTimeout(timer); + timer = null; + } + if (self2.domainReentrant && locked) { + self2.domains[key2] = process.domain; + } + var maxExecutionTime = opts.maxExecutionTime || self2.maxExecutionTime; + if (maxExecutionTime) { + executionTimer = setTimeout(function() { + if (!!self2.queues[key2]) { + done(locked, new Error("Maximum execution time is exceeded " + key2)); + } + }, maxExecutionTime); + } + if (fn.length === 1) { + var called = false; + try { + fn(function(err, ret) { + if (!called) { + called = true; + done(locked, err, ret); + } + }); + } catch (err) { + if (!called) { + called = true; + done(locked, err); + } + } + } else { + self2._promiseTry(function() { + return fn(); + }).then(function(ret) { + done(locked, void 0, ret); + }, function(error) { + done(locked, error); + }); + } + }; + if (self2.domainReentrant && !!process.domain) { + exec = process.domain.bind(exec); + } + var maxPending = opts.maxPending || self2.maxPending; + if (!self2.queues[key2]) { + self2.queues[key2] = []; + exec(true); + } else if (self2.domainReentrant && !!process.domain && process.domain === self2.domains[key2]) { + exec(false); + } else if (self2.queues[key2].length >= maxPending) { + done(false, new Error("Too many pending tasks in queue " + key2)); + } else { + var taskFn = function() { + exec(true); + }; + if (opts.skipQueue) { + self2.queues[key2].unshift(taskFn); + } else { + self2.queues[key2].push(taskFn); + } + var timeout = opts.timeout || self2.timeout; + if (timeout) { + timer = setTimeout(function() { + timer = null; + done(false, new Error("async-lock timed out in queue " + key2)); + }, timeout); + } + } + var maxOccupationTime = opts.maxOccupationTime || self2.maxOccupationTime; + if (maxOccupationTime) { + occupationTimer = setTimeout(function() { + if (!!self2.queues[key2]) { + done(false, new Error("Maximum occupation time is exceeded in queue " + key2)); + } + }, maxOccupationTime); + } + if (deferred2) { + return deferred2; + } + }; + AsyncLock2.prototype._acquireBatch = function(keys, fn, cb, opts) { + if (typeof cb !== "function") { + opts = cb; + cb = null; + } + var self2 = this; + var getFn = function(key2, fn2) { + return function(cb2) { + self2.acquire(key2, fn2, cb2, opts); + }; + }; + var fnx = keys.reduceRight(function(prev, key2) { + return getFn(key2, prev); + }, fn); + if (typeof cb === "function") { + fnx(cb); + } else { + return new this.Promise(function(resolve, reject) { + if (fnx.length === 1) { + fnx(function(err, ret) { + if (err) { + reject(err); + } else { + resolve(ret); + } + }); + } else { + resolve(fnx()); + } + }); + } + }; + AsyncLock2.prototype.isBusy = function(key2) { + if (!key2) { + return Object.keys(this.queues).length > 0; + } else { + return !!this.queues[key2]; + } + }; + AsyncLock2.prototype._promiseTry = function(fn) { + try { + return this.Promise.resolve(fn()); + } catch (e) { + return this.Promise.reject(e); + } + }; + module2.exports = AsyncLock2; + } +}); + +// node_modules/.pnpm/async-lock@1.4.1/node_modules/async-lock/index.js +var require_async_lock = __commonJS({ + "node_modules/.pnpm/async-lock@1.4.1/node_modules/async-lock/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = require_lib(); + } +}); + +// node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports2, module2) { + init_polyfill_buffer(); + if (typeof Object.create === "function") { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports2, module2) { + init_polyfill_buffer(); + var buffer2 = require_buffer(); + var Buffer2 = buffer2.Buffer; + function copyProps(src, dst) { + for (var key2 in src) { + dst[key2] = src[key2]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer2; + } else { + copyProps(buffer2, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer2.SlowBuffer(size); + }; + } +}); + +// node_modules/.pnpm/sha.js@2.4.11/node_modules/sha.js/hash.js +var require_hash = __commonJS({ + "node_modules/.pnpm/sha.js@2.4.11/node_modules/sha.js/hash.js"(exports2, module2) { + init_polyfill_buffer(); + var Buffer2 = require_safe_buffer().Buffer; + function Hash2(blockSize, finalSize) { + this._block = Buffer2.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + Hash2.prototype.update = function(data, enc) { + if (typeof data === "string") { + enc = enc || "utf8"; + data = Buffer2.from(data, enc); + } + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + for (var offset = 0; offset < length; ) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + accum += remainder; + offset += remainder; + if (accum % blockSize === 0) { + this._update(block); + } + } + this._len += length; + return this; + }; + Hash2.prototype.digest = function(enc) { + var rem = this._len % this._blockSize; + this._block[rem] = 128; + this._block.fill(0, rem + 1); + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + var bits = this._len * 8; + if (bits <= 4294967295) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + } else { + var lowBits = (bits & 4294967295) >>> 0; + var highBits = (bits - lowBits) / 4294967296; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + this._update(this._block); + var hash2 = this._hash(); + return enc ? hash2.toString(enc) : hash2; + }; + Hash2.prototype._update = function() { + throw new Error("_update must be implemented by subclass"); + }; + module2.exports = Hash2; + } +}); + +// node_modules/.pnpm/sha.js@2.4.11/node_modules/sha.js/sha1.js +var require_sha1 = __commonJS({ + "node_modules/.pnpm/sha.js@2.4.11/node_modules/sha.js/sha1.js"(exports2, module2) { + init_polyfill_buffer(); + var inherits = require_inherits_browser(); + var Hash2 = require_hash(); + var Buffer2 = require_safe_buffer().Buffer; + var K2 = [ + 1518500249, + 1859775393, + 2400959708 | 0, + 3395469782 | 0 + ]; + var W = new Array(80); + function Sha1() { + this.init(); + this._w = W; + Hash2.call(this, 64, 56); + } + inherits(Sha1, Hash2); + Sha1.prototype.init = function() { + this._a = 1732584193; + this._b = 4023233417; + this._c = 2562383102; + this._d = 271733878; + this._e = 3285377520; + return this; + }; + function rotl1(num2) { + return num2 << 1 | num2 >>> 31; + } + function rotl5(num2) { + return num2 << 5 | num2 >>> 27; + } + function rotl30(num2) { + return num2 << 30 | num2 >>> 2; + } + function ft(s, b, c, d) { + if (s === 0) + return b & c | ~b & d; + if (s === 2) + return b & c | b & d | c & d; + return b ^ c ^ d; + } + Sha1.prototype._update = function(M) { + var W2 = this._w; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + for (var i = 0; i < 16; ++i) + W2[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) + W2[i] = rotl1(W2[i - 3] ^ W2[i - 8] ^ W2[i - 14] ^ W2[i - 16]); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = rotl5(a) + ft(s, b, c, d) + e + W2[j] + K2[s] | 0; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + this._a = a + this._a | 0; + this._b = b + this._b | 0; + this._c = c + this._c | 0; + this._d = d + this._d | 0; + this._e = e + this._e | 0; + }; + Sha1.prototype._hash = function() { + var H = Buffer2.allocUnsafe(20); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + return H; + }; + module2.exports = Sha1; + } +}); + +// node_modules/.pnpm/crc-32@1.2.2/node_modules/crc-32/crc32.js +var require_crc32 = __commonJS({ + "node_modules/.pnpm/crc-32@1.2.2/node_modules/crc-32/crc32.js"(exports2) { + init_polyfill_buffer(); + var CRC32; + (function(factory) { + if (typeof DO_NOT_EXPORT_CRC === "undefined") { + if ("object" === typeof exports2) { + factory(exports2); + } else if ("function" === typeof define && define.amd) { + define(function() { + var module3 = {}; + factory(module3); + return module3; + }); + } else { + factory(CRC32 = {}); + } + } else { + factory(CRC32 = {}); + } + })(function(CRC322) { + CRC322.version = "1.2.2"; + function signed_crc_table() { + var c = 0, table = new Array(256); + for (var n = 0; n != 256; ++n) { + c = n; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1; + table[n] = c; + } + return typeof Int32Array !== "undefined" ? new Int32Array(table) : table; + } + var T0 = signed_crc_table(); + function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096); + for (n = 0; n != 256; ++n) + table[n] = T[n]; + for (n = 0; n != 256; ++n) { + v = T[n]; + for (c = 256 + n; c < 4096; c += 256) + v = table[c] = v >>> 8 ^ T[v & 255]; + } + var out = []; + for (n = 1; n != 16; ++n) + out[n - 1] = typeof Int32Array !== "undefined" ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; + } + var TT = slice_by_16_tables(T0); + var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; + var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; + var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; + function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for (var i = 0, L = bstr.length; i < L; ) + C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255]; + return ~C; + } + function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for (; i < L; ) + C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while (i < L) + C = C >>> 8 ^ T0[(C ^ B[i++]) & 255]; + return ~C; + } + function crc32_str(str, seed) { + var C = seed ^ -1; + for (var i = 0, L = str.length, c = 0, d = 0; i < L; ) { + c = str.charCodeAt(i++); + if (c < 128) { + C = C >>> 8 ^ T0[(C ^ c) & 255]; + } else if (c < 2048) { + C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255]; + } else if (c >= 55296 && c < 57344) { + c = (c & 1023) + 64; + d = str.charCodeAt(i++) & 1023; + C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255]; + } else { + C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255]; + C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255]; + } + } + return ~C; + } + CRC322.table = T0; + CRC322.bstr = crc32_bstr; + CRC322.buf = crc32_buf; + CRC322.str = crc32_str; + }); + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/common.js +var require_common = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/common.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports2.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { + continue; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be non-object"); + } + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + return obj; + }; + exports2.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports2.setTyped = function(on) { + if (on) { + exports2.Buf8 = Uint8Array; + exports2.Buf16 = Uint16Array; + exports2.Buf32 = Int32Array; + exports2.assign(exports2, fnTyped); + } else { + exports2.Buf8 = Array; + exports2.Buf16 = Array; + exports2.Buf32 = Array; + exports2.assign(exports2, fnUntyped); + } + }; + exports2.setTyped(TYPED_OK); + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/trees.js +var require_trees = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/trees.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var extra_lbits = ( + /* extra bits for each length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0] + ); + var extra_dbits = ( + /* extra bits for each distance code */ + [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13] + ); + var extra_blbits = ( + /* extra bits for each bit length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7] + ); + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value, length) { + if (s.bi_valid > Buf_size - length) { + s.bi_buf |= value << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value >> Buf_size - s.bi_valid; + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= value << s.bi_valid & 65535; + s.bi_valid += length; + } + } + function send_code(s, c, tree) { + send_bits( + s, + tree[c * 2], + tree[c * 2 + 1] + /*.Len*/ + ); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < 1 << extra_lbits[code]; n++) { + _length_code[length++] = code; + } + } + _length_code[length - 1] = code; + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < 1 << extra_dbits[code]; n++) { + _dist_code[dist++] = code; + } + } + dist >>= 7; + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist++] = code; + } + } + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0; n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0; n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0; n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k) { + var v = s.heap[k]; + var j = k << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k] = s.heap[j]; + k = j; + j <<= 1; + } + s.heap[k] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0; n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1; n >= 1; n--) { + pqdownheap(s, tree, n); + } + node = elems; + do { + n = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[ + 1 + /*SMALLEST*/ + ] = s.heap[s.heap_len--]; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + m = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[ + 1 + /*SMALLEST*/ + ] = node++; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[ + 1 + /*SMALLEST*/ + ]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0; rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last2) { + send_bits(s, (STORED_BLOCK << 1) + (last2 ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last2) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last2); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last2 ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last2 ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last2) { + bi_windup(s); + } + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports2._tr_init = _tr_init; + exports2._tr_stored_block = _tr_stored_block; + exports2._tr_flush_block = _tr_flush_block; + exports2._tr_tally = _tr_tally; + exports2._tr_align = _tr_align; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js +var require_adler32 = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/adler32.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2e3 ? 2e3 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module2.exports = adler32; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js +var require_crc322 = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/crc32.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc322(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos; i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + module2.exports = crc322; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/messages.js +var require_messages = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/messages.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = { + 2: "need dictionary", + /* Z_NEED_DICT 2 */ + 1: "stream end", + /* Z_STREAM_END 1 */ + 0: "", + /* Z_OK 0 */ + "-1": "file error", + /* Z_ERRNO (-1) */ + "-2": "stream error", + /* Z_STREAM_ERROR (-2) */ + "-3": "data error", + /* Z_DATA_ERROR (-3) */ + "-4": "insufficient memory", + /* Z_MEM_ERROR (-4) */ + "-5": "buffer error", + /* Z_BUF_ERROR (-5) */ + "-6": "incompatible version" + /* Z_VERSION_ERROR (-6) */ + }; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js +var require_deflate = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/deflate.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc322 = require_crc322(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last2) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last2); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc322(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush2) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (; ; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush2 === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush2 === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush2) { + var hash_head; + var bflush; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush2 === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush2 === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush2) { + var hash_head; + var bflush; + var max_insert; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush2 === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush2 === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush2) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (; ; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush2 === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush2 === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush2) { + var bflush; + for (; ; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush2 === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush2 === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), + /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), + /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), + /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), + /* 3 */ + new Config(4, 4, 16, 16, deflate_slow), + /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), + /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), + /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), + /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), + /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) + /* 9 max compression */ + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method2, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method2 !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState(); + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method2; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate2(strm, flush2) { + var old_flush, s; + var beg, val; + if (!strm || !strm.state || flush2 > Z_BLOCK || flush2 < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush2 !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush2; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte( + s, + (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush2) <= rank(old_flush) && flush2 !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush2 !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush2) : s.strategy === Z_RLE ? deflate_rle(s, flush2) : configuration_table[s.level].func(s, flush2); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush2 === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } else if (flush2 !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush2 === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush2 !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status2; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status2 = strm.state.status; + if (status2 !== INIT_STATE && status2 !== EXTRA_STATE && status2 !== NAME_STATE && status2 !== COMMENT_STATE && status2 !== HCRC_STATE && status2 !== BUSY_STATE && status2 !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status2 === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports2.deflateInit = deflateInit; + exports2.deflateInit2 = deflateInit2; + exports2.deflateReset = deflateReset; + exports2.deflateResetKeep = deflateResetKeep; + exports2.deflateSetHeader = deflateSetHeader; + exports2.deflate = deflate2; + exports2.deflateEnd = deflateEnd; + exports2.deflateSetDictionary = deflateSetDictionary; + exports2.deflateInfo = "pako deflate (from Nodeca project)"; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/strings.js +var require_strings = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/utils/strings.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (q = 0; q < 256; q++) { + _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + } + var q; + _utf8len[254] = _utf8len[254] = 1; + exports2.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i++] = c; + } else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + var result = ""; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + exports2.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports2.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + exports2.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0; i < len; ) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports2.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js +var require_zstream = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/zstream.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + module2.exports = ZStream; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/deflate.js +var require_deflate2 = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/deflate.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var zlib_deflate = require_deflate(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + function Deflate(options) { + if (!(this instanceof Deflate)) + return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) { + opt.windowBits = -opt.windowBits; + } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) { + opt.windowBits += 16; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status2 = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + if (status2 !== Z_OK) { + throw new Error(msg[status2]); + } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") { + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + status2 = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status2 !== Z_OK) { + throw new Error(msg[status2]); + } + this._dict_set = true; + } + } + Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status2, _mode; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data === "string") { + strm.input = strings.string2buf(data); + } else if (toString.call(data) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status2 = zlib_deflate.deflate(strm, _mode); + if (status2 !== Z_STREAM_END && status2 !== Z_OK) { + this.onEnd(status2); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status2 !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status2 = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status2); + this.ended = true; + return status2 === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Deflate.prototype.onEnd = function(status2) { + if (status2 === Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status2; + this.msg = this.strm.msg; + }; + function deflate2(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) { + throw deflator.msg || msg[deflator.err]; + } + return deflator.result; + } + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate2(input, options); + } + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate2(input, options); + } + exports2.Deflate = Deflate; + exports2.deflate = deflate2; + exports2.deflateRaw = deflateRaw; + exports2.gzip = gzip; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js +var require_inffast = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inffast.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var BAD = 30; + var TYPE = 12; + module2.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last2; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last2 = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last2 && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last2 ? 5 + (last2 - _in) : 5 - (_in - last2); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + return; + }; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inftrees.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + /* Length codes 257..285 base */ + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 15, + 17, + 19, + 23, + 27, + 31, + 35, + 43, + 51, + 59, + 67, + 83, + 99, + 115, + 131, + 163, + 195, + 227, + 258, + 0, + 0 + ]; + var lext = [ + /* Length codes 257..285 extra */ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + /* Distance codes 0..29 base */ + 1, + 2, + 3, + 4, + 5, + 7, + 9, + 13, + 17, + 25, + 33, + 49, + 65, + 97, + 129, + 193, + 257, + 385, + 513, + 769, + 1025, + 1537, + 2049, + 3073, + 4097, + 6145, + 8193, + 12289, + 16385, + 24577, + 0, + 0 + ]; + var dext = [ + /* Distance codes 0..29 extra */ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root2 = 0; + var curr = 0; + var drop = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill; + var low; + var mask; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root2 = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root2 > max) { + root2 = max; + } + if (max === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root2 < min) { + root2 = min; + } + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root2; + drop = 0; + low = -1; + used = 1 << root2; + mask = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (; ; ) { + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop; + fill = 1 << curr; + min = fill; + do { + fill -= incr; + table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root2 && (huff & mask) !== low) { + if (drop === 0) { + drop = root2; + } + next += min; + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask; + table[low] = root2 << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop << 24 | 64 << 16 | 0; + } + opts.bits = root2; + return 0; + }; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js +var require_inflate = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/inflate.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var utils = require_common(); + var adler32 = require_adler32(); + var crc322 = require_crc322(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA2 = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) { + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) { + return Z_STREAM_ERROR; + } + state = new InflateState(); + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy2) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy2 >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy2) { + dist = copy2; + } + utils.arraySet(state.window, src, end - copy2, dist, state.wnext); + copy2 -= dist; + if (copy2) { + utils.arraySet(state.window, src, end - copy2, copy2, 0); + state.wnext = copy2; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + function inflate2(strm, flush2) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy2; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = ( + /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] + ); + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (; ; ) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc322(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = hold >> 8 & 1; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc322(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.time = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc322(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc322(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc322(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) { + state.head.extra = null; + } + state.mode = EXTRA2; + case EXTRA2: + if (state.flags & 1024) { + copy2 = state.length; + if (copy2 > have) { + copy2 = have; + } + if (copy2) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy2, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + } + if (state.flags & 512) { + state.check = crc322(state.check, input, copy2, next); + } + have -= copy2; + next += copy2; + state.length -= copy2; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + case NAME: + if (state.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy2 = 0; + do { + len = input[next + copy2++]; + if (state.head && len && state.length < 65536) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy2 < have); + if (state.flags & 512) { + state.check = crc322(state.check, input, copy2, next); + } + have -= copy2; + next += copy2; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + case COMMENT: + if (state.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy2 = 0; + do { + len = input[next + copy2++]; + if (state.head && len && state.length < 65536) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy2 < have); + if (state.flags & 512) { + state.check = crc322(state.check, input, copy2, next); + } + have -= copy2; + next += copy2; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + case TYPE: + if (flush2 === Z_BLOCK || flush2 === Z_TREES) { + break inf_leave; + } + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush2 === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush2 === Z_TREES) { + break inf_leave; + } + case COPY_: + state.mode = COPY; + case COPY: + copy2 = state.length; + if (copy2) { + if (copy2 > have) { + copy2 = have; + } + if (copy2 > left) { + copy2 = left; + } + if (copy2 === 0) { + break inf_leave; + } + utils.arraySet(output, input, next, copy2, put); + have -= copy2; + next += copy2; + left -= copy2; + put += copy2; + state.length -= copy2; + break; + } + state.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (; ; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy2 = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy2 = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy2 = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy2 > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy2--) { + state.lens[state.have++] = len; + } + } + } + if (state.mode === BAD) { + break; + } + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush2 === Z_TREES) { + break inf_leave; + } + case LEN_: + state.mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (; ; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + case DIST: + for (; ; ) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + case MATCH: + if (left === 0) { + break inf_leave; + } + copy2 = _out - left; + if (state.offset > copy2) { + copy2 = state.offset - copy2; + if (copy2 > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy2 > state.wnext) { + copy2 -= state.wnext; + from = state.wsize - copy2; + } else { + from = state.wnext - copy2; + } + if (copy2 > state.length) { + copy2 = state.length; + } + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy2 = state.length; + } + if (copy2 > left) { + copy2 = left; + } + left -= copy2; + state.length -= copy2; + do { + output[put++] = from_source[from++]; + } while (--copy2); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ + state.flags ? crc322(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + } + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush2 !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + state.flags ? crc322(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush2 === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if ((state.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports2.inflateReset = inflateReset; + exports2.inflateReset2 = inflateReset2; + exports2.inflateResetKeep = inflateResetKeep; + exports2.inflateInit = inflateInit; + exports2.inflateInit2 = inflateInit2; + exports2.inflate = inflate2; + exports2.inflateEnd = inflateEnd; + exports2.inflateGetHeader = inflateGetHeader; + exports2.inflateSetDictionary = inflateSetDictionary; + exports2.inflateInfo = "pako inflate (from Nodeca project)"; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/constants.js +var require_constants = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/constants.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = { + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type + }; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/zlib/gzheader.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + function GZheader() { + this.text = 0; + this.time = 0; + this.xflags = 0; + this.os = 0; + this.extra = null; + this.extra_len = 0; + this.name = ""; + this.comment = ""; + this.hcrc = 0; + this.done = false; + } + module2.exports = GZheader; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/inflate.js +var require_inflate2 = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/lib/inflate.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var zlib_inflate = require_inflate(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString = Object.prototype.toString; + function Inflate(options) { + if (!(this instanceof Inflate)) + return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { + opt.windowBits = -15; + } + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { + opt.windowBits += 32; + } + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status2 = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + if (status2 !== c.Z_OK) { + throw new Error(msg[status2]); + } + this.header = new GZheader(); + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { + status2 = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status2 !== c.Z_OK) { + throw new Error(msg[status2]); + } + } + } + } + Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status2, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data === "string") { + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status2 = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status2 === c.Z_NEED_DICT && dictionary) { + status2 = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + if (status2 === c.Z_BUF_ERROR && allowBufError === true) { + status2 = c.Z_OK; + allowBufError = false; + } + if (status2 !== c.Z_STREAM_END && status2 !== c.Z_OK) { + this.onEnd(status2); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status2 === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { + utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + } + this.onData(utf8str); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status2 !== c.Z_STREAM_END); + if (status2 === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + if (_mode === c.Z_FINISH) { + status2 = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status2); + this.ended = true; + return status2 === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Inflate.prototype.onEnd = function(status2) { + if (status2 === c.Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status2; + this.msg = this.strm.msg; + }; + function inflate2(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) { + throw inflator.msg || msg[inflator.err]; + } + return inflator.result; + } + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate2(input, options); + } + exports2.Inflate = Inflate; + exports2.inflate = inflate2; + exports2.inflateRaw = inflateRaw; + exports2.ungzip = inflate2; + } +}); + +// node_modules/.pnpm/pako@1.0.11/node_modules/pako/index.js +var require_pako = __commonJS({ + "node_modules/.pnpm/pako@1.0.11/node_modules/pako/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var assign2 = require_common().assign; + var deflate2 = require_deflate2(); + var inflate2 = require_inflate2(); + var constants = require_constants(); + var pako2 = {}; + assign2(pako2, deflate2, inflate2, constants); + module2.exports = pako2; + } +}); + +// node_modules/.pnpm/pify@4.0.1/node_modules/pify/index.js +var require_pify = __commonJS({ + "node_modules/.pnpm/pify@4.0.1/node_modules/pify/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var processFn = (fn, options) => function(...args) { + const P = options.promiseModule; + return new P((resolve, reject) => { + if (options.multiArgs) { + args.push((...result) => { + if (options.errorFirst) { + if (result[0]) { + reject(result); + } else { + result.shift(); + resolve(result); + } + } else { + resolve(result); + } + }); + } else if (options.errorFirst) { + args.push((error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + } else { + args.push(resolve); + } + fn.apply(this, args); + }); + }; + module2.exports = (input, options) => { + options = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, options); + const objType = typeof input; + if (!(input !== null && (objType === "object" || objType === "function"))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? "null" : objType}\``); + } + const filter = (key2) => { + const match = (pattern) => typeof pattern === "string" ? key2 === pattern : pattern.test(key2); + return options.include ? options.include.some(match) : !options.exclude.some(match); + }; + let ret; + if (objType === "function") { + ret = function(...args) { + return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args); + }; + } else { + ret = Object.create(Object.getPrototypeOf(input)); + } + for (const key2 in input) { + const property = input[key2]; + ret[key2] = typeof property === "function" && filter(key2) ? processFn(property, options) : property; + } + return ret; + }; + } +}); + +// node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js +var require_ignore = __commonJS({ + "node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js"(exports2, module2) { + init_polyfill_buffer(); + function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; + } + var EMPTY = ""; + var SPACE = " "; + var ESCAPE = "\\"; + var REGEX_TEST_BLANK_LINE = /^\s+$/; + var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; + var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; + var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; + var REGEX_SPLITALL_CRLF = /\r?\n/g; + var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; + var SLASH = "/"; + var TMP_KEY_IGNORE = "node-ignore"; + if (typeof Symbol !== "undefined") { + TMP_KEY_IGNORE = Symbol.for("node-ignore"); + } + var KEY_IGNORE = TMP_KEY_IGNORE; + var define2 = (object, key2, value) => Object.defineProperty(object, key2, { value }); + var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; + var RETURN_FALSE = () => false; + var sanitizeRange = (range) => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY + ); + var cleanRangeBackSlash = (slashes) => { + const { length } = slashes; + return slashes.slice(0, length - length % 2); + }; + var REPLACERS = [ + [ + // remove BOM + // TODO: + // Other similar zero-width characters? + /^\uFEFF/, + () => EMPTY + ], + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + (match) => match.indexOf("\\") === 0 ? SPACE : EMPTY + ], + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], + // Escape metacharacters + // which is written down by users but means special for regular expressions. + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + (match) => `\\${match}` + ], + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => "[^/]" + ], + // leading slash + [ + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => "^" + ], + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => "\\/" + ], + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + // '**/foo' <-> 'foo' + () => "^(?:.*\\/)?" + ], + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer() { + return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^"; + } + ], + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + // Check if it is not the last `'/**'` + (_, index2, str) => index2 + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+" + ], + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + const unescaped = p2.replace(/\\\*/g, "[^\\/]*"); + return p1 + unescaped; + } + ], + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]" + ], + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)` + ], + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 ? `${p1}[^/]+` : "[^/]*"; + return `${prefix}(?=$|\\/$)`; + } + ] + ]; + var regexCache = /* @__PURE__ */ Object.create(null); + var makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern]; + if (!source) { + source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ); + regexCache[pattern] = source; + } + return ignoreCase ? new RegExp(source, "i") : new RegExp(source); + }; + var isString = (subject) => typeof subject === "string"; + var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0; + var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF); + var IgnoreRule = class { + constructor(origin, pattern, negative, regex2) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex2; + } + }; + var createRule = (pattern, ignoreCase) => { + const origin = pattern; + let negative = false; + if (pattern.indexOf("!") === 0) { + negative = true; + pattern = pattern.substr(1); + } + pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#"); + const regex2 = makeRegex(pattern, ignoreCase); + return new IgnoreRule( + origin, + pattern, + negative, + regex2 + ); + }; + var throwError = (message, Ctor) => { + throw new Ctor(message); + }; + var checkPath = (path2, originalPath, doThrow) => { + if (!isString(path2)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ); + } + if (!path2) { + return doThrow(`path must not be empty`, TypeError); + } + if (checkPath.isNotRelative(path2)) { + const r = "`path.relative()`d"; + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ); + } + return true; + }; + var isNotRelative = (path2) => REGEX_TEST_INVALID_PATH.test(path2); + checkPath.isNotRelative = isNotRelative; + checkPath.convert = (p) => p; + var Ignore = class { + constructor({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define2(this, KEY_IGNORE, true); + this._rules = []; + this._ignoreCase = ignoreCase; + this._allowRelativePaths = allowRelativePaths; + this._initCache(); + } + _initCache() { + this._ignoreCache = /* @__PURE__ */ Object.create(null); + this._testCache = /* @__PURE__ */ Object.create(null); + } + _addPattern(pattern) { + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + // @param {Array | string | Ignore} pattern + add(pattern) { + this._added = false; + makeArray( + isString(pattern) ? splitPattern(pattern) : pattern + ).forEach(this._addPattern, this); + if (this._added) { + this._initCache(); + } + return this; + } + // legacy + addPattern(pattern) { + return this.add(pattern); + } + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + // @returns {TestResult} true if a file is ignored + _testOne(path2, checkUnignored) { + let ignored = false; + let unignored = false; + this._rules.forEach((rule) => { + const { negative } = rule; + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + const matched = rule.regex.test(path2); + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + return { + ignored, + unignored + }; + } + // @returns {TestResult} + _test(originalPath, cache, checkUnignored, slices) { + const path2 = originalPath && checkPath.convert(originalPath); + checkPath( + path2, + originalPath, + this._allowRelativePaths ? RETURN_FALSE : throwError + ); + return this._t(path2, cache, checkUnignored, slices); + } + _t(path2, cache, checkUnignored, slices) { + if (path2 in cache) { + return cache[path2]; + } + if (!slices) { + slices = path2.split(SLASH); + } + slices.pop(); + if (!slices.length) { + return cache[path2] = this._testOne(path2, checkUnignored); + } + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ); + return cache[path2] = parent.ignored ? parent : this._testOne(path2, checkUnignored); + } + ignores(path2) { + return this._test(path2, this._ignoreCache, false).ignored; + } + createFilter() { + return (path2) => !this.ignores(path2); + } + filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } + // @returns {TestResult} + test(path2) { + return this._test(path2, this._testCache, true); + } + }; + var factory = (options) => new Ignore(options); + var isPathValid = (path2) => checkPath(path2 && checkPath.convert(path2), path2, RETURN_FALSE); + factory.isPathValid = isPathValid; + factory.default = factory; + module2.exports = factory; + if ( + // Detect `process` so that it can run in browsers. + typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32") + ) { + const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/"); + checkPath.convert = makePosix; + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = (path2) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path2) || isNotRelative(path2); + } + } +}); + +// node_modules/.pnpm/clean-git-ref@2.0.1/node_modules/clean-git-ref/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/.pnpm/clean-git-ref@2.0.1/node_modules/clean-git-ref/lib/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function replaceAll(str, search, replacement) { + search = search instanceof RegExp ? search : new RegExp(escapeRegExp(search), "g"); + return str.replace(search, replacement); + } + var CleanGitRef = { + clean: function clean(value) { + if (typeof value !== "string") { + throw new Error("Expected a string, received: " + value); + } + value = replaceAll(value, "./", "/"); + value = replaceAll(value, "..", "."); + value = replaceAll(value, " ", "-"); + value = replaceAll(value, /^[~^:?*\\\-]/g, ""); + value = replaceAll(value, /[~^:?*\\]/g, "-"); + value = replaceAll(value, /[~^:?*\\\-]$/g, ""); + value = replaceAll(value, "@{", "-"); + value = replaceAll(value, /\.$/g, ""); + value = replaceAll(value, /\/$/g, ""); + value = replaceAll(value, /\.lock$/g, ""); + return value; + } + }; + module2.exports = CleanGitRef; + } +}); + +// node_modules/.pnpm/diff3@0.0.3/node_modules/diff3/onp.js +var require_onp = __commonJS({ + "node_modules/.pnpm/diff3@0.0.3/node_modules/diff3/onp.js"(exports2, module2) { + init_polyfill_buffer(); + module2.exports = function(a_, b_) { + var a = a_, b = b_, m = a.length, n = b.length, reverse = false, ed = null, offset = m + 1, path2 = [], pathposi = [], ses = [], lcs = "", SES_DELETE = -1, SES_COMMON = 0, SES_ADD = 1; + var tmp1, tmp2; + var init3 = function() { + if (m >= n) { + tmp1 = a; + tmp2 = m; + a = b; + b = tmp1; + m = n; + n = tmp2; + reverse = true; + offset = m + 1; + } + }; + var P = function(x, y, k) { + return { + "x": x, + "y": y, + "k": k + }; + }; + var seselem = function(elem, t) { + return { + "elem": elem, + "t": t + }; + }; + var snake = function(k, p, pp) { + var r, x, y; + if (p > pp) { + r = path2[k - 1 + offset]; + } else { + r = path2[k + 1 + offset]; + } + y = Math.max(p, pp); + x = y - k; + while (x < m && y < n && a[x] === b[y]) { + ++x; + ++y; + } + path2[k + offset] = pathposi.length; + pathposi[pathposi.length] = new P(x, y, r); + return y; + }; + var recordseq = function(epc) { + var x_idx, y_idx, px_idx, py_idx, i; + x_idx = y_idx = 1; + px_idx = py_idx = 0; + for (i = epc.length - 1; i >= 0; --i) { + while (px_idx < epc[i].x || py_idx < epc[i].y) { + if (epc[i].y - epc[i].x > py_idx - px_idx) { + if (reverse) { + ses[ses.length] = new seselem(b[py_idx], SES_DELETE); + } else { + ses[ses.length] = new seselem(b[py_idx], SES_ADD); + } + ++y_idx; + ++py_idx; + } else if (epc[i].y - epc[i].x < py_idx - px_idx) { + if (reverse) { + ses[ses.length] = new seselem(a[px_idx], SES_ADD); + } else { + ses[ses.length] = new seselem(a[px_idx], SES_DELETE); + } + ++x_idx; + ++px_idx; + } else { + ses[ses.length] = new seselem(a[px_idx], SES_COMMON); + lcs += a[px_idx]; + ++x_idx; + ++y_idx; + ++px_idx; + ++py_idx; + } + } + } + }; + init3(); + return { + SES_DELETE: -1, + SES_COMMON: 0, + SES_ADD: 1, + editdistance: function() { + return ed; + }, + getlcs: function() { + return lcs; + }, + getses: function() { + return ses; + }, + compose: function() { + var delta, size, fp, p, r, epc, i, k; + delta = n - m; + size = m + n + 3; + fp = {}; + for (i = 0; i < size; ++i) { + fp[i] = -1; + path2[i] = -1; + } + p = -1; + do { + ++p; + for (k = -p; k <= delta - 1; ++k) { + fp[k + offset] = snake(k, fp[k - 1 + offset] + 1, fp[k + 1 + offset]); + } + for (k = delta + p; k >= delta + 1; --k) { + fp[k + offset] = snake(k, fp[k - 1 + offset] + 1, fp[k + 1 + offset]); + } + fp[delta + offset] = snake(delta, fp[delta - 1 + offset] + 1, fp[delta + 1 + offset]); + } while (fp[delta + offset] !== n); + ed = delta + 2 * p; + r = path2[delta + offset]; + epc = []; + while (r !== -1) { + epc[epc.length] = new P(pathposi[r].x, pathposi[r].y, null); + r = pathposi[r].k; + } + recordseq(epc); + } + }; + }; + } +}); + +// node_modules/.pnpm/diff3@0.0.3/node_modules/diff3/diff3.js +var require_diff3 = __commonJS({ + "node_modules/.pnpm/diff3@0.0.3/node_modules/diff3/diff3.js"(exports2, module2) { + init_polyfill_buffer(); + var onp = require_onp(); + function longestCommonSubsequence(file1, file2) { + var diff3 = new onp(file1, file2); + diff3.compose(); + var ses = diff3.getses(); + var root2; + var prev; + var file1RevIdx = file1.length - 1, file2RevIdx = file2.length - 1; + for (var i = ses.length - 1; i >= 0; --i) { + if (ses[i].t === diff3.SES_COMMON) { + if (prev) { + prev.chain = { + file1index: file1RevIdx, + file2index: file2RevIdx, + chain: null + }; + prev = prev.chain; + } else { + root2 = { + file1index: file1RevIdx, + file2index: file2RevIdx, + chain: null + }; + prev = root2; + } + file1RevIdx--; + file2RevIdx--; + } else if (ses[i].t === diff3.SES_DELETE) { + file1RevIdx--; + } else if (ses[i].t === diff3.SES_ADD) { + file2RevIdx--; + } + } + var tail = { + file1index: -1, + file2index: -1, + chain: null + }; + if (!prev) { + return tail; + } + prev.chain = tail; + return root2; + } + function diffIndices(file1, file2) { + var result = []; + var tail1 = file1.length; + var tail2 = file2.length; + for (var candidate = longestCommonSubsequence(file1, file2); candidate !== null; candidate = candidate.chain) { + var mismatchLength1 = tail1 - candidate.file1index - 1; + var mismatchLength2 = tail2 - candidate.file2index - 1; + tail1 = candidate.file1index; + tail2 = candidate.file2index; + if (mismatchLength1 || mismatchLength2) { + result.push({ + file1: [tail1 + 1, mismatchLength1], + file2: [tail2 + 1, mismatchLength2] + }); + } + } + result.reverse(); + return result; + } + function diff3MergeIndices(a, o, b) { + var i; + var m1 = diffIndices(o, a); + var m2 = diffIndices(o, b); + var hunks = []; + function addHunk(h, side2) { + hunks.push([h.file1[0], side2, h.file1[1], h.file2[0], h.file2[1]]); + } + for (i = 0; i < m1.length; i++) { + addHunk(m1[i], 0); + } + for (i = 0; i < m2.length; i++) { + addHunk(m2[i], 2); + } + hunks.sort(function(x, y) { + return x[0] - y[0]; + }); + var result = []; + var commonOffset = 0; + function copyCommon(targetOffset) { + if (targetOffset > commonOffset) { + result.push([1, commonOffset, targetOffset - commonOffset]); + commonOffset = targetOffset; + } + } + for (var hunkIndex = 0; hunkIndex < hunks.length; hunkIndex++) { + var firstHunkIndex = hunkIndex; + var hunk = hunks[hunkIndex]; + var regionLhs = hunk[0]; + var regionRhs = regionLhs + hunk[2]; + while (hunkIndex < hunks.length - 1) { + var maybeOverlapping = hunks[hunkIndex + 1]; + var maybeLhs = maybeOverlapping[0]; + if (maybeLhs > regionRhs) + break; + regionRhs = Math.max(regionRhs, maybeLhs + maybeOverlapping[2]); + hunkIndex++; + } + copyCommon(regionLhs); + if (firstHunkIndex == hunkIndex) { + if (hunk[4] > 0) { + result.push([hunk[1], hunk[3], hunk[4]]); + } + } else { + var regions = { + 0: [a.length, -1, o.length, -1], + 2: [b.length, -1, o.length, -1] + }; + for (i = firstHunkIndex; i <= hunkIndex; i++) { + hunk = hunks[i]; + var side = hunk[1]; + var r = regions[side]; + var oLhs = hunk[0]; + var oRhs = oLhs + hunk[2]; + var abLhs = hunk[3]; + var abRhs = abLhs + hunk[4]; + r[0] = Math.min(abLhs, r[0]); + r[1] = Math.max(abRhs, r[1]); + r[2] = Math.min(oLhs, r[2]); + r[3] = Math.max(oRhs, r[3]); + } + var aLhs = regions[0][0] + (regionLhs - regions[0][2]); + var aRhs = regions[0][1] + (regionRhs - regions[0][3]); + var bLhs = regions[2][0] + (regionLhs - regions[2][2]); + var bRhs = regions[2][1] + (regionRhs - regions[2][3]); + result.push([ + -1, + aLhs, + aRhs - aLhs, + regionLhs, + regionRhs - regionLhs, + bLhs, + bRhs - bLhs + ]); + } + commonOffset = regionRhs; + } + copyCommon(o.length); + return result; + } + function diff3Merge2(a, o, b) { + var result = []; + var files = [a, o, b]; + var indices = diff3MergeIndices(a, o, b); + var okLines = []; + function flushOk() { + if (okLines.length) { + result.push({ + ok: okLines + }); + } + okLines = []; + } + function pushOk(xs) { + for (var j = 0; j < xs.length; j++) { + okLines.push(xs[j]); + } + } + function isTrueConflict(rec) { + if (rec[2] != rec[6]) + return true; + var aoff = rec[1]; + var boff = rec[5]; + for (var j = 0; j < rec[2]; j++) { + if (a[j + aoff] != b[j + boff]) + return true; + } + return false; + } + for (var i = 0; i < indices.length; i++) { + var x = indices[i]; + var side = x[0]; + if (side == -1) { + if (!isTrueConflict(x)) { + pushOk(files[0].slice(x[1], x[1] + x[2])); + } else { + flushOk(); + result.push({ + conflict: { + a: a.slice(x[1], x[1] + x[2]), + aIndex: x[1], + o: o.slice(x[3], x[3] + x[4]), + oIndex: x[3], + b: b.slice(x[5], x[5] + x[6]), + bIndex: x[5] + } + }); + } + } else { + pushOk(files[side].slice(x[1], x[1] + x[2])); + } + } + flushOk(); + return result; + } + module2.exports = diff3Merge2; + } +}); + +// node_modules/.pnpm/ms@2.1.2/node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/.pnpm/ms@2.1.2/node_modules/ms/index.js"(exports2, module2) { + init_polyfill_buffer(); + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse2(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse2(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/.pnpm/debug@4.3.4_supports-color@9.4.0/node_modules/debug/src/common.js +var require_common2 = __commonJS({ + "node_modules/.pnpm/debug@4.3.4_supports-color@9.4.0/node_modules/debug/src/common.js"(exports2, module2) { + init_polyfill_buffer(); + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key2) => { + createDebug[key2] = env[key2]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug3(...args) { + if (!debug3.enabled) { + return; + } + const self2 = debug3; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug3.namespace = namespace; + debug3.useColors = createDebug.useColors(); + debug3.color = createDebug.selectColor(namespace); + debug3.extend = extend; + debug3.destroy = createDebug.destroy; + Object.defineProperty(debug3, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug3); + } + return debug3; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + continue; + } + namespaces = split[i].replace(/\*/g, ".*?"); + if (namespaces[0] === "-") { + createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$")); + } else { + createDebug.names.push(new RegExp("^" + namespaces + "$")); + } + } + } + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + if (name[name.length - 1] === "*") { + return true; + } + let i; + let len; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + return false; + } + function toNamespace(regexp) { + return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*"); + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module2.exports = setup; + } +}); + +// node_modules/.pnpm/debug@4.3.4_supports-color@9.4.0/node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/.pnpm/debug@4.3.4_supports-color@9.4.0/node_modules/debug/src/browser.js"(exports2, module2) { + init_polyfill_buffer(); + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error) { + } + } + function load() { + let r; + try { + r = exports2.storage.getItem("debug"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + module2.exports = require_common2()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + } +}); + +// node_modules/.pnpm/@kwsites+file-exists@1.1.1_supports-color@9.4.0/node_modules/@kwsites/file-exists/dist/src/index.js +var require_src = __commonJS({ + "node_modules/.pnpm/@kwsites+file-exists@1.1.1_supports-color@9.4.0/node_modules/@kwsites/file-exists/dist/src/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + var __importDefault = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + var fs_1 = require("fs"); + var debug_1 = __importDefault(require_browser()); + var log2 = debug_1.default("@kwsites/file-exists"); + function check(path2, isFile, isDirectory) { + log2(`checking %s`, path2); + try { + const stat = fs_1.statSync(path2); + if (stat.isFile() && isFile) { + log2(`[OK] path represents a file`); + return true; + } + if (stat.isDirectory() && isDirectory) { + log2(`[OK] path represents a directory`); + return true; + } + log2(`[FAIL] path represents something other than a file or directory`); + return false; + } catch (e) { + if (e.code === "ENOENT") { + log2(`[FAIL] path is not accessible: %o`, e); + return false; + } + log2(`[FATAL] %o`, e); + throw e; + } + } + function exists2(path2, type = exports2.READABLE) { + return check(path2, (type & exports2.FILE) > 0, (type & exports2.FOLDER) > 0); + } + exports2.exists = exists2; + exports2.FILE = 1; + exports2.FOLDER = 2; + exports2.READABLE = exports2.FILE + exports2.FOLDER; + } +}); + +// node_modules/.pnpm/@kwsites+file-exists@1.1.1_supports-color@9.4.0/node_modules/@kwsites/file-exists/dist/index.js +var require_dist = __commonJS({ + "node_modules/.pnpm/@kwsites+file-exists@1.1.1_supports-color@9.4.0/node_modules/@kwsites/file-exists/dist/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + function __export3(m) { + for (var p in m) + if (!exports2.hasOwnProperty(p)) + exports2[p] = m[p]; + } + Object.defineProperty(exports2, "__esModule", { value: true }); + __export3(require_src()); + } +}); + +// node_modules/.pnpm/@kwsites+promise-deferred@1.1.1/node_modules/@kwsites/promise-deferred/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/.pnpm/@kwsites+promise-deferred@1.1.1/node_modules/@kwsites/promise-deferred/dist/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createDeferred = exports2.deferred = void 0; + function deferred2() { + let done; + let fail; + let status2 = "pending"; + const promise2 = new Promise((_done, _fail) => { + done = _done; + fail = _fail; + }); + return { + promise: promise2, + done(result) { + if (status2 === "pending") { + status2 = "resolved"; + done(result); + } + }, + fail(error) { + if (status2 === "pending") { + status2 = "rejected"; + fail(error); + } + }, + get fulfilled() { + return status2 !== "pending"; + }, + get status() { + return status2; + } + }; + } + exports2.deferred = deferred2; + exports2.createDeferred = deferred2; + exports2.default = deferred2; + } +}); + +// node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js +var require_color_name = __commonJS({ + "node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// node_modules/.pnpm/css-unit-converter@1.1.2/node_modules/css-unit-converter/index.js +var require_css_unit_converter = __commonJS({ + "node_modules/.pnpm/css-unit-converter@1.1.2/node_modules/css-unit-converter/index.js"(exports2, module2) { + init_polyfill_buffer(); + var conversions = { + // length + "px": { + "px": 1, + "cm": 96 / 2.54, + "mm": 96 / 25.4, + "in": 96, + "pt": 96 / 72, + "pc": 16 + }, + "cm": { + "px": 2.54 / 96, + "cm": 1, + "mm": 0.1, + "in": 2.54, + "pt": 2.54 / 72, + "pc": 2.54 / 6 + }, + "mm": { + "px": 25.4 / 96, + "cm": 10, + "mm": 1, + "in": 25.4, + "pt": 25.4 / 72, + "pc": 25.4 / 6 + }, + "in": { + "px": 1 / 96, + "cm": 1 / 2.54, + "mm": 1 / 25.4, + "in": 1, + "pt": 1 / 72, + "pc": 1 / 6 + }, + "pt": { + "px": 0.75, + "cm": 72 / 2.54, + "mm": 72 / 25.4, + "in": 72, + "pt": 1, + "pc": 12 + }, + "pc": { + "px": 6 / 96, + "cm": 6 / 2.54, + "mm": 6 / 25.4, + "in": 6, + "pt": 6 / 72, + "pc": 1 + }, + // angle + "deg": { + "deg": 1, + "grad": 0.9, + "rad": 180 / Math.PI, + "turn": 360 + }, + "grad": { + "deg": 400 / 360, + "grad": 1, + "rad": 200 / Math.PI, + "turn": 400 + }, + "rad": { + "deg": Math.PI / 180, + "grad": Math.PI / 200, + "rad": 1, + "turn": Math.PI * 2 + }, + "turn": { + "deg": 1 / 360, + "grad": 1 / 400, + "rad": 0.5 / Math.PI, + "turn": 1 + }, + // time + "s": { + "s": 1, + "ms": 1 / 1e3 + }, + "ms": { + "s": 1e3, + "ms": 1 + }, + // frequency + "Hz": { + "Hz": 1, + "kHz": 1e3 + }, + "kHz": { + "Hz": 1 / 1e3, + "kHz": 1 + }, + // resolution + "dpi": { + "dpi": 1, + "dpcm": 1 / 2.54, + "dppx": 1 / 96 + }, + "dpcm": { + "dpi": 2.54, + "dpcm": 1, + "dppx": 2.54 / 96 + }, + "dppx": { + "dpi": 96, + "dpcm": 96 / 2.54, + "dppx": 1 + } + }; + module2.exports = function(value, sourceUnit, targetUnit, precision) { + if (!conversions.hasOwnProperty(targetUnit)) + throw new Error("Cannot convert to " + targetUnit); + if (!conversions[targetUnit].hasOwnProperty(sourceUnit)) + throw new Error("Cannot convert from " + sourceUnit + " to " + targetUnit); + var converted = conversions[targetUnit][sourceUnit] * value; + if (precision !== false) { + precision = Math.pow(10, parseInt(precision) || 5); + return Math.round(converted * precision) / precision; + } + return converted; + }; + } +}); + +// node_modules/.pnpm/css-color-converter@2.0.0/node_modules/css-color-converter/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/.pnpm/css-color-converter@2.0.0/node_modules/css-color-converter/lib/index.js"(exports2) { + "use strict"; + init_polyfill_buffer(); + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.fromRgba = fromRgba; + exports2.fromRgb = fromRgb; + exports2.fromHsla = fromHsla; + exports2.fromHsl = fromHsl; + exports2.fromString = fromString2; + exports2["default"] = void 0; + var _colorName = _interopRequireDefault(require_color_name()); + var _cssUnitConverter = _interopRequireDefault(require_css_unit_converter()); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { "default": obj }; + } + function _classCallCheck(instance10, Constructor) { + if (!(instance10 instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + return Constructor; + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray2(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _unsupportedIterableToArray2(o, minLen) { + if (!o) + return; + if (typeof o === "string") + return _arrayLikeToArray2(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) + n = o.constructor.name; + if (n === "Map" || n === "Set") + return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) + return _arrayLikeToArray2(o, minLen); + } + function _arrayLikeToArray2(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) + return; + var _arr = []; + var _n = true; + var _d = false; + var _e = void 0; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) + break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) + _i["return"](); + } finally { + if (_d) + throw _e; + } + } + return _arr; + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) + return arr; + } + var hex = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?$/; + var shortHex = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])?$/; + var rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(0|1|0?\.\d+|\d+%))?\s*\)$/; + var rgbfn = /^rgba?\(\s*(\d+)\s+(\d+)\s+(\d+)(?:\s*\/\s*(0|1|0?\.\d+|\d+%))?\s*\)$/; + var rgbperc = /^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(0|1|0?\.\d+|\d+%))?\s*\)$/; + var rgbpercfn = /^rgba?\(\s*(\d+%)\s+(\d+%)\s+(\d+%)(?:\s*\/\s*(0|1|0?\.\d+|\d+%))?\s*\)$/; + var hsl = /^hsla?\(\s*(\d+)(deg|rad|grad|turn)?\s*,\s*(\d+)%\s*,\s*(\d+)%(?:\s*,\s*(0|1|0?\.\d+|\d+%))?\s*\)$/; + function contains2(haystack, needle) { + return haystack.indexOf(needle) > -1; + } + function rgbToHsl(r, g, b) { + var rprim = r / 255; + var gprim = g / 255; + var bprim = b / 255; + var cmax = Math.max(rprim, gprim, bprim); + var cmin = Math.min(rprim, gprim, bprim); + var delta = cmax - cmin; + var l = (cmax + cmin) / 2; + if (delta === 0) { + return [0, 0, l * 100]; + } + var s = delta / (1 - Math.abs(2 * l - 1)); + var h = function() { + switch (cmax) { + case rprim: { + return (gprim - bprim) / delta % 6; + } + case gprim: { + return (bprim - rprim) / delta + 2; + } + default: { + return (rprim - gprim) / delta + 4; + } + } + }(); + return [h * 60, s * 100, l * 100]; + } + function hslToRgb(h, s, l) { + var hprim = h / 60; + var sprim = s / 100; + var lprim = l / 100; + var c = (1 - Math.abs(2 * lprim - 1)) * sprim; + var x = c * (1 - Math.abs(hprim % 2 - 1)); + var m = lprim - c / 2; + var _ref = function() { + if (hprim < 1) + return [c, x, 0]; + if (hprim < 2) + return [x, c, 0]; + if (hprim < 3) + return [0, c, x]; + if (hprim < 4) + return [0, x, c]; + if (hprim < 5) + return [x, 0, c]; + return [c, 0, x]; + }(), _ref2 = _slicedToArray(_ref, 3), rprim = _ref2[0], gprim = _ref2[1], bprim = _ref2[2]; + return [(rprim + m) * 255, (gprim + m) * 255, (bprim + m) * 255]; + } + var Color = /* @__PURE__ */ function() { + function Color2(_ref3) { + var _ref4 = _slicedToArray(_ref3, 4), r = _ref4[0], g = _ref4[1], b = _ref4[2], a = _ref4[3]; + _classCallCheck(this, Color2); + this.values = [Math.max(Math.min(parseInt(r, 10), 255), 0), Math.max(Math.min(parseInt(g, 10), 255), 0), Math.max(Math.min(parseInt(b, 10), 255), 0), a == null ? 1 : Math.max(Math.min(parseFloat(a), 255), 0)]; + } + _createClass(Color2, [{ + key: "toRgbString", + value: function toRgbString() { + var _this$values = _slicedToArray(this.values, 4), r = _this$values[0], g = _this$values[1], b = _this$values[2], a = _this$values[3]; + if (a === 1) { + return "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")"); + } + return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(a, ")"); + } + }, { + key: "toHslString", + value: function toHslString() { + var _this$toHslaArray = this.toHslaArray(), _this$toHslaArray2 = _slicedToArray(_this$toHslaArray, 4), h = _this$toHslaArray2[0], s = _this$toHslaArray2[1], l = _this$toHslaArray2[2], a = _this$toHslaArray2[3]; + if (a === 1) { + return "hsl(".concat(h, ", ").concat(s, "%, ").concat(l, "%)"); + } + return "hsla(".concat(h, ", ").concat(s, "%, ").concat(l, "%, ").concat(a, ")"); + } + }, { + key: "toHexString", + value: function toHexString() { + var _this$values2 = _slicedToArray(this.values, 4), r = _this$values2[0], g = _this$values2[1], b = _this$values2[2], a = _this$values2[3]; + r = Number(r).toString(16).padStart(2, "0"); + g = Number(g).toString(16).padStart(2, "0"); + b = Number(b).toString(16).padStart(2, "0"); + a = a < 1 ? parseInt(a * 255, 10).toString(16).padStart(2, "0") : ""; + return "#".concat(r).concat(g).concat(b).concat(a); + } + }, { + key: "toRgbaArray", + value: function toRgbaArray() { + return this.values; + } + }, { + key: "toHslaArray", + value: function toHslaArray() { + var _this$values3 = _slicedToArray(this.values, 4), r = _this$values3[0], g = _this$values3[1], b = _this$values3[2], a = _this$values3[3]; + var _rgbToHsl = rgbToHsl(r, g, b), _rgbToHsl2 = _slicedToArray(_rgbToHsl, 3), h = _rgbToHsl2[0], s = _rgbToHsl2[1], l = _rgbToHsl2[2]; + return [h, s, l, a]; + } + }]); + return Color2; + }(); + function fromRgba(_ref5) { + var _ref6 = _slicedToArray(_ref5, 4), r = _ref6[0], g = _ref6[1], b = _ref6[2], a = _ref6[3]; + return new Color([r, g, b, a]); + } + function fromRgb(_ref7) { + var _ref8 = _slicedToArray(_ref7, 3), r = _ref8[0], g = _ref8[1], b = _ref8[2]; + return fromRgba([r, g, b, 1]); + } + function fromHsla(_ref9) { + var _ref10 = _slicedToArray(_ref9, 4), h = _ref10[0], s = _ref10[1], l = _ref10[2], a = _ref10[3]; + var _hslToRgb = hslToRgb(h, s, l), _hslToRgb2 = _slicedToArray(_hslToRgb, 3), r = _hslToRgb2[0], g = _hslToRgb2[1], b = _hslToRgb2[2]; + return fromRgba([r, g, b, a]); + } + function fromHsl(_ref11) { + var _ref12 = _slicedToArray(_ref11, 3), h = _ref12[0], s = _ref12[1], l = _ref12[2]; + return fromHsla([h, s, l, 1]); + } + function fromHexString(str) { + var _ref13 = hex.exec(str) || shortHex.exec(str), _ref14 = _slicedToArray(_ref13, 5), r = _ref14[1], g = _ref14[2], b = _ref14[3], a = _ref14[4]; + r = parseInt(r.length < 2 ? r.repeat(2) : r, 16); + g = parseInt(g.length < 2 ? g.repeat(2) : g, 16); + b = parseInt(b.length < 2 ? b.repeat(2) : b, 16); + a = a && (parseInt(a.length < 2 ? a.repeat(2) : a, 16) / 255).toPrecision(1) || 1; + return fromRgba([r, g, b, a]); + } + function fromRgbString(str) { + var _ref15 = rgb.exec(str) || rgbperc.exec(str) || rgbfn.exec(str) || rgbpercfn.exec(str), _ref16 = _slicedToArray(_ref15, 5), r = _ref16[1], g = _ref16[2], b = _ref16[3], a = _ref16[4]; + r = contains2(r, "%") ? parseInt(r, 10) * 255 / 100 : parseInt(r, 10); + g = contains2(g, "%") ? parseInt(g, 10) * 255 / 100 : parseInt(g, 10); + b = contains2(b, "%") > 0 ? parseInt(b, 10) * 255 / 100 : parseInt(b, 10); + a = a === void 0 ? 1 : parseFloat(a) / (contains2(a, "%") ? 100 : 1); + return fromRgba([r, g, b, a]); + } + function fromHslString(str) { + var _hsl$exec = hsl.exec(str), _hsl$exec2 = _slicedToArray(_hsl$exec, 6), h = _hsl$exec2[1], unit = _hsl$exec2[2], s = _hsl$exec2[3], l = _hsl$exec2[4], a = _hsl$exec2[5]; + unit = unit || "deg"; + h = (0, _cssUnitConverter["default"])(parseFloat(h), unit, "deg"); + s = parseFloat(s); + l = parseFloat(l); + a = a === void 0 ? 1 : parseFloat(a) / (contains2(a, "%") ? 100 : 1); + return fromHsla([h, s, l, a]); + } + function fromString2(str) { + if (_colorName["default"][str]) { + return fromRgb(_colorName["default"][str]); + } + if (hex.test(str) || shortHex.test(str)) { + return fromHexString(str); + } + if (rgb.test(str) || rgbperc.test(str) || rgbfn.test(str) || rgbpercfn.test(str)) { + return fromRgbString(str); + } + if (hsl.test(str)) { + return fromHslString(str); + } + return null; + } + var _default = { + fromString: fromString2, + fromRgb, + fromRgba, + fromHsl, + fromHsla + }; + exports2["default"] = _default; + } +}); + +// node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/isArguments.js +var require_isArguments = __commonJS({ + "node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/isArguments.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var toStr = Object.prototype.toString; + module2.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === "[object Arguments]"; + if (!isArgs) { + isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr.call(value.callee) === "[object Function]"; + } + return isArgs; + }; + } +}); + +// node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/implementation.js +var require_implementation = __commonJS({ + "node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/implementation.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var keysShim; + if (!Object.keys) { + has = Object.prototype.hasOwnProperty; + toStr = Object.prototype.toString; + isArgs = require_isArguments(); + isEnumerable = Object.prototype.propertyIsEnumerable; + hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString"); + hasProtoEnumBug = isEnumerable.call(function() { + }, "prototype"); + dontEnums = [ + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "constructor" + ]; + equalsConstructorPrototype = function(o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + hasAutomationEqualityBug = function() { + if (typeof window === "undefined") { + return false; + } + for (var k in window) { + try { + if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }(); + equalsConstructorPrototypeIfNotBuggy = function(o) { + if (typeof window === "undefined" || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + keysShim = function keys(object) { + var isObject2 = object !== null && typeof object === "object"; + var isFunction2 = toStr.call(object) === "[object Function]"; + var isArguments = isArgs(object); + var isString = isObject2 && toStr.call(object) === "[object String]"; + var theKeys = []; + if (!isObject2 && !isFunction2 && !isArguments) { + throw new TypeError("Object.keys called on a non-object"); + } + var skipProto = hasProtoEnumBug && isFunction2; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === "prototype") && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; + } + var has; + var toStr; + var isArgs; + var isEnumerable; + var hasDontEnumBug; + var hasProtoEnumBug; + var dontEnums; + var equalsConstructorPrototype; + var excludedKeys; + var hasAutomationEqualityBug; + var equalsConstructorPrototypeIfNotBuggy; + module2.exports = keysShim; + } +}); + +// node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/index.js +var require_object_keys = __commonJS({ + "node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var slice = Array.prototype.slice; + var isArgs = require_isArguments(); + var origKeys = Object.keys; + var keysShim = origKeys ? function keys(o) { + return origKeys(o); + } : require_implementation(); + var originalKeys = Object.keys; + keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = function() { + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; + }; + module2.exports = keysShim; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js +var require_es_errors = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = Error; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js +var require_eval = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = EvalError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js +var require_range = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = RangeError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js +var require_ref = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = ReferenceError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js +var require_syntax = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = SyntaxError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js +var require_type = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = TypeError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js +var require_uri = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = URIError; + } +}); + +// node_modules/.pnpm/has-symbols@1.0.3/node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/.pnpm/has-symbols@1.0.3/node_modules/has-symbols/shams.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + module2.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/.pnpm/has-symbols@1.0.3/node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/.pnpm/has-symbols@1.0.3/node_modules/has-symbols/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module2.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + } +}); + +// node_modules/.pnpm/has-proto@1.0.1/node_modules/has-proto/index.js +var require_has_proto = __commonJS({ + "node_modules/.pnpm/has-proto@1.0.1/node_modules/has-proto/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var test = { + foo: {} + }; + var $Object = Object; + module2.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); + }; + } +}); + +// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js +var require_implementation2 = __commonJS({ + "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a, b) { + var arr = []; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + module2.exports = function bind(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = "$" + i; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + } +}); + +// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var implementation = require_implementation2(); + module2.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/.pnpm/hasown@2.0.1/node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/.pnpm/hasown@2.0.1/node_modules/hasown/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind = require_function_bind(); + module2.exports = bind.call(call, $hasOwn); + } +}); + +// node_modules/.pnpm/get-intrinsic@1.2.4/node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/.pnpm/get-intrinsic@1.2.4/node_modules/get-intrinsic/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var undefined2; + var $Error = require_es_errors(); + var $EvalError = require_eval(); + var $RangeError = require_range(); + var $ReferenceError = require_ref(); + var $SyntaxError = require_syntax(); + var $TypeError = require_type(); + var $URIError = require_uri(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e) { + } + }; + var $gOPD = Object.getOwnPropertyDescriptor; + if ($gOPD) { + try { + $gOPD({}, ""); + } catch (e) { + $gOPD = null; + } + } + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var hasProto = require_has_proto()(); + var getProto = Object.getPrototypeOf || (hasProto ? function(x) { + return x.__proto__; + } : null); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": Object, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet + }; + if (getProto) { + try { + null.error; + } catch (e) { + errorProto = getProto(getProto(e)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var errorProto; + var doEval = function doEval2(name) { + var value; + if (name === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + INTRINSICS[name] = value; + return value; + }; + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind.call(Function.call, Array.prototype.concat); + var $spliceApply = bind.call(Function.apply, Array.prototype.splice); + var $replace = bind.call(Function.call, String.prototype.replace); + var $strSlice = bind.call(Function.call, String.prototype.slice); + var $exec = bind.call(Function.call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string) { + var first2 = $strSlice(string, 0, 1); + var last2 = $strSlice(string, -1); + if (first2 === "%" && last2 !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last2 === "%" && first2 !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string, rePropName, function(match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name + " does not exist!"); + }; + module2.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== "string" || name.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first2 = $strSlice(part, 0, 1); + var last2 = $strSlice(part, -1); + if ((first2 === '"' || first2 === "'" || first2 === "`" || (last2 === '"' || last2 === "'" || last2 === "`")) && first2 !== last2) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); + } + return void 0; + } + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + } +}); + +// node_modules/.pnpm/has-property-descriptors@1.0.1/node_modules/has-property-descriptors/index.js +var require_has_property_descriptors = __commonJS({ + "node_modules/.pnpm/has-property-descriptors@1.0.1/node_modules/has-property-descriptors/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasPropertyDescriptors = function hasPropertyDescriptors2() { + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + return true; + } catch (e) { + return false; + } + } + return false; + }; + hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + if (!hasPropertyDescriptors()) { + return null; + } + try { + return $defineProperty([], "length", { value: 1 }).length !== 1; + } catch (e) { + return true; + } + }; + module2.exports = hasPropertyDescriptors; + } +}); + +// node_modules/.pnpm/gopd@1.0.1/node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/.pnpm/gopd@1.0.1/node_modules/gopd/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e) { + $gOPD = null; + } + } + module2.exports = $gOPD; + } +}); + +// node_modules/.pnpm/define-data-property@1.1.2/node_modules/define-data-property/index.js +var require_define_data_property = __commonJS({ + "node_modules/.pnpm/define-data-property@1.1.2/node_modules/define-data-property/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var hasPropertyDescriptors = require_has_property_descriptors()(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = hasPropertyDescriptors && GetIntrinsic("%Object.defineProperty%", true); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = false; + } + } + var $SyntaxError = require_syntax(); + var $TypeError = require_type(); + var gopd = require_gopd(); + module2.exports = function defineDataProperty(obj, property, value) { + if (!obj || typeof obj !== "object" && typeof obj !== "function") { + throw new $TypeError("`obj` must be an object or a function`"); + } + if (typeof property !== "string" && typeof property !== "symbol") { + throw new $TypeError("`property` must be a string or a symbol`"); + } + if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { + throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); + } + if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { + throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); + } + if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { + throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); + } + if (arguments.length > 6 && typeof arguments[6] !== "boolean") { + throw new $TypeError("`loose`, if provided, must be a boolean"); + } + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + var desc = !!gopd && gopd(obj, property); + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { + obj[property] = value; + } else { + throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); + } + }; + } +}); + +// node_modules/.pnpm/define-properties@1.2.1/node_modules/define-properties/index.js +var require_define_properties = __commonJS({ + "node_modules/.pnpm/define-properties@1.2.1/node_modules/define-properties/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var keys = require_object_keys(); + var hasSymbols = typeof Symbol === "function" && typeof Symbol("foo") === "symbol"; + var toStr = Object.prototype.toString; + var concat = Array.prototype.concat; + var defineDataProperty = require_define_data_property(); + var isFunction2 = function(fn) { + return typeof fn === "function" && toStr.call(fn) === "[object Function]"; + }; + var supportsDescriptors = require_has_property_descriptors()(); + var defineProperty = function(object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction2(predicate) || !predicate()) { + return; + } + } + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } + }; + var defineProperties = function(object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } + }; + defineProperties.supportsDescriptors = !!supportsDescriptors; + module2.exports = defineProperties; + } +}); + +// node_modules/.pnpm/set-function-length@1.2.1/node_modules/set-function-length/index.js +var require_set_function_length = __commonJS({ + "node_modules/.pnpm/set-function-length@1.2.1/node_modules/set-function-length/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var define2 = require_define_data_property(); + var hasDescriptors = require_has_property_descriptors()(); + var gOPD = require_gopd(); + var $TypeError = require_type(); + var $floor = GetIntrinsic("%Math.floor%"); + module2.exports = function setFunctionLength(fn, length) { + if (typeof fn !== "function") { + throw new $TypeError("`fn` is not a function"); + } + if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length) { + throw new $TypeError("`length` must be a positive 32-bit integer"); + } + var loose = arguments.length > 2 && !!arguments[2]; + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ("length" in fn && gOPD) { + var desc = gOPD(fn, "length"); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length, + true, + true + ); + } else { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length + ); + } + } + return fn; + }; + } +}); + +// node_modules/.pnpm/call-bind@1.0.6/node_modules/call-bind/index.js +var require_call_bind = __commonJS({ + "node_modules/.pnpm/call-bind@1.0.6/node_modules/call-bind/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var bind = require_function_bind(); + var GetIntrinsic = require_get_intrinsic(); + var setFunctionLength = require_set_function_length(); + var $TypeError = require_type(); + var $apply = GetIntrinsic("%Function.prototype.apply%"); + var $call = GetIntrinsic("%Function.prototype.call%"); + var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var $max = GetIntrinsic("%Math.max%"); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = null; + } + } + module2.exports = function callBind(originalFunction) { + if (typeof originalFunction !== "function") { + throw new $TypeError("a function is required"); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); + }; + var applyBind = function applyBind2() { + return $reflectApply(bind, $apply, arguments); + }; + if ($defineProperty) { + $defineProperty(module2.exports, "apply", { value: applyBind }); + } else { + module2.exports.apply = applyBind; + } + } +}); + +// node_modules/.pnpm/call-bind@1.0.6/node_modules/call-bind/callBound.js +var require_callBound = __commonJS({ + "node_modules/.pnpm/call-bind@1.0.6/node_modules/call-bind/callBound.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var callBind = require_call_bind(); + var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf")); + module2.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) { + return callBind(intrinsic); + } + return intrinsic; + }; + } +}); + +// node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/implementation.js +var require_implementation3 = __commonJS({ + "node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/implementation.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var objectKeys = require_object_keys(); + var hasSymbols = require_shams()(); + var callBound = require_callBound(); + var toObject = Object; + var $push = callBound("Array.prototype.push"); + var $propIsEnumerable = callBound("Object.prototype.propertyIsEnumerable"); + var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; + module2.exports = function assign2(target, source1) { + if (target == null) { + throw new TypeError("target must be an object"); + } + var to = toObject(target); + if (arguments.length === 1) { + return to; + } + for (var s = 1; s < arguments.length; ++s) { + var from = toObject(arguments[s]); + var keys = objectKeys(from); + var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key2 = syms[j]; + if ($propIsEnumerable(from, key2)) { + $push(keys, key2); + } + } + } + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { + var propValue = from[nextKey]; + to[nextKey] = propValue; + } + } + } + return to; + }; + } +}); + +// node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/polyfill.js +var require_polyfill = __commonJS({ + "node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/polyfill.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var implementation = require_implementation3(); + var lacksProperEnumerationOrder = function() { + if (!Object.assign) { + return false; + } + var str = "abcdefghijklmnopqrst"; + var letters = str.split(""); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ""; + for (var k in obj) { + actual += k; + } + return str !== actual; + }; + var assignHasPendingExceptions = function() { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, "xy"); + } catch (e) { + return thrower[1] === "y"; + } + return false; + }; + module2.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; + }; + } +}); + +// node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/shim.js +var require_shim = __commonJS({ + "node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/shim.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var define2 = require_define_properties(); + var getPolyfill = require_polyfill(); + module2.exports = function shimAssign() { + var polyfill = getPolyfill(); + define2( + Object, + { assign: polyfill }, + { assign: function() { + return Object.assign !== polyfill; + } } + ); + return polyfill; + }; + } +}); + +// node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/index.js +var require_object = __commonJS({ + "node_modules/.pnpm/object.assign@4.1.5/node_modules/object.assign/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var defineProperties = require_define_properties(); + var callBind = require_call_bind(); + var implementation = require_implementation3(); + var getPolyfill = require_polyfill(); + var shim = require_shim(); + var polyfill = callBind.apply(getPolyfill()); + var bound = function assign2(target, source1) { + return polyfill(Object, arguments); + }; + defineProperties(bound, { + getPolyfill, + implementation, + shim + }); + module2.exports = bound; + } +}); + +// node_modules/.pnpm/functions-have-names@1.2.3/node_modules/functions-have-names/index.js +var require_functions_have_names = __commonJS({ + "node_modules/.pnpm/functions-have-names@1.2.3/node_modules/functions-have-names/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var functionsHaveNames = function functionsHaveNames2() { + return typeof function f() { + }.name === "string"; + }; + var gOPD = Object.getOwnPropertyDescriptor; + if (gOPD) { + try { + gOPD([], "length"); + } catch (e) { + gOPD = null; + } + } + functionsHaveNames.functionsHaveConfigurableNames = function functionsHaveConfigurableNames() { + if (!functionsHaveNames() || !gOPD) { + return false; + } + var desc = gOPD(function() { + }, "name"); + return !!desc && !!desc.configurable; + }; + var $bind = Function.prototype.bind; + functionsHaveNames.boundFunctionsHaveNames = function boundFunctionsHaveNames() { + return functionsHaveNames() && typeof $bind === "function" && function f() { + }.bind().name !== ""; + }; + module2.exports = functionsHaveNames; + } +}); + +// node_modules/.pnpm/set-function-name@2.0.1/node_modules/set-function-name/index.js +var require_set_function_name = __commonJS({ + "node_modules/.pnpm/set-function-name@2.0.1/node_modules/set-function-name/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var define2 = require_define_data_property(); + var hasDescriptors = require_has_property_descriptors()(); + var functionsHaveConfigurableNames = require_functions_have_names().functionsHaveConfigurableNames(); + var $TypeError = TypeError; + module2.exports = function setFunctionName(fn, name) { + if (typeof fn !== "function") { + throw new $TypeError("`fn` is not a function"); + } + var loose = arguments.length > 2 && !!arguments[2]; + if (!loose || functionsHaveConfigurableNames) { + if (hasDescriptors) { + define2(fn, "name", name, true, true); + } else { + define2(fn, "name", name); + } + } + return fn; + }; + } +}); + +// node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/implementation.js +var require_implementation4 = __commonJS({ + "node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/implementation.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var setFunctionName = require_set_function_name(); + var $TypeError = require_type(); + var $Object = Object; + module2.exports = setFunctionName(function flags() { + if (this == null || this !== $Object(this)) { + throw new $TypeError("RegExp.prototype.flags getter called on non-object"); + } + var result = ""; + if (this.hasIndices) { + result += "d"; + } + if (this.global) { + result += "g"; + } + if (this.ignoreCase) { + result += "i"; + } + if (this.multiline) { + result += "m"; + } + if (this.dotAll) { + result += "s"; + } + if (this.unicode) { + result += "u"; + } + if (this.unicodeSets) { + result += "v"; + } + if (this.sticky) { + result += "y"; + } + return result; + }, "get flags", true); + } +}); + +// node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/polyfill.js +var require_polyfill2 = __commonJS({ + "node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/polyfill.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var implementation = require_implementation4(); + var supportsDescriptors = require_define_properties().supportsDescriptors; + var $gOPD = Object.getOwnPropertyDescriptor; + module2.exports = function getPolyfill() { + if (supportsDescriptors && /a/mig.flags === "gim") { + var descriptor = $gOPD(RegExp.prototype, "flags"); + if (descriptor && typeof descriptor.get === "function" && typeof RegExp.prototype.dotAll === "boolean" && typeof RegExp.prototype.hasIndices === "boolean") { + var calls = ""; + var o = {}; + Object.defineProperty(o, "hasIndices", { + get: function() { + calls += "d"; + } + }); + Object.defineProperty(o, "sticky", { + get: function() { + calls += "y"; + } + }); + if (calls === "dy") { + return descriptor.get; + } + } + } + return implementation; + }; + } +}); + +// node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/shim.js +var require_shim2 = __commonJS({ + "node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/shim.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var supportsDescriptors = require_define_properties().supportsDescriptors; + var getPolyfill = require_polyfill2(); + var gOPD = Object.getOwnPropertyDescriptor; + var defineProperty = Object.defineProperty; + var TypeErr = TypeError; + var getProto = Object.getPrototypeOf; + var regex2 = /a/; + module2.exports = function shimFlags() { + if (!supportsDescriptors || !getProto) { + throw new TypeErr("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors"); + } + var polyfill = getPolyfill(); + var proto = getProto(regex2); + var descriptor = gOPD(proto, "flags"); + if (!descriptor || descriptor.get !== polyfill) { + defineProperty(proto, "flags", { + configurable: true, + enumerable: false, + get: polyfill + }); + } + return polyfill; + }; + } +}); + +// node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/index.js +var require_regexp_prototype = __commonJS({ + "node_modules/.pnpm/regexp.prototype.flags@1.5.2/node_modules/regexp.prototype.flags/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var define2 = require_define_properties(); + var callBind = require_call_bind(); + var implementation = require_implementation4(); + var getPolyfill = require_polyfill2(); + var shim = require_shim2(); + var flagsBound = callBind(getPolyfill()); + define2(flagsBound, { + getPolyfill, + implementation, + shim + }); + module2.exports = flagsBound; + } +}); + +// node_modules/.pnpm/has-tostringtag@1.0.2/node_modules/has-tostringtag/shams.js +var require_shams2 = __commonJS({ + "node_modules/.pnpm/has-tostringtag@1.0.2/node_modules/has-tostringtag/shams.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var hasSymbols = require_shams(); + module2.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; + }; + } +}); + +// node_modules/.pnpm/is-arguments@1.1.1/node_modules/is-arguments/index.js +var require_is_arguments = __commonJS({ + "node_modules/.pnpm/is-arguments@1.1.1/node_modules/is-arguments/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var hasToStringTag = require_shams2()(); + var callBound = require_callBound(); + var $toString = callBound("Object.prototype.toString"); + var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === "object" && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === "[object Arguments]"; + }; + var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && $toString(value) !== "[object Array]" && $toString(value.callee) === "[object Function]"; + }; + var supportsStandardArguments = function() { + return isStandardArguments(arguments); + }(); + isStandardArguments.isLegacyArguments = isLegacyArguments; + module2.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + } +}); + +// (disabled):node_modules/.pnpm/object-inspect@1.13.1/node_modules/object-inspect/util.inspect +var require_util = __commonJS({ + "(disabled):node_modules/.pnpm/object-inspect@1.13.1/node_modules/object-inspect/util.inspect"() { + init_polyfill_buffer(); + } +}); + +// node_modules/.pnpm/object-inspect@1.13.1/node_modules/object-inspect/index.js +var require_object_inspect = __commonJS({ + "node_modules/.pnpm/object-inspect@1.13.1/node_modules/object-inspect/index.js"(exports2, module2) { + init_polyfill_buffer(); + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString2 = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { + return O.__proto__; + } : null); + function addNumericSeparator(num2, str) { + if (num2 === Infinity || num2 === -Infinity || num2 !== num2 || num2 && num2 > -1e3 && num2 < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num2 === "number") { + var int = num2 < 0 ? -$floor(-num2) : $floor(num2); + if (int !== num2) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = require_util(); + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + module2.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray(obj) ? "[Array]" : "[Object]"; + } + var indent2 = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp(obj)) { + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts); + } + s += ">"; + if (obj.childNodes && obj.childNodes.length) { + s += "..."; + } + s += ""; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent2 && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent2) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key2) { + mapParts.push(inspect(key2, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent2); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent2); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (obj === global) { + return "{ [object globalThis] }"; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag2 = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag2 + "{}"; + } + if (indent2) { + return tag2 + "{" + indentedJoin(ys, indent2) + "}"; + } + return tag2 + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'"; + return quoteChar + s + quoteChar; + } + function quote(s) { + return $replace.call(String(s), /"/g, """); + } + function isArray(obj) { + return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isDate(obj) { + return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isRegExp(obj) { + return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isError(obj) { + return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isString(obj) { + return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isNumber(obj) { + return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isBoolean(obj) { + return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) { + } + return false; + } + function isBigInt(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) { + } + return false; + } + var hasOwn = Object.prototype.hasOwnProperty || function(key2) { + return key2 in this; + }; + function has(obj, key2) { + return hasOwn.call(obj, key2); + } + function toStr(obj) { + return objectToString2.call(obj); + } + function nameOf(f) { + if (f.name) { + return f.name; + } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { + return m[1]; + } + return null; + } + function indexOf(xs, x) { + if (xs.indexOf) { + return xs.indexOf(x); + } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { + return i; + } + } + return -1; + } + function isMap(x) { + if (!mapSize || !x || typeof x !== "object") { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; + } catch (e) { + } + return false; + } + function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== "object") { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; + } catch (e) { + } + return false; + } + function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== "object") { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) { + } + return false; + } + function isSet(x) { + if (!setSize || !x || typeof x !== "object") { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; + } catch (e) { + } + return false; + } + function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== "object") { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; + } catch (e) { + } + return false; + } + function isElement(x) { + if (!x || typeof x !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === "string" && typeof x.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var s = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, "single", opts); + } + function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n]; + if (x) { + return "\\" + x; + } + return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type) { + return type + " { ? }"; + } + function collectionOf(type, size, entries, indent2) { + var joinedEntries = indent2 ? indentedJoin(entries, indent2) : $join.call(entries, ", "); + return type + " (" + size + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent2) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent2.prev + indent2.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent2.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap["$" + syms[k]] = syms[k]; + } + } + for (var key2 in obj) { + if (!has(obj, key2)) { + continue; + } + if (isArr && String(Number(key2)) === key2 && key2 < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key2] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key2)) { + xs.push(inspect(key2, obj) + ": " + inspect(obj[key2], obj)); + } else { + xs.push(key2 + ": " + inspect(obj[key2], obj)); + } + } + if (typeof gOPS === "function") { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj)); + } + } + } + return xs; + } + } +}); + +// node_modules/.pnpm/side-channel@1.0.5/node_modules/side-channel/index.js +var require_side_channel = __commonJS({ + "node_modules/.pnpm/side-channel@1.0.5/node_modules/side-channel/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_callBound(); + var inspect = require_object_inspect(); + var $TypeError = require_type(); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $Map = GetIntrinsic("%Map%", true); + var $weakMapGet = callBound("WeakMap.prototype.get", true); + var $weakMapSet = callBound("WeakMap.prototype.set", true); + var $weakMapHas = callBound("WeakMap.prototype.has", true); + var $mapGet = callBound("Map.prototype.get", true); + var $mapSet = callBound("Map.prototype.set", true); + var $mapHas = callBound("Map.prototype.has", true); + var listGetNode = function(list, key2) { + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key2) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; + return curr; + } + } + }; + var listGet = function(objects, key2) { + var node = listGetNode(objects, key2); + return node && node.value; + }; + var listSet = function(objects, key2, value) { + var node = listGetNode(objects, key2); + if (node) { + node.value = value; + } else { + objects.next = { + // eslint-disable-line no-param-reassign + key: key2, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key2) { + return !!listGetNode(objects, key2); + }; + module2.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function(key2) { + if (!channel.has(key2)) { + throw new $TypeError("Side channel does not contain " + inspect(key2)); + } + }, + get: function(key2) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if ($wm) { + return $weakMapGet($wm, key2); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key2); + } + } else { + if ($o) { + return listGet($o, key2); + } + } + }, + has: function(key2) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if ($wm) { + return $weakMapHas($wm, key2); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key2); + } + } else { + if ($o) { + return listHas($o, key2); + } + } + return false; + }, + set: function(key2, value) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key2, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key2, value); + } else { + if (!$o) { + $o = { key: {}, next: null }; + } + listSet($o, key2, value); + } + } + }; + return channel; + }; + } +}); + +// node_modules/.pnpm/internal-slot@1.0.7/node_modules/internal-slot/index.js +var require_internal_slot = __commonJS({ + "node_modules/.pnpm/internal-slot@1.0.7/node_modules/internal-slot/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var hasOwn = require_hasown(); + var channel = require_side_channel()(); + var $TypeError = require_type(); + var SLOT = { + assert: function(O, slot) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new $TypeError("`O` is not an object"); + } + if (typeof slot !== "string") { + throw new $TypeError("`slot` must be a string"); + } + channel.assert(O); + if (!SLOT.has(O, slot)) { + throw new $TypeError("`" + slot + "` is not present on `O`"); + } + }, + get: function(O, slot) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new $TypeError("`O` is not an object"); + } + if (typeof slot !== "string") { + throw new $TypeError("`slot` must be a string"); + } + var slots = channel.get(O); + return slots && slots["$" + slot]; + }, + has: function(O, slot) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new $TypeError("`O` is not an object"); + } + if (typeof slot !== "string") { + throw new $TypeError("`slot` must be a string"); + } + var slots = channel.get(O); + return !!slots && hasOwn(slots, "$" + slot); + }, + set: function(O, slot, V) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new $TypeError("`O` is not an object"); + } + if (typeof slot !== "string") { + throw new $TypeError("`slot` must be a string"); + } + var slots = channel.get(O); + if (!slots) { + slots = {}; + channel.set(O, slots); + } + slots["$" + slot] = V; + } + }; + if (Object.freeze) { + Object.freeze(SLOT); + } + module2.exports = SLOT; + } +}); + +// node_modules/.pnpm/stop-iteration-iterator@1.0.0/node_modules/stop-iteration-iterator/index.js +var require_stop_iteration_iterator = __commonJS({ + "node_modules/.pnpm/stop-iteration-iterator@1.0.0/node_modules/stop-iteration-iterator/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var SLOT = require_internal_slot(); + var $SyntaxError = SyntaxError; + var $StopIteration = typeof StopIteration === "object" ? StopIteration : null; + module2.exports = function getStopIterationIterator(origIterator) { + if (!$StopIteration) { + throw new $SyntaxError("this environment lacks StopIteration"); + } + SLOT.set(origIterator, "[[Done]]", false); + var siIterator = { + next: function next() { + var iterator = SLOT.get(this, "[[Iterator]]"); + var done = SLOT.get(iterator, "[[Done]]"); + try { + return { + done, + value: done ? void 0 : iterator.next() + }; + } catch (e) { + SLOT.set(iterator, "[[Done]]", true); + if (e !== $StopIteration) { + throw e; + } + return { + done: true, + value: void 0 + }; + } + } + }; + SLOT.set(siIterator, "[[Iterator]]", origIterator); + return siIterator; + }; + } +}); + +// node_modules/.pnpm/isarray@2.0.5/node_modules/isarray/index.js +var require_isarray = __commonJS({ + "node_modules/.pnpm/isarray@2.0.5/node_modules/isarray/index.js"(exports2, module2) { + init_polyfill_buffer(); + var toString = {}.toString; + module2.exports = Array.isArray || function(arr) { + return toString.call(arr) == "[object Array]"; + }; + } +}); + +// node_modules/.pnpm/is-string@1.0.7/node_modules/is-string/index.js +var require_is_string = __commonJS({ + "node_modules/.pnpm/is-string@1.0.7/node_modules/is-string/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var strValue = String.prototype.valueOf; + var tryStringObject = function tryStringObject2(value) { + try { + strValue.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + var strClass = "[object String]"; + var hasToStringTag = require_shams2()(); + module2.exports = function isString(value) { + if (typeof value === "string") { + return true; + } + if (typeof value !== "object") { + return false; + } + return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; + }; + } +}); + +// node_modules/.pnpm/is-map@2.0.2/node_modules/is-map/index.js +var require_is_map = __commonJS({ + "node_modules/.pnpm/is-map@2.0.2/node_modules/is-map/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var $Map = typeof Map === "function" && Map.prototype ? Map : null; + var $Set = typeof Set === "function" && Set.prototype ? Set : null; + var exported; + if (!$Map) { + exported = function isMap(x) { + return false; + }; + } + var $mapHas = $Map ? Map.prototype.has : null; + var $setHas = $Set ? Set.prototype.has : null; + if (!exported && !$mapHas) { + exported = function isMap(x) { + return false; + }; + } + module2.exports = exported || function isMap(x) { + if (!x || typeof x !== "object") { + return false; + } + try { + $mapHas.call(x); + if ($setHas) { + try { + $setHas.call(x); + } catch (e) { + return true; + } + } + return x instanceof $Map; + } catch (e) { + } + return false; + }; + } +}); + +// node_modules/.pnpm/is-set@2.0.2/node_modules/is-set/index.js +var require_is_set = __commonJS({ + "node_modules/.pnpm/is-set@2.0.2/node_modules/is-set/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var $Map = typeof Map === "function" && Map.prototype ? Map : null; + var $Set = typeof Set === "function" && Set.prototype ? Set : null; + var exported; + if (!$Set) { + exported = function isSet(x) { + return false; + }; + } + var $mapHas = $Map ? Map.prototype.has : null; + var $setHas = $Set ? Set.prototype.has : null; + if (!exported && !$setHas) { + exported = function isSet(x) { + return false; + }; + } + module2.exports = exported || function isSet(x) { + if (!x || typeof x !== "object") { + return false; + } + try { + $setHas.call(x); + if ($mapHas) { + try { + $mapHas.call(x); + } catch (e) { + return true; + } + } + return x instanceof $Set; + } catch (e) { + } + return false; + }; + } +}); + +// node_modules/.pnpm/es-get-iterator@1.1.3/node_modules/es-get-iterator/index.js +var require_es_get_iterator = __commonJS({ + "node_modules/.pnpm/es-get-iterator@1.1.3/node_modules/es-get-iterator/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var isArguments = require_is_arguments(); + var getStopIterationIterator = require_stop_iteration_iterator(); + if (require_has_symbols()() || require_shams()()) { + $iterator = Symbol.iterator; + module2.exports = function getIterator3(iterable) { + if (iterable != null && typeof iterable[$iterator] !== "undefined") { + return iterable[$iterator](); + } + if (isArguments(iterable)) { + return Array.prototype[$iterator].call(iterable); + } + }; + } else { + isArray = require_isarray(); + isString = require_is_string(); + GetIntrinsic = require_get_intrinsic(); + $Map = GetIntrinsic("%Map%", true); + $Set = GetIntrinsic("%Set%", true); + callBound = require_callBound(); + $arrayPush = callBound("Array.prototype.push"); + $charCodeAt = callBound("String.prototype.charCodeAt"); + $stringSlice = callBound("String.prototype.slice"); + advanceStringIndex = function advanceStringIndex2(S, index2) { + var length = S.length; + if (index2 + 1 >= length) { + return index2 + 1; + } + var first2 = $charCodeAt(S, index2); + if (first2 < 55296 || first2 > 56319) { + return index2 + 1; + } + var second = $charCodeAt(S, index2 + 1); + if (second < 56320 || second > 57343) { + return index2 + 1; + } + return index2 + 2; + }; + getArrayIterator = function getArrayIterator2(arraylike) { + var i = 0; + return { + next: function next() { + var done = i >= arraylike.length; + var value; + if (!done) { + value = arraylike[i]; + i += 1; + } + return { + done, + value + }; + } + }; + }; + getNonCollectionIterator = function getNonCollectionIterator2(iterable, noPrimordialCollections) { + if (isArray(iterable) || isArguments(iterable)) { + return getArrayIterator(iterable); + } + if (isString(iterable)) { + var i = 0; + return { + next: function next() { + var nextIndex = advanceStringIndex(iterable, i); + var value = $stringSlice(iterable, i, nextIndex); + i = nextIndex; + return { + done: nextIndex > iterable.length, + value + }; + } + }; + } + if (noPrimordialCollections && typeof iterable["_es6-shim iterator_"] !== "undefined") { + return iterable["_es6-shim iterator_"](); + } + }; + if (!$Map && !$Set) { + module2.exports = function getIterator3(iterable) { + if (iterable != null) { + return getNonCollectionIterator(iterable, true); + } + }; + } else { + isMap = require_is_map(); + isSet = require_is_set(); + $mapForEach = callBound("Map.prototype.forEach", true); + $setForEach = callBound("Set.prototype.forEach", true); + if (typeof process === "undefined" || !process.versions || !process.versions.node) { + $mapIterator = callBound("Map.prototype.iterator", true); + $setIterator = callBound("Set.prototype.iterator", true); + } + $mapAtAtIterator = callBound("Map.prototype.@@iterator", true) || callBound("Map.prototype._es6-shim iterator_", true); + $setAtAtIterator = callBound("Set.prototype.@@iterator", true) || callBound("Set.prototype._es6-shim iterator_", true); + getCollectionIterator = function getCollectionIterator2(iterable) { + if (isMap(iterable)) { + if ($mapIterator) { + return getStopIterationIterator($mapIterator(iterable)); + } + if ($mapAtAtIterator) { + return $mapAtAtIterator(iterable); + } + if ($mapForEach) { + var entries = []; + $mapForEach(iterable, function(v, k) { + $arrayPush(entries, [k, v]); + }); + return getArrayIterator(entries); + } + } + if (isSet(iterable)) { + if ($setIterator) { + return getStopIterationIterator($setIterator(iterable)); + } + if ($setAtAtIterator) { + return $setAtAtIterator(iterable); + } + if ($setForEach) { + var values = []; + $setForEach(iterable, function(v) { + $arrayPush(values, v); + }); + return getArrayIterator(values); + } + } + }; + module2.exports = function getIterator3(iterable) { + return getCollectionIterator(iterable) || getNonCollectionIterator(iterable); + }; + } + } + var $iterator; + var isArray; + var isString; + var GetIntrinsic; + var $Map; + var $Set; + var callBound; + var $arrayPush; + var $charCodeAt; + var $stringSlice; + var advanceStringIndex; + var getArrayIterator; + var getNonCollectionIterator; + var isMap; + var isSet; + var $mapForEach; + var $setForEach; + var $mapIterator; + var $setIterator; + var $mapAtAtIterator; + var $setAtAtIterator; + var getCollectionIterator; + } +}); + +// node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/implementation.js +var require_implementation5 = __commonJS({ + "node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/implementation.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var numberIsNaN = function(value) { + return value !== value; + }; + module2.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; + }; + } +}); + +// node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/polyfill.js +var require_polyfill3 = __commonJS({ + "node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/polyfill.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var implementation = require_implementation5(); + module2.exports = function getPolyfill() { + return typeof Object.is === "function" ? Object.is : implementation; + }; + } +}); + +// node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/shim.js +var require_shim3 = __commonJS({ + "node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/shim.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var getPolyfill = require_polyfill3(); + var define2 = require_define_properties(); + module2.exports = function shimObjectIs() { + var polyfill = getPolyfill(); + define2(Object, { is: polyfill }, { + is: function testObjectIs() { + return Object.is !== polyfill; + } + }); + return polyfill; + }; + } +}); + +// node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/index.js +var require_object_is = __commonJS({ + "node_modules/.pnpm/object-is@1.1.5/node_modules/object-is/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var define2 = require_define_properties(); + var callBind = require_call_bind(); + var implementation = require_implementation5(); + var getPolyfill = require_polyfill3(); + var shim = require_shim3(); + var polyfill = callBind(getPolyfill(), Object); + define2(polyfill, { + getPolyfill, + implementation, + shim + }); + module2.exports = polyfill; + } +}); + +// node_modules/.pnpm/is-array-buffer@3.0.4/node_modules/is-array-buffer/index.js +var require_is_array_buffer = __commonJS({ + "node_modules/.pnpm/is-array-buffer@3.0.4/node_modules/is-array-buffer/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var callBind = require_call_bind(); + var callBound = require_callBound(); + var GetIntrinsic = require_get_intrinsic(); + var $ArrayBuffer = GetIntrinsic("%ArrayBuffer%", true); + var $byteLength = callBound("ArrayBuffer.prototype.byteLength", true); + var $toString = callBound("Object.prototype.toString"); + var abSlice = !!$ArrayBuffer && !$byteLength && new $ArrayBuffer(0).slice; + var $abSlice = !!abSlice && callBind(abSlice); + module2.exports = $byteLength || $abSlice ? function isArrayBuffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + try { + if ($byteLength) { + $byteLength(obj); + } else { + $abSlice(obj, 0); + } + return true; + } catch (e) { + return false; + } + } : $ArrayBuffer ? function isArrayBuffer(obj) { + return $toString(obj) === "[object ArrayBuffer]"; + } : function isArrayBuffer(obj) { + return false; + }; + } +}); + +// node_modules/.pnpm/is-date-object@1.0.5/node_modules/is-date-object/index.js +var require_is_date_object = __commonJS({ + "node_modules/.pnpm/is-date-object@1.0.5/node_modules/is-date-object/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var getDay = Date.prototype.getDay; + var tryDateObject = function tryDateGetDayCall(value) { + try { + getDay.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + var dateClass = "[object Date]"; + var hasToStringTag = require_shams2()(); + module2.exports = function isDateObject(value) { + if (typeof value !== "object" || value === null) { + return false; + } + return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; + }; + } +}); + +// node_modules/.pnpm/is-regex@1.1.4/node_modules/is-regex/index.js +var require_is_regex = __commonJS({ + "node_modules/.pnpm/is-regex@1.1.4/node_modules/is-regex/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var callBound = require_callBound(); + var hasToStringTag = require_shams2()(); + var has; + var $exec; + var isRegexMarker; + var badStringifier; + if (hasToStringTag) { + has = callBound("Object.prototype.hasOwnProperty"); + $exec = callBound("RegExp.prototype.exec"); + isRegexMarker = {}; + throwRegexMarker = function() { + throw isRegexMarker; + }; + badStringifier = { + toString: throwRegexMarker, + valueOf: throwRegexMarker + }; + if (typeof Symbol.toPrimitive === "symbol") { + badStringifier[Symbol.toPrimitive] = throwRegexMarker; + } + } + var throwRegexMarker; + var $toString = callBound("Object.prototype.toString"); + var gOPD = Object.getOwnPropertyDescriptor; + var regexClass = "[object RegExp]"; + module2.exports = hasToStringTag ? function isRegex(value) { + if (!value || typeof value !== "object") { + return false; + } + var descriptor = gOPD(value, "lastIndex"); + var hasLastIndexDataProperty = descriptor && has(descriptor, "value"); + if (!hasLastIndexDataProperty) { + return false; + } + try { + $exec(value, badStringifier); + } catch (e) { + return e === isRegexMarker; + } + } : function isRegex(value) { + if (!value || typeof value !== "object" && typeof value !== "function") { + return false; + } + return $toString(value) === regexClass; + }; + } +}); + +// node_modules/.pnpm/is-shared-array-buffer@1.0.2/node_modules/is-shared-array-buffer/index.js +var require_is_shared_array_buffer = __commonJS({ + "node_modules/.pnpm/is-shared-array-buffer@1.0.2/node_modules/is-shared-array-buffer/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var callBound = require_callBound(); + var $byteLength = callBound("SharedArrayBuffer.prototype.byteLength", true); + module2.exports = $byteLength ? function isSharedArrayBuffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + try { + $byteLength(obj); + return true; + } catch (e) { + return false; + } + } : function isSharedArrayBuffer(obj) { + return false; + }; + } +}); + +// node_modules/.pnpm/is-number-object@1.0.7/node_modules/is-number-object/index.js +var require_is_number_object = __commonJS({ + "node_modules/.pnpm/is-number-object@1.0.7/node_modules/is-number-object/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var numToStr = Number.prototype.toString; + var tryNumberObject = function tryNumberObject2(value) { + try { + numToStr.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + var numClass = "[object Number]"; + var hasToStringTag = require_shams2()(); + module2.exports = function isNumberObject(value) { + if (typeof value === "number") { + return true; + } + if (typeof value !== "object") { + return false; + } + return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass; + }; + } +}); + +// node_modules/.pnpm/is-boolean-object@1.1.2/node_modules/is-boolean-object/index.js +var require_is_boolean_object = __commonJS({ + "node_modules/.pnpm/is-boolean-object@1.1.2/node_modules/is-boolean-object/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var callBound = require_callBound(); + var $boolToStr = callBound("Boolean.prototype.toString"); + var $toString = callBound("Object.prototype.toString"); + var tryBooleanObject = function booleanBrandCheck(value) { + try { + $boolToStr(value); + return true; + } catch (e) { + return false; + } + }; + var boolClass = "[object Boolean]"; + var hasToStringTag = require_shams2()(); + module2.exports = function isBoolean(value) { + if (typeof value === "boolean") { + return true; + } + if (value === null || typeof value !== "object") { + return false; + } + return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString(value) === boolClass; + }; + } +}); + +// node_modules/.pnpm/is-symbol@1.0.4/node_modules/is-symbol/index.js +var require_is_symbol = __commonJS({ + "node_modules/.pnpm/is-symbol@1.0.4/node_modules/is-symbol/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var toStr = Object.prototype.toString; + var hasSymbols = require_has_symbols()(); + if (hasSymbols) { + symToStr = Symbol.prototype.toString; + symStringRegex = /^Symbol\(.*\)$/; + isSymbolObject = function isRealSymbolObject(value) { + if (typeof value.valueOf() !== "symbol") { + return false; + } + return symStringRegex.test(symToStr.call(value)); + }; + module2.exports = function isSymbol(value) { + if (typeof value === "symbol") { + return true; + } + if (toStr.call(value) !== "[object Symbol]") { + return false; + } + try { + return isSymbolObject(value); + } catch (e) { + return false; + } + }; + } else { + module2.exports = function isSymbol(value) { + return false; + }; + } + var symToStr; + var symStringRegex; + var isSymbolObject; + } +}); + +// node_modules/.pnpm/has-bigints@1.0.2/node_modules/has-bigints/index.js +var require_has_bigints = __commonJS({ + "node_modules/.pnpm/has-bigints@1.0.2/node_modules/has-bigints/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var $BigInt = typeof BigInt !== "undefined" && BigInt; + module2.exports = function hasNativeBigInts() { + return typeof $BigInt === "function" && typeof BigInt === "function" && typeof $BigInt(42) === "bigint" && typeof BigInt(42) === "bigint"; + }; + } +}); + +// node_modules/.pnpm/is-bigint@1.0.4/node_modules/is-bigint/index.js +var require_is_bigint = __commonJS({ + "node_modules/.pnpm/is-bigint@1.0.4/node_modules/is-bigint/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var hasBigInts = require_has_bigints()(); + if (hasBigInts) { + bigIntValueOf = BigInt.prototype.valueOf; + tryBigInt = function tryBigIntObject(value) { + try { + bigIntValueOf.call(value); + return true; + } catch (e) { + } + return false; + }; + module2.exports = function isBigInt(value) { + if (value === null || typeof value === "undefined" || typeof value === "boolean" || typeof value === "string" || typeof value === "number" || typeof value === "symbol" || typeof value === "function") { + return false; + } + if (typeof value === "bigint") { + return true; + } + return tryBigInt(value); + }; + } else { + module2.exports = function isBigInt(value) { + return false; + }; + } + var bigIntValueOf; + var tryBigInt; + } +}); + +// node_modules/.pnpm/which-boxed-primitive@1.0.2/node_modules/which-boxed-primitive/index.js +var require_which_boxed_primitive = __commonJS({ + "node_modules/.pnpm/which-boxed-primitive@1.0.2/node_modules/which-boxed-primitive/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var isString = require_is_string(); + var isNumber = require_is_number_object(); + var isBoolean = require_is_boolean_object(); + var isSymbol = require_is_symbol(); + var isBigInt = require_is_bigint(); + module2.exports = function whichBoxedPrimitive(value) { + if (value == null || typeof value !== "object" && typeof value !== "function") { + return null; + } + if (isString(value)) { + return "String"; + } + if (isNumber(value)) { + return "Number"; + } + if (isBoolean(value)) { + return "Boolean"; + } + if (isSymbol(value)) { + return "Symbol"; + } + if (isBigInt(value)) { + return "BigInt"; + } + }; + } +}); + +// node_modules/.pnpm/is-weakmap@2.0.1/node_modules/is-weakmap/index.js +var require_is_weakmap = __commonJS({ + "node_modules/.pnpm/is-weakmap@2.0.1/node_modules/is-weakmap/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var $WeakMap = typeof WeakMap === "function" && WeakMap.prototype ? WeakMap : null; + var $WeakSet = typeof WeakSet === "function" && WeakSet.prototype ? WeakSet : null; + var exported; + if (!$WeakMap) { + exported = function isWeakMap(x) { + return false; + }; + } + var $mapHas = $WeakMap ? $WeakMap.prototype.has : null; + var $setHas = $WeakSet ? $WeakSet.prototype.has : null; + if (!exported && !$mapHas) { + exported = function isWeakMap(x) { + return false; + }; + } + module2.exports = exported || function isWeakMap(x) { + if (!x || typeof x !== "object") { + return false; + } + try { + $mapHas.call(x, $mapHas); + if ($setHas) { + try { + $setHas.call(x, $setHas); + } catch (e) { + return true; + } + } + return x instanceof $WeakMap; + } catch (e) { + } + return false; + }; + } +}); + +// node_modules/.pnpm/is-weakset@2.0.2/node_modules/is-weakset/index.js +var require_is_weakset = __commonJS({ + "node_modules/.pnpm/is-weakset@2.0.2/node_modules/is-weakset/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_callBound(); + var $WeakSet = GetIntrinsic("%WeakSet%", true); + var $setHas = callBound("WeakSet.prototype.has", true); + if ($setHas) { + $mapHas = callBound("WeakMap.prototype.has", true); + module2.exports = function isWeakSet(x) { + if (!x || typeof x !== "object") { + return false; + } + try { + $setHas(x, $setHas); + if ($mapHas) { + try { + $mapHas(x, $mapHas); + } catch (e) { + return true; + } + } + return x instanceof $WeakSet; + } catch (e) { + } + return false; + }; + } else { + module2.exports = function isWeakSet(x) { + return false; + }; + } + var $mapHas; + } +}); + +// node_modules/.pnpm/which-collection@1.0.1/node_modules/which-collection/index.js +var require_which_collection = __commonJS({ + "node_modules/.pnpm/which-collection@1.0.1/node_modules/which-collection/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var isMap = require_is_map(); + var isSet = require_is_set(); + var isWeakMap = require_is_weakmap(); + var isWeakSet = require_is_weakset(); + module2.exports = function whichCollection(value) { + if (value && typeof value === "object") { + if (isMap(value)) { + return "Map"; + } + if (isSet(value)) { + return "Set"; + } + if (isWeakMap(value)) { + return "WeakMap"; + } + if (isWeakSet(value)) { + return "WeakSet"; + } + } + return false; + }; + } +}); + +// node_modules/.pnpm/is-callable@1.2.7/node_modules/is-callable/index.js +var require_is_callable = __commonJS({ + "node_modules/.pnpm/is-callable@1.2.7/node_modules/is-callable/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var fnToStr = Function.prototype.toString; + var reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply; + var badArrayLike; + var isCallableMarker; + if (typeof reflectApply === "function" && typeof Object.defineProperty === "function") { + try { + badArrayLike = Object.defineProperty({}, "length", { + get: function() { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + reflectApply(function() { + throw 42; + }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } + } else { + reflectApply = null; + } + var constructorRegex = /^\s*class\b/; + var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; + } + }; + var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { + return false; + } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + var objectClass = "[object Object]"; + var fnClass = "[object Function]"; + var genClass = "[object GeneratorFunction]"; + var ddaClass = "[object HTMLAllCollection]"; + var ddaClass2 = "[object HTML document.all class]"; + var ddaClass3 = "[object HTMLCollection]"; + var hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag; + var isIE68 = !(0 in [,]); + var isDDA = function isDocumentDotAll() { + return false; + }; + if (typeof document === "object") { + all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) { + try { + var str = toStr.call(value); + return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null; + } catch (e) { + } + } + return false; + }; + } + } + var all; + module2.exports = reflectApply ? function isCallable(value) { + if (isDDA(value)) { + return true; + } + if (!value) { + return false; + } + if (typeof value !== "function" && typeof value !== "object") { + return false; + } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { + return false; + } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } : function isCallable(value) { + if (isDDA(value)) { + return true; + } + if (!value) { + return false; + } + if (typeof value !== "function" && typeof value !== "object") { + return false; + } + if (hasToStringTag) { + return tryFunctionObject(value); + } + if (isES6ClassFn(value)) { + return false; + } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) { + return false; + } + return tryFunctionObject(value); + }; + } +}); + +// node_modules/.pnpm/for-each@0.3.3/node_modules/for-each/index.js +var require_for_each = __commonJS({ + "node_modules/.pnpm/for-each@0.3.3/node_modules/for-each/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var isCallable = require_is_callable(); + var toStr = Object.prototype.toString; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var forEachArray = function forEachArray2(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } + }; + var forEachString = function forEachString2(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } + }; + var forEachObject = function forEachObject2(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } + }; + var forEach2 = function forEach3(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError("iterator must be a function"); + } + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + if (toStr.call(list) === "[object Array]") { + forEachArray(list, iterator, receiver); + } else if (typeof list === "string") { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } + }; + module2.exports = forEach2; + } +}); + +// node_modules/.pnpm/available-typed-arrays@1.0.6/node_modules/available-typed-arrays/index.js +var require_available_typed_arrays = __commonJS({ + "node_modules/.pnpm/available-typed-arrays@1.0.6/node_modules/available-typed-arrays/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var possibleNames = [ + "BigInt64Array", + "BigUint64Array", + "Float32Array", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray" + ]; + var g = typeof globalThis === "undefined" ? global : globalThis; + module2.exports = function availableTypedArrays() { + var out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === "function") { + out[out.length] = possibleNames[i]; + } + } + return out; + }; + } +}); + +// node_modules/.pnpm/which-typed-array@1.1.14/node_modules/which-typed-array/index.js +var require_which_typed_array = __commonJS({ + "node_modules/.pnpm/which-typed-array@1.1.14/node_modules/which-typed-array/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var forEach2 = require_for_each(); + var availableTypedArrays = require_available_typed_arrays(); + var callBind = require_call_bind(); + var callBound = require_callBound(); + var gOPD = require_gopd(); + var $toString = callBound("Object.prototype.toString"); + var hasToStringTag = require_shams2()(); + var g = typeof globalThis === "undefined" ? global : globalThis; + var typedArrays = availableTypedArrays(); + var $slice = callBound("String.prototype.slice"); + var getPrototypeOf = Object.getPrototypeOf; + var $indexOf = callBound("Array.prototype.indexOf", true) || /** @type {(array: readonly unknown[], value: unknown) => keyof array} */ + function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; + }; + var cache = { __proto__: null }; + if (hasToStringTag && gOPD && getPrototypeOf) { + forEach2(typedArrays, function(typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + cache["$" + typedArray] = callBind(descriptor.get); + } + }); + } else { + forEach2(typedArrays, function(typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + cache["$" + typedArray] = callBind(fn); + } + }); + } + var tryTypedArrays = function tryAllTypedArrays(value) { + var found = false; + forEach2( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, typeof cache>} */ + /** @type {any} */ + cache, + /** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ + function(getter, typedArray) { + if (!found) { + try { + if ("$" + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { + } + } + } + ); + return found; + }; + var trySlices = function tryAllSlices(value) { + var found = false; + forEach2( + // eslint-disable-next-line no-extra-parens + /** @type {any} */ + cache, + /** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */ + function(getter, name) { + if (!found) { + try { + getter(value); + found = $slice(name, 1); + } catch (e) { + } + } + } + ); + return found; + }; + module2.exports = function whichTypedArray(value) { + if (!value || typeof value !== "object") { + return false; + } + if (!hasToStringTag) { + var tag2 = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag2) > -1) { + return tag2; + } + if (tag2 !== "Object") { + return false; + } + return trySlices(value); + } + if (!gOPD) { + return null; + } + return tryTypedArrays(value); + }; + } +}); + +// node_modules/.pnpm/array-buffer-byte-length@1.0.1/node_modules/array-buffer-byte-length/index.js +var require_array_buffer_byte_length = __commonJS({ + "node_modules/.pnpm/array-buffer-byte-length@1.0.1/node_modules/array-buffer-byte-length/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var callBound = require_callBound(); + var $byteLength = callBound("ArrayBuffer.prototype.byteLength", true); + var isArrayBuffer = require_is_array_buffer(); + module2.exports = function byteLength(ab) { + if (!isArrayBuffer(ab)) { + return NaN; + } + return $byteLength ? $byteLength(ab) : ab.byteLength; + }; + } +}); + +// node_modules/.pnpm/deep-equal@2.2.3/node_modules/deep-equal/index.js +var require_deep_equal = __commonJS({ + "node_modules/.pnpm/deep-equal@2.2.3/node_modules/deep-equal/index.js"(exports2, module2) { + "use strict"; + init_polyfill_buffer(); + var assign2 = require_object(); + var callBound = require_callBound(); + var flags = require_regexp_prototype(); + var GetIntrinsic = require_get_intrinsic(); + var getIterator3 = require_es_get_iterator(); + var getSideChannel = require_side_channel(); + var is = require_object_is(); + var isArguments = require_is_arguments(); + var isArray = require_isarray(); + var isArrayBuffer = require_is_array_buffer(); + var isDate = require_is_date_object(); + var isRegex = require_is_regex(); + var isSharedArrayBuffer = require_is_shared_array_buffer(); + var objectKeys = require_object_keys(); + var whichBoxedPrimitive = require_which_boxed_primitive(); + var whichCollection = require_which_collection(); + var whichTypedArray = require_which_typed_array(); + var byteLength = require_array_buffer_byte_length(); + var sabByteLength = callBound("SharedArrayBuffer.prototype.byteLength", true); + var $getTime = callBound("Date.prototype.getTime"); + var gPO = Object.getPrototypeOf; + var $objToString = callBound("Object.prototype.toString"); + var $Set = GetIntrinsic("%Set%", true); + var $mapHas = callBound("Map.prototype.has", true); + var $mapGet = callBound("Map.prototype.get", true); + var $mapSize = callBound("Map.prototype.size", true); + var $setAdd = callBound("Set.prototype.add", true); + var $setDelete = callBound("Set.prototype.delete", true); + var $setHas = callBound("Set.prototype.has", true); + var $setSize = callBound("Set.prototype.size", true); + function setHasEqualElement(set, val1, opts, channel) { + var i = getIterator3(set); + var result; + while ((result = i.next()) && !result.done) { + if (internalDeepEqual(val1, result.value, opts, channel)) { + $setDelete(set, result.value); + return true; + } + } + return false; + } + function findLooseMatchingPrimitives(prim) { + if (typeof prim === "undefined") { + return null; + } + if (typeof prim === "object") { + return void 0; + } + if (typeof prim === "symbol") { + return false; + } + if (typeof prim === "string" || typeof prim === "number") { + return +prim === +prim; + } + return true; + } + function mapMightHaveLoosePrim(a, b, prim, item, opts, channel) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + var curB = $mapGet(b, altValue); + var looseOpts = assign2({}, opts, { strict: false }); + if (typeof curB === "undefined" && !$mapHas(b, altValue) || !internalDeepEqual(item, curB, looseOpts, channel)) { + return false; + } + return !$mapHas(a, altValue) && internalDeepEqual(item, curB, looseOpts, channel); + } + function setMightHaveLoosePrim(a, b, prim) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + return $setHas(b, altValue) && !$setHas(a, altValue); + } + function mapHasEqualEntry(set, map, key1, item1, opts, channel) { + var i = getIterator3(set); + var result; + var key2; + while ((result = i.next()) && !result.done) { + key2 = result.value; + if ( + // eslint-disable-next-line no-use-before-define + internalDeepEqual(key1, key2, opts, channel) && internalDeepEqual(item1, $mapGet(map, key2), opts, channel) + ) { + $setDelete(set, key2); + return true; + } + } + return false; + } + function internalDeepEqual(actual, expected, options, channel) { + var opts = options || {}; + if (opts.strict ? is(actual, expected) : actual === expected) { + return true; + } + var actualBoxed = whichBoxedPrimitive(actual); + var expectedBoxed = whichBoxedPrimitive(expected); + if (actualBoxed !== expectedBoxed) { + return false; + } + if (!actual || !expected || typeof actual !== "object" && typeof expected !== "object") { + return opts.strict ? is(actual, expected) : actual == expected; + } + var hasActual = channel.has(actual); + var hasExpected = channel.has(expected); + var sentinel; + if (hasActual && hasExpected) { + if (channel.get(actual) === channel.get(expected)) { + return true; + } + } else { + sentinel = {}; + } + if (!hasActual) { + channel.set(actual, sentinel); + } + if (!hasExpected) { + channel.set(expected, sentinel); + } + return objEquiv(actual, expected, opts, channel); + } + function isBuffer(x) { + if (!x || typeof x !== "object" || typeof x.length !== "number") { + return false; + } + if (typeof x.copy !== "function" || typeof x.slice !== "function") { + return false; + } + if (x.length > 0 && typeof x[0] !== "number") { + return false; + } + return !!(x.constructor && x.constructor.isBuffer && x.constructor.isBuffer(x)); + } + function setEquiv(a, b, opts, channel) { + if ($setSize(a) !== $setSize(b)) { + return false; + } + var iA = getIterator3(a); + var iB = getIterator3(b); + var resultA; + var resultB; + var set; + while ((resultA = iA.next()) && !resultA.done) { + if (resultA.value && typeof resultA.value === "object") { + if (!set) { + set = new $Set(); + } + $setAdd(set, resultA.value); + } else if (!$setHas(b, resultA.value)) { + if (opts.strict) { + return false; + } + if (!setMightHaveLoosePrim(a, b, resultA.value)) { + return false; + } + if (!set) { + set = new $Set(); + } + $setAdd(set, resultA.value); + } + } + if (set) { + while ((resultB = iB.next()) && !resultB.done) { + if (resultB.value && typeof resultB.value === "object") { + if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) { + return false; + } + } else if (!opts.strict && !$setHas(a, resultB.value) && !setHasEqualElement(set, resultB.value, opts.strict, channel)) { + return false; + } + } + return $setSize(set) === 0; + } + return true; + } + function mapEquiv(a, b, opts, channel) { + if ($mapSize(a) !== $mapSize(b)) { + return false; + } + var iA = getIterator3(a); + var iB = getIterator3(b); + var resultA; + var resultB; + var set; + var key2; + var item1; + var item2; + while ((resultA = iA.next()) && !resultA.done) { + key2 = resultA.value[0]; + item1 = resultA.value[1]; + if (key2 && typeof key2 === "object") { + if (!set) { + set = new $Set(); + } + $setAdd(set, key2); + } else { + item2 = $mapGet(b, key2); + if (typeof item2 === "undefined" && !$mapHas(b, key2) || !internalDeepEqual(item1, item2, opts, channel)) { + if (opts.strict) { + return false; + } + if (!mapMightHaveLoosePrim(a, b, key2, item1, opts, channel)) { + return false; + } + if (!set) { + set = new $Set(); + } + $setAdd(set, key2); + } + } + } + if (set) { + while ((resultB = iB.next()) && !resultB.done) { + key2 = resultB.value[0]; + item2 = resultB.value[1]; + if (key2 && typeof key2 === "object") { + if (!mapHasEqualEntry(set, a, key2, item2, opts, channel)) { + return false; + } + } else if (!opts.strict && (!a.has(key2) || !internalDeepEqual($mapGet(a, key2), item2, opts, channel)) && !mapHasEqualEntry(set, a, key2, item2, assign2({}, opts, { strict: false }), channel)) { + return false; + } + } + return $setSize(set) === 0; + } + return true; + } + function objEquiv(a, b, opts, channel) { + var i, key2; + if (typeof a !== typeof b) { + return false; + } + if (a == null || b == null) { + return false; + } + if ($objToString(a) !== $objToString(b)) { + return false; + } + if (isArguments(a) !== isArguments(b)) { + return false; + } + var aIsArray = isArray(a); + var bIsArray = isArray(b); + if (aIsArray !== bIsArray) { + return false; + } + var aIsError = a instanceof Error; + var bIsError = b instanceof Error; + if (aIsError !== bIsError) { + return false; + } + if (aIsError || bIsError) { + if (a.name !== b.name || a.message !== b.message) { + return false; + } + } + var aIsRegex = isRegex(a); + var bIsRegex = isRegex(b); + if (aIsRegex !== bIsRegex) { + return false; + } + if ((aIsRegex || bIsRegex) && (a.source !== b.source || flags(a) !== flags(b))) { + return false; + } + var aIsDate = isDate(a); + var bIsDate = isDate(b); + if (aIsDate !== bIsDate) { + return false; + } + if (aIsDate || bIsDate) { + if ($getTime(a) !== $getTime(b)) { + return false; + } + } + if (opts.strict && gPO && gPO(a) !== gPO(b)) { + return false; + } + var aWhich = whichTypedArray(a); + var bWhich = whichTypedArray(b); + if (aWhich !== bWhich) { + return false; + } + if (aWhich || bWhich) { + if (a.length !== b.length) { + return false; + } + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + var aIsBuffer = isBuffer(a); + var bIsBuffer = isBuffer(b); + if (aIsBuffer !== bIsBuffer) { + return false; + } + if (aIsBuffer || bIsBuffer) { + if (a.length !== b.length) { + return false; + } + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + var aIsArrayBuffer = isArrayBuffer(a); + var bIsArrayBuffer = isArrayBuffer(b); + if (aIsArrayBuffer !== bIsArrayBuffer) { + return false; + } + if (aIsArrayBuffer || bIsArrayBuffer) { + if (byteLength(a) !== byteLength(b)) { + return false; + } + return typeof Uint8Array === "function" && internalDeepEqual(new Uint8Array(a), new Uint8Array(b), opts, channel); + } + var aIsSAB = isSharedArrayBuffer(a); + var bIsSAB = isSharedArrayBuffer(b); + if (aIsSAB !== bIsSAB) { + return false; + } + if (aIsSAB || bIsSAB) { + if (sabByteLength(a) !== sabByteLength(b)) { + return false; + } + return typeof Uint8Array === "function" && internalDeepEqual(new Uint8Array(a), new Uint8Array(b), opts, channel); + } + if (typeof a !== typeof b) { + return false; + } + var ka = objectKeys(a); + var kb = objectKeys(b); + if (ka.length !== kb.length) { + return false; + } + ka.sort(); + kb.sort(); + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) { + return false; + } + } + for (i = ka.length - 1; i >= 0; i--) { + key2 = ka[i]; + if (!internalDeepEqual(a[key2], b[key2], opts, channel)) { + return false; + } + } + var aCollection = whichCollection(a); + var bCollection = whichCollection(b); + if (aCollection !== bCollection) { + return false; + } + if (aCollection === "Set" || bCollection === "Set") { + return setEquiv(a, b, opts, channel); + } + if (aCollection === "Map") { + return mapEquiv(a, b, opts, channel); + } + return true; + } + module2.exports = function deepEqual2(a, b, opts) { + return internalDeepEqual(a, b, opts, getSideChannel()); + }; + } +}); + +// node_modules/.pnpm/js-sha256@0.9.0/node_modules/js-sha256/src/sha256.js +var require_sha256 = __commonJS({ + "node_modules/.pnpm/js-sha256@0.9.0/node_modules/js-sha256/src/sha256.js"(exports, module) { + init_polyfill_buffer(); + (function() { + "use strict"; + var ERROR = "input is invalid type"; + var WINDOW = typeof window === "object"; + var root = WINDOW ? window : {}; + if (root.JS_SHA256_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === "object"; + var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; + if (NODE_JS) { + root = global; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === "object" && module.exports; + var AMD = typeof define === "function" && define.amd; + var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; + var HEX_CHARS = "0123456789abcdef".split(""); + var EXTRA = [-2147483648, 8388608, 32768, 128]; + var SHIFT = [24, 16, 8, 0]; + var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]; + var OUTPUT_TYPES = ["hex", "array", "digest", "arrayBuffer"]; + var blocks = []; + if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) { + Array.isArray = function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + } + if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function(obj) { + return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + var createOutputMethod = function(outputType, is2242) { + return function(message) { + return new Sha256(is2242, true).update(message)[outputType](); + }; + }; + var createMethod = function(is2242) { + var method2 = createOutputMethod("hex", is2242); + if (NODE_JS) { + method2 = nodeWrap(method2, is2242); + } + method2.create = function() { + return new Sha256(is2242); + }; + method2.update = function(message) { + return method2.create().update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method2[type] = createOutputMethod(type, is2242); + } + return method2; + }; + var nodeWrap = function(method, is224) { + var crypto = eval("require('crypto')"); + var Buffer = eval("require('buffer').Buffer"); + var algorithm = is224 ? "sha224" : "sha256"; + var nodeMethod = function(message) { + if (typeof message === "string") { + return crypto.createHash(algorithm).update(message, "utf8").digest("hex"); + } else { + if (message === null || message === void 0) { + throw new Error(ERROR); + } else if (message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } + } + if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) { + return crypto.createHash(algorithm).update(new Buffer(message)).digest("hex"); + } else { + return method(message); + } + }; + return nodeMethod; + }; + var createHmacOutputMethod = function(outputType, is2242) { + return function(key2, message) { + return new HmacSha256(key2, is2242, true).update(message)[outputType](); + }; + }; + var createHmacMethod = function(is2242) { + var method2 = createHmacOutputMethod("hex", is2242); + method2.create = function(key2) { + return new HmacSha256(key2, is2242); + }; + method2.update = function(key2, message) { + return method2.create(key2).update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method2[type] = createHmacOutputMethod(type, is2242); + } + return method2; + }; + function Sha256(is2242, sharedMemory) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + if (is2242) { + this.h0 = 3238371032; + this.h1 = 914150663; + this.h2 = 812702999; + this.h3 = 4144912697; + this.h4 = 4290775857; + this.h5 = 1750603025; + this.h6 = 1694076839; + this.h7 = 3204075428; + } else { + this.h0 = 1779033703; + this.h1 = 3144134277; + this.h2 = 1013904242; + this.h3 = 2773480762; + this.h4 = 1359893119; + this.h5 = 2600822924; + this.h6 = 528734635; + this.h7 = 1541459225; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is2242; + } + Sha256.prototype.update = function(message) { + if (this.finalized) { + return; + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(ERROR); + } + } + } else { + throw new Error(ERROR); + } + notString = true; + } + var code, index2 = 0, i, length = message.length, blocks2 = this.blocks; + while (index2 < length) { + if (this.hashed) { + this.hashed = false; + blocks2[0] = this.block; + blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; + } + if (notString) { + for (i = this.start; index2 < length && i < 64; ++index2) { + blocks2[i >> 2] |= message[index2] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index2 < length && i < 64; ++index2) { + code = message.charCodeAt(index2); + if (code < 128) { + blocks2[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 2048) { + blocks2[i >> 2] |= (192 | code >> 6) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks2[i >> 2] |= (224 | code >> 12) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code >> 6 & 63) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index2) & 1023); + blocks2[i >> 2] |= (240 | code >> 18) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code >> 12 & 63) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code >> 6 & 63) << SHIFT[i++ & 3]; + blocks2[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks2[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; + }; + Sha256.prototype.finalize = function() { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks2 = this.blocks, i = this.lastByteIndex; + blocks2[16] = this.block; + blocks2[i >> 2] |= EXTRA[i & 3]; + this.block = blocks2[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks2[0] = this.block; + blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; + } + blocks2[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks2[15] = this.bytes << 3; + this.hash(); + }; + Sha256.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks2 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + t1 = blocks2[j - 15]; + s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; + t1 = blocks2[j - 2]; + s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + blocks2[j] = blocks2[j - 16] + s0 + blocks2[j - 7] + s1 << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks2[0] - 1413257819; + h = t1 - 150054599 << 0; + d = t1 + 24177077 << 0; + } else { + ab = 704751109; + t1 = blocks2[0] - 210244248; + h = t1 - 1521486534 << 0; + d = t1 + 143694565 << 0; + } + this.first = false; + } else { + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ab = a & b; + maj = ab ^ a & c ^ bc; + ch = e & f ^ ~e & g; + t1 = h + s1 + ch + K[j] + blocks2[j]; + t2 = s0 + maj; + h = d + t1 << 0; + d = t1 + t2 << 0; + } + s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); + s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); + da = d & a; + maj = da ^ d & b ^ ab; + ch = h & e ^ ~h & f; + t1 = g + s1 + ch + K[j + 1] + blocks2[j + 1]; + t2 = s0 + maj; + g = c + t1 << 0; + c = t1 + t2 << 0; + s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); + s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); + cd = c & d; + maj = cd ^ c & a ^ da; + ch = g & h ^ ~g & e; + t1 = f + s1 + ch + K[j + 2] + blocks2[j + 2]; + t2 = s0 + maj; + f = b + t1 << 0; + b = t1 + t2 << 0; + s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); + s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); + bc = b & c; + maj = bc ^ b & d ^ cd; + ch = f & g ^ ~f & h; + t1 = e + s1 + ch + K[j + 3] + blocks2[j + 3]; + t2 = s0 + maj; + e = a + t1 << 0; + a = t1 + t2 << 0; + } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; + this.h5 = this.h5 + f << 0; + this.h6 = this.h6 + g << 0; + this.h7 = this.h7 + h << 0; + }; + Sha256.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >> 28 & 15] + HEX_CHARS[h2 >> 24 & 15] + HEX_CHARS[h2 >> 20 & 15] + HEX_CHARS[h2 >> 16 & 15] + HEX_CHARS[h2 >> 12 & 15] + HEX_CHARS[h2 >> 8 & 15] + HEX_CHARS[h2 >> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >> 28 & 15] + HEX_CHARS[h5 >> 24 & 15] + HEX_CHARS[h5 >> 20 & 15] + HEX_CHARS[h5 >> 16 & 15] + HEX_CHARS[h5 >> 12 & 15] + HEX_CHARS[h5 >> 8 & 15] + HEX_CHARS[h5 >> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >> 28 & 15] + HEX_CHARS[h6 >> 24 & 15] + HEX_CHARS[h6 >> 20 & 15] + HEX_CHARS[h6 >> 16 & 15] + HEX_CHARS[h6 >> 12 & 15] + HEX_CHARS[h6 >> 8 & 15] + HEX_CHARS[h6 >> 4 & 15] + HEX_CHARS[h6 & 15]; + if (!this.is224) { + hex += HEX_CHARS[h7 >> 28 & 15] + HEX_CHARS[h7 >> 24 & 15] + HEX_CHARS[h7 >> 20 & 15] + HEX_CHARS[h7 >> 16 & 15] + HEX_CHARS[h7 >> 12 & 15] + HEX_CHARS[h7 >> 8 & 15] + HEX_CHARS[h7 >> 4 & 15] + HEX_CHARS[h7 & 15]; + } + return hex; + }; + Sha256.prototype.toString = Sha256.prototype.hex; + Sha256.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr = [ + h0 >> 24 & 255, + h0 >> 16 & 255, + h0 >> 8 & 255, + h0 & 255, + h1 >> 24 & 255, + h1 >> 16 & 255, + h1 >> 8 & 255, + h1 & 255, + h2 >> 24 & 255, + h2 >> 16 & 255, + h2 >> 8 & 255, + h2 & 255, + h3 >> 24 & 255, + h3 >> 16 & 255, + h3 >> 8 & 255, + h3 & 255, + h4 >> 24 & 255, + h4 >> 16 & 255, + h4 >> 8 & 255, + h4 & 255, + h5 >> 24 & 255, + h5 >> 16 & 255, + h5 >> 8 & 255, + h5 & 255, + h6 >> 24 & 255, + h6 >> 16 & 255, + h6 >> 8 & 255, + h6 & 255 + ]; + if (!this.is224) { + arr.push(h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255); + } + return arr; + }; + Sha256.prototype.array = Sha256.prototype.digest; + Sha256.prototype.arrayBuffer = function() { + this.finalize(); + var buffer2 = new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer2); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) { + dataView.setUint32(28, this.h7); + } + return buffer2; + }; + function HmacSha256(key2, is2242, sharedMemory) { + var i, type = typeof key2; + if (type === "string") { + var bytes = [], length = key2.length, index2 = 0, code; + for (i = 0; i < length; ++i) { + code = key2.charCodeAt(i); + if (code < 128) { + bytes[index2++] = code; + } else if (code < 2048) { + bytes[index2++] = 192 | code >> 6; + bytes[index2++] = 128 | code & 63; + } else if (code < 55296 || code >= 57344) { + bytes[index2++] = 224 | code >> 12; + bytes[index2++] = 128 | code >> 6 & 63; + bytes[index2++] = 128 | code & 63; + } else { + code = 65536 + ((code & 1023) << 10 | key2.charCodeAt(++i) & 1023); + bytes[index2++] = 240 | code >> 18; + bytes[index2++] = 128 | code >> 12 & 63; + bytes[index2++] = 128 | code >> 6 & 63; + bytes[index2++] = 128 | code & 63; + } + } + key2 = bytes; + } else { + if (type === "object") { + if (key2 === null) { + throw new Error(ERROR); + } else if (ARRAY_BUFFER && key2.constructor === ArrayBuffer) { + key2 = new Uint8Array(key2); + } else if (!Array.isArray(key2)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(key2)) { + throw new Error(ERROR); + } + } + } else { + throw new Error(ERROR); + } + } + if (key2.length > 64) { + key2 = new Sha256(is2242, true).update(key2).array(); + } + var oKeyPad = [], iKeyPad = []; + for (i = 0; i < 64; ++i) { + var b = key2[i] || 0; + oKeyPad[i] = 92 ^ b; + iKeyPad[i] = 54 ^ b; + } + Sha256.call(this, is2242, sharedMemory); + this.update(iKeyPad); + this.oKeyPad = oKeyPad; + this.inner = true; + this.sharedMemory = sharedMemory; + } + HmacSha256.prototype = new Sha256(); + HmacSha256.prototype.finalize = function() { + Sha256.prototype.finalize.call(this); + if (this.inner) { + this.inner = false; + var innerHash = this.array(); + Sha256.call(this, this.is224, this.sharedMemory); + this.update(this.oKeyPad); + this.update(innerHash); + Sha256.prototype.finalize.call(this); + } + }; + var exports = createMethod(); + exports.sha256 = exports; + exports.sha224 = createMethod(true); + exports.sha256.hmac = createHmacMethod(); + exports.sha224.hmac = createHmacMethod(true); + if (COMMON_JS) { + module.exports = exports; + } else { + root.sha256 = exports.sha256; + root.sha224 = exports.sha224; + if (AMD) { + define(function() { + return exports; + }); + } + } + })(); + } +}); + +// node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/compiler.js +var require_compiler = __commonJS({ + "node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/compiler.js"(exports2) { + init_polyfill_buffer(); + (function(Hogan4) { + var rIsWhitespace = /\S/, rQuot = /\"/g, rNewline = /\n/g, rCr = /\r/g, rSlash = /\\/g, rLineSep = /\u2028/, rParagraphSep = /\u2029/; + Hogan4.tags = { + "#": 1, + "^": 2, + "<": 3, + "$": 4, + "/": 5, + "!": 6, + ">": 7, + "=": 8, + "_v": 9, + "{": 10, + "&": 11, + "_t": 12 + }; + Hogan4.scan = function scan(text2, delimiters) { + var len = text2.length, IN_TEXT = 0, IN_TAG_TYPE = 1, IN_TAG = 2, state = IN_TEXT, tagType = null, tag2 = null, buf = "", tokens = [], seenTag = false, i = 0, lineStart = 0, otag = "{{", ctag = "}}"; + function addBuf() { + if (buf.length > 0) { + tokens.push({ tag: "_t", text: new String(buf) }); + buf = ""; + } + } + function lineIsWhitespace() { + var isAllWhitespace = true; + for (var j = lineStart; j < tokens.length; j++) { + isAllWhitespace = Hogan4.tags[tokens[j].tag] < Hogan4.tags["_v"] || tokens[j].tag == "_t" && tokens[j].text.match(rIsWhitespace) === null; + if (!isAllWhitespace) { + return false; + } + } + return isAllWhitespace; + } + function filterLine(haveSeenTag, noNewLine) { + addBuf(); + if (haveSeenTag && lineIsWhitespace()) { + for (var j = lineStart, next; j < tokens.length; j++) { + if (tokens[j].text) { + if ((next = tokens[j + 1]) && next.tag == ">") { + next.indent = tokens[j].text.toString(); + } + tokens.splice(j, 1); + } + } + } else if (!noNewLine) { + tokens.push({ tag: "\n" }); + } + seenTag = false; + lineStart = tokens.length; + } + function changeDelimiters(text3, index2) { + var close = "=" + ctag, closeIndex = text3.indexOf(close, index2), delimiters2 = trim( + text3.substring(text3.indexOf("=", index2) + 1, closeIndex) + ).split(" "); + otag = delimiters2[0]; + ctag = delimiters2[delimiters2.length - 1]; + return closeIndex + close.length - 1; + } + if (delimiters) { + delimiters = delimiters.split(" "); + otag = delimiters[0]; + ctag = delimiters[1]; + } + for (i = 0; i < len; i++) { + if (state == IN_TEXT) { + if (tagChange(otag, text2, i)) { + --i; + addBuf(); + state = IN_TAG_TYPE; + } else { + if (text2.charAt(i) == "\n") { + filterLine(seenTag); + } else { + buf += text2.charAt(i); + } + } + } else if (state == IN_TAG_TYPE) { + i += otag.length - 1; + tag2 = Hogan4.tags[text2.charAt(i + 1)]; + tagType = tag2 ? text2.charAt(i + 1) : "_v"; + if (tagType == "=") { + i = changeDelimiters(text2, i); + state = IN_TEXT; + } else { + if (tag2) { + i++; + } + state = IN_TAG; + } + seenTag = i; + } else { + if (tagChange(ctag, text2, i)) { + tokens.push({ + tag: tagType, + n: trim(buf), + otag, + ctag, + i: tagType == "/" ? seenTag - otag.length : i + ctag.length + }); + buf = ""; + i += ctag.length - 1; + state = IN_TEXT; + if (tagType == "{") { + if (ctag == "}}") { + i++; + } else { + cleanTripleStache(tokens[tokens.length - 1]); + } + } + } else { + buf += text2.charAt(i); + } + } + } + filterLine(seenTag, true); + return tokens; + }; + function cleanTripleStache(token) { + if (token.n.substr(token.n.length - 1) === "}") { + token.n = token.n.substring(0, token.n.length - 1); + } + } + function trim(s) { + if (s.trim) { + return s.trim(); + } + return s.replace(/^\s*|\s*$/g, ""); + } + function tagChange(tag2, text2, index2) { + if (text2.charAt(index2) != tag2.charAt(0)) { + return false; + } + for (var i = 1, l = tag2.length; i < l; i++) { + if (text2.charAt(index2 + i) != tag2.charAt(i)) { + return false; + } + } + return true; + } + var allowedInSuper = { "_t": true, "\n": true, "$": true, "/": true }; + function buildTree(tokens, kind, stack, customTags) { + var instructions = [], opener = null, tail = null, token = null; + tail = stack[stack.length - 1]; + while (tokens.length > 0) { + token = tokens.shift(); + if (tail && tail.tag == "<" && !(token.tag in allowedInSuper)) { + throw new Error("Illegal content in < super tag."); + } + if (Hogan4.tags[token.tag] <= Hogan4.tags["$"] || isOpener(token, customTags)) { + stack.push(token); + token.nodes = buildTree(tokens, token.tag, stack, customTags); + } else if (token.tag == "/") { + if (stack.length === 0) { + throw new Error("Closing tag without opener: /" + token.n); + } + opener = stack.pop(); + if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) { + throw new Error("Nesting error: " + opener.n + " vs. " + token.n); + } + opener.end = token.i; + return instructions; + } else if (token.tag == "\n") { + token.last = tokens.length == 0 || tokens[0].tag == "\n"; + } + instructions.push(token); + } + if (stack.length > 0) { + throw new Error("missing closing tag: " + stack.pop().n); + } + return instructions; + } + function isOpener(token, tags) { + for (var i = 0, l = tags.length; i < l; i++) { + if (tags[i].o == token.n) { + token.tag = "#"; + return true; + } + } + } + function isCloser(close, open, tags) { + for (var i = 0, l = tags.length; i < l; i++) { + if (tags[i].c == close && tags[i].o == open) { + return true; + } + } + } + function stringifySubstitutions(obj) { + var items = []; + for (var key2 in obj) { + items.push('"' + esc(key2) + '": function(c,p,t,i) {' + obj[key2] + "}"); + } + return "{ " + items.join(",") + " }"; + } + function stringifyPartials(codeObj) { + var partials = []; + for (var key2 in codeObj.partials) { + partials.push('"' + esc(key2) + '":{name:"' + esc(codeObj.partials[key2].name) + '", ' + stringifyPartials(codeObj.partials[key2]) + "}"); + } + return "partials: {" + partials.join(",") + "}, subs: " + stringifySubstitutions(codeObj.subs); + } + Hogan4.stringify = function(codeObj, text2, options) { + return "{code: function (c,p,i) { " + Hogan4.wrapMain(codeObj.code) + " }," + stringifyPartials(codeObj) + "}"; + }; + var serialNo = 0; + Hogan4.generate = function(tree, text2, options) { + serialNo = 0; + var context = { code: "", subs: {}, partials: {} }; + Hogan4.walk(tree, context); + if (options.asString) { + return this.stringify(context, text2, options); + } + return this.makeTemplate(context, text2, options); + }; + Hogan4.wrapMain = function(code) { + return 'var t=this;t.b(i=i||"");' + code + "return t.fl();"; + }; + Hogan4.template = Hogan4.Template; + Hogan4.makeTemplate = function(codeObj, text2, options) { + var template = this.makePartials(codeObj); + template.code = new Function("c", "p", "i", this.wrapMain(codeObj.code)); + return new this.template(template, text2, this, options); + }; + Hogan4.makePartials = function(codeObj) { + var key2, template = { subs: {}, partials: codeObj.partials, name: codeObj.name }; + for (key2 in template.partials) { + template.partials[key2] = this.makePartials(template.partials[key2]); + } + for (key2 in codeObj.subs) { + template.subs[key2] = new Function("c", "p", "t", "i", codeObj.subs[key2]); + } + return template; + }; + function esc(s) { + return s.replace(rSlash, "\\\\").replace(rQuot, '\\"').replace(rNewline, "\\n").replace(rCr, "\\r").replace(rLineSep, "\\u2028").replace(rParagraphSep, "\\u2029"); + } + function chooseMethod(s) { + return ~s.indexOf(".") ? "d" : "f"; + } + function createPartial(node, context) { + var prefix = "<" + (context.prefix || ""); + var sym = prefix + node.n + serialNo++; + context.partials[sym] = { name: node.n, partials: {} }; + context.code += 't.b(t.rp("' + esc(sym) + '",c,p,"' + (node.indent || "") + '"));'; + return sym; + } + Hogan4.codegen = { + "#": function(node, context) { + context.code += "if(t.s(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),c,p,0,' + node.i + "," + node.end + ',"' + node.otag + " " + node.ctag + '")){t.rs(c,p,function(c,p,t){'; + Hogan4.walk(node.nodes, context); + context.code += "});c.pop();}"; + }, + "^": function(node, context) { + context.code += "if(!t.s(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),c,p,1,0,0,"")){'; + Hogan4.walk(node.nodes, context); + context.code += "};"; + }, + ">": createPartial, + "<": function(node, context) { + var ctx = { partials: {}, code: "", subs: {}, inPartial: true }; + Hogan4.walk(node.nodes, ctx); + var template = context.partials[createPartial(node, context)]; + template.subs = ctx.subs; + template.partials = ctx.partials; + }, + "$": function(node, context) { + var ctx = { subs: {}, code: "", partials: context.partials, prefix: node.n }; + Hogan4.walk(node.nodes, ctx); + context.subs[node.n] = ctx.code; + if (!context.inPartial) { + context.code += 't.sub("' + esc(node.n) + '",c,p,i);'; + } + }, + "\n": function(node, context) { + context.code += write('"\\n"' + (node.last ? "" : " + i")); + }, + "_v": function(node, context) { + context.code += "t.b(t.v(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));'; + }, + "_t": function(node, context) { + context.code += write('"' + esc(node.text) + '"'); + }, + "{": tripleStache, + "&": tripleStache + }; + function tripleStache(node, context) { + context.code += "t.b(t.t(t." + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));'; + } + function write(s) { + return "t.b(" + s + ");"; + } + Hogan4.walk = function(nodelist, context) { + var func; + for (var i = 0, l = nodelist.length; i < l; i++) { + func = Hogan4.codegen[nodelist[i].tag]; + func && func(nodelist[i], context); + } + return context; + }; + Hogan4.parse = function(tokens, text2, options) { + options = options || {}; + return buildTree(tokens, "", [], options.sectionTags || []); + }; + Hogan4.cache = {}; + Hogan4.cacheKey = function(text2, options) { + return [text2, !!options.asString, !!options.disableLambda, options.delimiters, !!options.modelGet].join("||"); + }; + Hogan4.compile = function(text2, options) { + options = options || {}; + var key2 = Hogan4.cacheKey(text2, options); + var template = this.cache[key2]; + if (template) { + var partials = template.partials; + for (var name in partials) { + delete partials[name].instance; + } + return template; + } + template = this.generate(this.parse(this.scan(text2, options.delimiters), text2, options), text2, options); + return this.cache[key2] = template; + }; + })(typeof exports2 !== "undefined" ? exports2 : Hogan); + } +}); + +// node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/template.js +var require_template = __commonJS({ + "node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/template.js"(exports2) { + init_polyfill_buffer(); + var Hogan4 = {}; + (function(Hogan5) { + Hogan5.Template = function(codeObj, text2, compiler, options) { + codeObj = codeObj || {}; + this.r = codeObj.code || this.r; + this.c = compiler; + this.options = options || {}; + this.text = text2 || ""; + this.partials = codeObj.partials || {}; + this.subs = codeObj.subs || {}; + this.buf = ""; + }; + Hogan5.Template.prototype = { + // render: replaced by generated code. + r: function(context, partials, indent2) { + return ""; + }, + // variable escaping + v: hoganEscape, + // triple stache + t: coerceToString, + render: function render(context, partials, indent2) { + return this.ri([context], partials || {}, indent2); + }, + // render internal -- a hook for overrides that catches partials too + ri: function(context, partials, indent2) { + return this.r(context, partials, indent2); + }, + // ensurePartial + ep: function(symbol, partials) { + var partial = this.partials[symbol]; + var template = partials[partial.name]; + if (partial.instance && partial.base == template) { + return partial.instance; + } + if (typeof template == "string") { + if (!this.c) { + throw new Error("No compiler available."); + } + template = this.c.compile(template, this.options); + } + if (!template) { + return null; + } + this.partials[symbol].base = template; + if (partial.subs) { + if (!partials.stackText) + partials.stackText = {}; + for (key in partial.subs) { + if (!partials.stackText[key]) { + partials.stackText[key] = this.activeSub !== void 0 && partials.stackText[this.activeSub] ? partials.stackText[this.activeSub] : this.text; + } + } + template = createSpecializedPartial( + template, + partial.subs, + partial.partials, + this.stackSubs, + this.stackPartials, + partials.stackText + ); + } + this.partials[symbol].instance = template; + return template; + }, + // tries to find a partial in the current scope and render it + rp: function(symbol, context, partials, indent2) { + var partial = this.ep(symbol, partials); + if (!partial) { + return ""; + } + return partial.ri(context, partials, indent2); + }, + // render a section + rs: function(context, partials, section) { + var tail = context[context.length - 1]; + if (!isArray(tail)) { + section(context, partials, this); + return; + } + for (var i = 0; i < tail.length; i++) { + context.push(tail[i]); + section(context, partials, this); + context.pop(); + } + }, + // maybe start a section + s: function(val, ctx, partials, inverted, start, end, tags) { + var pass; + if (isArray(val) && val.length === 0) { + return false; + } + if (typeof val == "function") { + val = this.ms(val, ctx, partials, inverted, start, end, tags); + } + pass = !!val; + if (!inverted && pass && ctx) { + ctx.push(typeof val == "object" ? val : ctx[ctx.length - 1]); + } + return pass; + }, + // find values with dotted names + d: function(key2, ctx, partials, returnFound) { + var found, names = key2.split("."), val = this.f(names[0], ctx, partials, returnFound), doModelGet = this.options.modelGet, cx = null; + if (key2 === "." && isArray(ctx[ctx.length - 2])) { + val = ctx[ctx.length - 1]; + } else { + for (var i = 1; i < names.length; i++) { + found = findInScope(names[i], val, doModelGet); + if (found !== void 0) { + cx = val; + val = found; + } else { + val = ""; + } + } + } + if (returnFound && !val) { + return false; + } + if (!returnFound && typeof val == "function") { + ctx.push(cx); + val = this.mv(val, ctx, partials); + ctx.pop(); + } + return val; + }, + // find values with normal names + f: function(key2, ctx, partials, returnFound) { + var val = false, v = null, found = false, doModelGet = this.options.modelGet; + for (var i = ctx.length - 1; i >= 0; i--) { + v = ctx[i]; + val = findInScope(key2, v, doModelGet); + if (val !== void 0) { + found = true; + break; + } + } + if (!found) { + return returnFound ? false : ""; + } + if (!returnFound && typeof val == "function") { + val = this.mv(val, ctx, partials); + } + return val; + }, + // higher order templates + ls: function(func, cx, partials, text2, tags) { + var oldTags = this.options.delimiters; + this.options.delimiters = tags; + this.b(this.ct(coerceToString(func.call(cx, text2)), cx, partials)); + this.options.delimiters = oldTags; + return false; + }, + // compile text + ct: function(text2, cx, partials) { + if (this.options.disableLambda) { + throw new Error("Lambda features disabled."); + } + return this.c.compile(text2, this.options).render(cx, partials); + }, + // template result buffering + b: function(s) { + this.buf += s; + }, + fl: function() { + var r = this.buf; + this.buf = ""; + return r; + }, + // method replace section + ms: function(func, ctx, partials, inverted, start, end, tags) { + var textSource, cx = ctx[ctx.length - 1], result = func.call(cx); + if (typeof result == "function") { + if (inverted) { + return true; + } else { + textSource = this.activeSub && this.subsText && this.subsText[this.activeSub] ? this.subsText[this.activeSub] : this.text; + return this.ls(result, cx, partials, textSource.substring(start, end), tags); + } + } + return result; + }, + // method replace variable + mv: function(func, ctx, partials) { + var cx = ctx[ctx.length - 1]; + var result = func.call(cx); + if (typeof result == "function") { + return this.ct(coerceToString(result.call(cx)), cx, partials); + } + return result; + }, + sub: function(name, context, partials, indent2) { + var f = this.subs[name]; + if (f) { + this.activeSub = name; + f(context, partials, this, indent2); + this.activeSub = false; + } + } + }; + function findInScope(key2, scope, doModelGet) { + var val; + if (scope && typeof scope == "object") { + if (scope[key2] !== void 0) { + val = scope[key2]; + } else if (doModelGet && scope.get && typeof scope.get == "function") { + val = scope.get(key2); + } + } + return val; + } + function createSpecializedPartial(instance10, subs, partials, stackSubs, stackPartials, stackText) { + function PartialTemplate() { + } + ; + PartialTemplate.prototype = instance10; + function Substitutions() { + } + ; + Substitutions.prototype = instance10.subs; + var key2; + var partial = new PartialTemplate(); + partial.subs = new Substitutions(); + partial.subsText = {}; + partial.buf = ""; + stackSubs = stackSubs || {}; + partial.stackSubs = stackSubs; + partial.subsText = stackText; + for (key2 in subs) { + if (!stackSubs[key2]) + stackSubs[key2] = subs[key2]; + } + for (key2 in stackSubs) { + partial.subs[key2] = stackSubs[key2]; + } + stackPartials = stackPartials || {}; + partial.stackPartials = stackPartials; + for (key2 in partials) { + if (!stackPartials[key2]) + stackPartials[key2] = partials[key2]; + } + for (key2 in stackPartials) { + partial.partials[key2] = stackPartials[key2]; + } + return partial; + } + var rAmp = /&/g, rLt = //g, rApos = /\'/g, rQuot = /\"/g, hChars = /[&<>\"\']/; + function coerceToString(val) { + return String(val === null || val === void 0 ? "" : val); + } + function hoganEscape(str) { + str = coerceToString(str); + return hChars.test(str) ? str.replace(rAmp, "&").replace(rLt, "<").replace(rGt, ">").replace(rApos, "'").replace(rQuot, """) : str; + } + var isArray = Array.isArray || function(a) { + return Object.prototype.toString.call(a) === "[object Array]"; + }; + })(typeof exports2 !== "undefined" ? exports2 : Hogan4); + } +}); + +// node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/hogan.js +var require_hogan = __commonJS({ + "node_modules/.pnpm/hogan.js@3.0.2/node_modules/hogan.js/lib/hogan.js"(exports2, module2) { + init_polyfill_buffer(); + var Hogan4 = require_compiler(); + Hogan4.Template = require_template().Template; + Hogan4.template = Hogan4.Template; + module2.exports = Hogan4; + } +}); + +// node_modules/.pnpm/feather-icons@4.29.1/node_modules/feather-icons/dist/feather.js +var require_feather = __commonJS({ + "node_modules/.pnpm/feather-icons@4.29.1/node_modules/feather-icons/dist/feather.js"(exports2, module2) { + init_polyfill_buffer(); + (function webpackUniversalModuleDefinition(root2, factory) { + if (typeof exports2 === "object" && typeof module2 === "object") + module2.exports = factory(); + else if (typeof define === "function" && define.amd) + define([], factory); + else if (typeof exports2 === "object") + exports2["feather"] = factory(); + else + root2["feather"] = factory(); + })(typeof self !== "undefined" ? self : exports2, function() { + return ( + /******/ + function(modules) { + var installedModules = {}; + function __webpack_require__(moduleId) { + if (installedModules[moduleId]) { + return installedModules[moduleId].exports; + } + var module3 = installedModules[moduleId] = { + /******/ + i: moduleId, + /******/ + l: false, + /******/ + exports: {} + /******/ + }; + modules[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__); + module3.l = true; + return module3.exports; + } + __webpack_require__.m = modules; + __webpack_require__.c = installedModules; + __webpack_require__.d = function(exports3, name, getter) { + if (!__webpack_require__.o(exports3, name)) { + Object.defineProperty(exports3, name, { + /******/ + configurable: false, + /******/ + enumerable: true, + /******/ + get: getter + /******/ + }); + } + }; + __webpack_require__.r = function(exports3) { + Object.defineProperty(exports3, "__esModule", { value: true }); + }; + __webpack_require__.n = function(module3) { + var getter = module3 && module3.__esModule ? ( + /******/ + function getDefault() { + return module3["default"]; + } + ) : ( + /******/ + function getModuleExports() { + return module3; + } + ); + __webpack_require__.d(getter, "a", getter); + return getter; + }; + __webpack_require__.o = function(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); + }; + __webpack_require__.p = ""; + return __webpack_require__(__webpack_require__.s = 0); + }({ + /***/ + "./dist/icons.json": ( + /*!*************************!*\ + !*** ./dist/icons.json ***! + \*************************/ + /*! exports provided: activity, airplay, alert-circle, alert-octagon, alert-triangle, align-center, align-justify, align-left, align-right, anchor, aperture, archive, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, award, bar-chart-2, bar-chart, battery-charging, battery, bell-off, bell, bluetooth, bold, book-open, book, bookmark, box, briefcase, calendar, camera-off, camera, cast, check-circle, check-square, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, chrome, circle, clipboard, clock, cloud-drizzle, cloud-lightning, cloud-off, cloud-rain, cloud-snow, cloud, code, codepen, codesandbox, coffee, columns, command, compass, copy, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, cpu, credit-card, crop, crosshair, database, delete, disc, divide-circle, divide-square, divide, dollar-sign, download-cloud, download, dribbble, droplet, edit-2, edit-3, edit, external-link, eye-off, eye, facebook, fast-forward, feather, figma, file-minus, file-plus, file-text, file, film, filter, flag, folder-minus, folder-plus, folder, framer, frown, gift, git-branch, git-commit, git-merge, git-pull-request, github, gitlab, globe, grid, hard-drive, hash, headphones, heart, help-circle, hexagon, home, image, inbox, info, instagram, italic, key, layers, layout, life-buoy, link-2, link, linkedin, list, loader, lock, log-in, log-out, mail, map-pin, map, maximize-2, maximize, meh, menu, message-circle, message-square, mic-off, mic, minimize-2, minimize, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, mouse-pointer, move, music, navigation-2, navigation, octagon, package, paperclip, pause-circle, pause, pen-tool, percent, phone-call, phone-forwarded, phone-incoming, phone-missed, phone-off, phone-outgoing, phone, pie-chart, play-circle, play, plus-circle, plus-square, plus, pocket, power, printer, radio, refresh-ccw, refresh-cw, repeat, rewind, rotate-ccw, rotate-cw, rss, save, scissors, search, send, server, settings, share-2, share, shield-off, shield, shopping-bag, shopping-cart, shuffle, sidebar, skip-back, skip-forward, slack, slash, sliders, smartphone, smile, speaker, square, star, stop-circle, sun, sunrise, sunset, table, tablet, tag, target, terminal, thermometer, thumbs-down, thumbs-up, toggle-left, toggle-right, tool, trash-2, trash, trello, trending-down, trending-up, triangle, truck, tv, twitch, twitter, type, umbrella, underline, unlock, upload-cloud, upload, user-check, user-minus, user-plus, user-x, user, users, video-off, video, voicemail, volume-1, volume-2, volume-x, volume, watch, wifi-off, wifi, wind, x-circle, x-octagon, x-square, x, youtube, zap-off, zap, zoom-in, zoom-out, default */ + /***/ + function(module3) { + module3.exports = { "activity": '', "airplay": '', "alert-circle": '', "alert-octagon": '', "alert-triangle": '', "align-center": '', "align-justify": '', "align-left": '', "align-right": '', "anchor": '', "aperture": '', "archive": '', "arrow-down-circle": '', "arrow-down-left": '', "arrow-down-right": '', "arrow-down": '', "arrow-left-circle": '', "arrow-left": '', "arrow-right-circle": '', "arrow-right": '', "arrow-up-circle": '', "arrow-up-left": '', "arrow-up-right": '', "arrow-up": '', "at-sign": '', "award": '', "bar-chart-2": '', "bar-chart": '', "battery-charging": '', "battery": '', "bell-off": '', "bell": '', "bluetooth": '', "bold": '', "book-open": '', "book": '', "bookmark": '', "box": '', "briefcase": '', "calendar": '', "camera-off": '', "camera": '', "cast": '', "check-circle": '', "check-square": '', "check": '', "chevron-down": '', "chevron-left": '', "chevron-right": '', "chevron-up": '', "chevrons-down": '', "chevrons-left": '', "chevrons-right": '', "chevrons-up": '', "chrome": '', "circle": '', "clipboard": '', "clock": '', "cloud-drizzle": '', "cloud-lightning": '', "cloud-off": '', "cloud-rain": '', "cloud-snow": '', "cloud": '', "code": '', "codepen": '', "codesandbox": '', "coffee": '', "columns": '', "command": '', "compass": '', "copy": '', "corner-down-left": '', "corner-down-right": '', "corner-left-down": '', "corner-left-up": '', "corner-right-down": '', "corner-right-up": '', "corner-up-left": '', "corner-up-right": '', "cpu": '', "credit-card": '', "crop": '', "crosshair": '', "database": '', "delete": '', "disc": '', "divide-circle": '', "divide-square": '', "divide": '', "dollar-sign": '', "download-cloud": '', "download": '', "dribbble": '', "droplet": '', "edit-2": '', "edit-3": '', "edit": '', "external-link": '', "eye-off": '', "eye": '', "facebook": '', "fast-forward": '', "feather": '', "figma": '', "file-minus": '', "file-plus": '', "file-text": '', "file": '', "film": '', "filter": '', "flag": '', "folder-minus": '', "folder-plus": '', "folder": '', "framer": '', "frown": '', "gift": '', "git-branch": '', "git-commit": '', "git-merge": '', "git-pull-request": '', "github": '', "gitlab": '', "globe": '', "grid": '', "hard-drive": '', "hash": '', "headphones": '', "heart": '', "help-circle": '', "hexagon": '', "home": '', "image": '', "inbox": '', "info": '', "instagram": '', "italic": '', "key": '', "layers": '', "layout": '', "life-buoy": '', "link-2": '', "link": '', "linkedin": '', "list": '', "loader": '', "lock": '', "log-in": '', "log-out": '', "mail": '', "map-pin": '', "map": '', "maximize-2": '', "maximize": '', "meh": '', "menu": '', "message-circle": '', "message-square": '', "mic-off": '', "mic": '', "minimize-2": '', "minimize": '', "minus-circle": '', "minus-square": '', "minus": '', "monitor": '', "moon": '', "more-horizontal": '', "more-vertical": '', "mouse-pointer": '', "move": '', "music": '', "navigation-2": '', "navigation": '', "octagon": '', "package": '', "paperclip": '', "pause-circle": '', "pause": '', "pen-tool": '', "percent": '', "phone-call": '', "phone-forwarded": '', "phone-incoming": '', "phone-missed": '', "phone-off": '', "phone-outgoing": '', "phone": '', "pie-chart": '', "play-circle": '', "play": '', "plus-circle": '', "plus-square": '', "plus": '', "pocket": '', "power": '', "printer": '', "radio": '', "refresh-ccw": '', "refresh-cw": '', "repeat": '', "rewind": '', "rotate-ccw": '', "rotate-cw": '', "rss": '', "save": '', "scissors": '', "search": '', "send": '', "server": '', "settings": '', "share-2": '', "share": '', "shield-off": '', "shield": '', "shopping-bag": '', "shopping-cart": '', "shuffle": '', "sidebar": '', "skip-back": '', "skip-forward": '', "slack": '', "slash": '', "sliders": '', "smartphone": '', "smile": '', "speaker": '', "square": '', "star": '', "stop-circle": '', "sun": '', "sunrise": '', "sunset": '', "table": '', "tablet": '', "tag": '', "target": '', "terminal": '', "thermometer": '', "thumbs-down": '', "thumbs-up": '', "toggle-left": '', "toggle-right": '', "tool": '', "trash-2": '', "trash": '', "trello": '', "trending-down": '', "trending-up": '', "triangle": '', "truck": '', "tv": '', "twitch": '', "twitter": '', "type": '', "umbrella": '', "underline": '', "unlock": '', "upload-cloud": '', "upload": '', "user-check": '', "user-minus": '', "user-plus": '', "user-x": '', "user": '', "users": '', "video-off": '', "video": '', "voicemail": '', "volume-1": '', "volume-2": '', "volume-x": '', "volume": '', "watch": '', "wifi-off": '', "wifi": '', "wind": '', "x-circle": '', "x-octagon": '', "x-square": '', "x": '', "youtube": '', "zap-off": '', "zap": '', "zoom-in": '', "zoom-out": '' }; + } + ), + /***/ + "./node_modules/classnames/dedupe.js": ( + /*!*******************************************!*\ + !*** ./node_modules/classnames/dedupe.js ***! + \*******************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; + (function() { + "use strict"; + var classNames = function() { + function StorageObject() { + } + StorageObject.prototype = /* @__PURE__ */ Object.create(null); + function _parseArray(resultSet, array) { + var length = array.length; + for (var i = 0; i < length; ++i) { + _parse(resultSet, array[i]); + } + } + var hasOwn = {}.hasOwnProperty; + function _parseNumber(resultSet, num2) { + resultSet[num2] = true; + } + function _parseObject(resultSet, object) { + for (var k in object) { + if (hasOwn.call(object, k)) { + resultSet[k] = !!object[k]; + } + } + } + var SPACE = /\s+/; + function _parseString(resultSet, str) { + var array = str.split(SPACE); + var length = array.length; + for (var i = 0; i < length; ++i) { + resultSet[array[i]] = true; + } + } + function _parse(resultSet, arg) { + if (!arg) + return; + var argType = typeof arg; + if (argType === "string") { + _parseString(resultSet, arg); + } else if (Array.isArray(arg)) { + _parseArray(resultSet, arg); + } else if (argType === "object") { + _parseObject(resultSet, arg); + } else if (argType === "number") { + _parseNumber(resultSet, arg); + } + } + function _classNames() { + var len = arguments.length; + var args = Array(len); + for (var i = 0; i < len; i++) { + args[i] = arguments[i]; + } + var classSet = new StorageObject(); + _parseArray(classSet, args); + var list = []; + for (var k in classSet) { + if (classSet[k]) { + list.push(k); + } + } + return list.join(" "); + } + return _classNames; + }(); + if (typeof module3 !== "undefined" && module3.exports) { + module3.exports = classNames; + } else if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { + return classNames; + }.apply(exports3, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== void 0 && (module3.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else { + } + })(); + } + ), + /***/ + "./node_modules/core-js/es/array/from.js": ( + /*!***********************************************!*\ + !*** ./node_modules/core-js/es/array/from.js ***! + \***********************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + __webpack_require__( + /*! ../../modules/es.string.iterator */ + "./node_modules/core-js/modules/es.string.iterator.js" + ); + __webpack_require__( + /*! ../../modules/es.array.from */ + "./node_modules/core-js/modules/es.array.from.js" + ); + var path2 = __webpack_require__( + /*! ../../internals/path */ + "./node_modules/core-js/internals/path.js" + ); + module3.exports = path2.Array.from; + } + ), + /***/ + "./node_modules/core-js/internals/a-function.js": ( + /*!******************************************************!*\ + !*** ./node_modules/core-js/internals/a-function.js ***! + \******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = function(it) { + if (typeof it != "function") { + throw TypeError(String(it) + " is not a function"); + } + return it; + }; + } + ), + /***/ + "./node_modules/core-js/internals/an-object.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/an-object.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var isObject2 = __webpack_require__( + /*! ../internals/is-object */ + "./node_modules/core-js/internals/is-object.js" + ); + module3.exports = function(it) { + if (!isObject2(it)) { + throw TypeError(String(it) + " is not an object"); + } + return it; + }; + } + ), + /***/ + "./node_modules/core-js/internals/array-from.js": ( + /*!******************************************************!*\ + !*** ./node_modules/core-js/internals/array-from.js ***! + \******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var bind = __webpack_require__( + /*! ../internals/bind-context */ + "./node_modules/core-js/internals/bind-context.js" + ); + var toObject = __webpack_require__( + /*! ../internals/to-object */ + "./node_modules/core-js/internals/to-object.js" + ); + var callWithSafeIterationClosing = __webpack_require__( + /*! ../internals/call-with-safe-iteration-closing */ + "./node_modules/core-js/internals/call-with-safe-iteration-closing.js" + ); + var isArrayIteratorMethod = __webpack_require__( + /*! ../internals/is-array-iterator-method */ + "./node_modules/core-js/internals/is-array-iterator-method.js" + ); + var toLength = __webpack_require__( + /*! ../internals/to-length */ + "./node_modules/core-js/internals/to-length.js" + ); + var createProperty = __webpack_require__( + /*! ../internals/create-property */ + "./node_modules/core-js/internals/create-property.js" + ); + var getIteratorMethod = __webpack_require__( + /*! ../internals/get-iterator-method */ + "./node_modules/core-js/internals/get-iterator-method.js" + ); + module3.exports = function from(arrayLike) { + var O = toObject(arrayLike); + var C = typeof this == "function" ? this : Array; + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : void 0; + var mapping = mapfn !== void 0; + var index2 = 0; + var iteratorMethod = getIteratorMethod(O); + var length, result, step, iterator; + if (mapping) + mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : void 0, 2); + if (iteratorMethod != void 0 && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { + iterator = iteratorMethod.call(O); + result = new C(); + for (; !(step = iterator.next()).done; index2++) { + createProperty( + result, + index2, + mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index2], true) : step.value + ); + } + } else { + length = toLength(O.length); + result = new C(length); + for (; length > index2; index2++) { + createProperty(result, index2, mapping ? mapfn(O[index2], index2) : O[index2]); + } + } + result.length = index2; + return result; + }; + } + ), + /***/ + "./node_modules/core-js/internals/array-includes.js": ( + /*!**********************************************************!*\ + !*** ./node_modules/core-js/internals/array-includes.js ***! + \**********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var toIndexedObject = __webpack_require__( + /*! ../internals/to-indexed-object */ + "./node_modules/core-js/internals/to-indexed-object.js" + ); + var toLength = __webpack_require__( + /*! ../internals/to-length */ + "./node_modules/core-js/internals/to-length.js" + ); + var toAbsoluteIndex = __webpack_require__( + /*! ../internals/to-absolute-index */ + "./node_modules/core-js/internals/to-absolute-index.js" + ); + module3.exports = function(IS_INCLUDES) { + return function($this, el, fromIndex) { + var O = toIndexedObject($this); + var length = toLength(O.length); + var index2 = toAbsoluteIndex(fromIndex, length); + var value; + if (IS_INCLUDES && el != el) + while (length > index2) { + value = O[index2++]; + if (value != value) + return true; + } + else + for (; length > index2; index2++) + if (IS_INCLUDES || index2 in O) { + if (O[index2] === el) + return IS_INCLUDES || index2 || 0; + } + return !IS_INCLUDES && -1; + }; + }; + } + ), + /***/ + "./node_modules/core-js/internals/bind-context.js": ( + /*!********************************************************!*\ + !*** ./node_modules/core-js/internals/bind-context.js ***! + \********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var aFunction = __webpack_require__( + /*! ../internals/a-function */ + "./node_modules/core-js/internals/a-function.js" + ); + module3.exports = function(fn, that, length) { + aFunction(fn); + if (that === void 0) + return fn; + switch (length) { + case 0: + return function() { + return fn.call(that); + }; + case 1: + return function(a) { + return fn.call(that, a); + }; + case 2: + return function(a, b) { + return fn.call(that, a, b); + }; + case 3: + return function(a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function() { + return fn.apply(that, arguments); + }; + }; + } + ), + /***/ + "./node_modules/core-js/internals/call-with-safe-iteration-closing.js": ( + /*!****************************************************************************!*\ + !*** ./node_modules/core-js/internals/call-with-safe-iteration-closing.js ***! + \****************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + module3.exports = function(iterator, fn, value, ENTRIES) { + try { + return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); + } catch (error) { + var returnMethod = iterator["return"]; + if (returnMethod !== void 0) + anObject(returnMethod.call(iterator)); + throw error; + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/check-correctness-of-iteration.js": ( + /*!**************************************************************************!*\ + !*** ./node_modules/core-js/internals/check-correctness-of-iteration.js ***! + \**************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var ITERATOR = wellKnownSymbol("iterator"); + var SAFE_CLOSING = false; + try { + var called = 0; + var iteratorWithReturn = { + next: function() { + return { done: !!called++ }; + }, + "return": function() { + SAFE_CLOSING = true; + } + }; + iteratorWithReturn[ITERATOR] = function() { + return this; + }; + Array.from(iteratorWithReturn, function() { + throw 2; + }); + } catch (error) { + } + module3.exports = function(exec, SKIP_CLOSING) { + if (!SKIP_CLOSING && !SAFE_CLOSING) + return false; + var ITERATION_SUPPORT = false; + try { + var object = {}; + object[ITERATOR] = function() { + return { + next: function() { + return { done: ITERATION_SUPPORT = true }; + } + }; + }; + exec(object); + } catch (error) { + } + return ITERATION_SUPPORT; + }; + } + ), + /***/ + "./node_modules/core-js/internals/classof-raw.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/core-js/internals/classof-raw.js ***! + \*******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + var toString = {}.toString; + module3.exports = function(it) { + return toString.call(it).slice(8, -1); + }; + } + ), + /***/ + "./node_modules/core-js/internals/classof.js": ( + /*!***************************************************!*\ + !*** ./node_modules/core-js/internals/classof.js ***! + \***************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var classofRaw = __webpack_require__( + /*! ../internals/classof-raw */ + "./node_modules/core-js/internals/classof-raw.js" + ); + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var TO_STRING_TAG = wellKnownSymbol("toStringTag"); + var CORRECT_ARGUMENTS = classofRaw(/* @__PURE__ */ function() { + return arguments; + }()) == "Arguments"; + var tryGet = function(it, key2) { + try { + return it[key2]; + } catch (error) { + } + }; + module3.exports = function(it) { + var O, tag2, result; + return it === void 0 ? "Undefined" : it === null ? "Null" : typeof (tag2 = tryGet(O = Object(it), TO_STRING_TAG)) == "string" ? tag2 : CORRECT_ARGUMENTS ? classofRaw(O) : (result = classofRaw(O)) == "Object" && typeof O.callee == "function" ? "Arguments" : result; + }; + } + ), + /***/ + "./node_modules/core-js/internals/copy-constructor-properties.js": ( + /*!***********************************************************************!*\ + !*** ./node_modules/core-js/internals/copy-constructor-properties.js ***! + \***********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var ownKeys = __webpack_require__( + /*! ../internals/own-keys */ + "./node_modules/core-js/internals/own-keys.js" + ); + var getOwnPropertyDescriptorModule = __webpack_require__( + /*! ../internals/object-get-own-property-descriptor */ + "./node_modules/core-js/internals/object-get-own-property-descriptor.js" + ); + var definePropertyModule = __webpack_require__( + /*! ../internals/object-define-property */ + "./node_modules/core-js/internals/object-define-property.js" + ); + module3.exports = function(target, source) { + var keys = ownKeys(source); + var defineProperty = definePropertyModule.f; + var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + for (var i = 0; i < keys.length; i++) { + var key2 = keys[i]; + if (!has(target, key2)) + defineProperty(target, key2, getOwnPropertyDescriptor(source, key2)); + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/correct-prototype-getter.js": ( + /*!********************************************************************!*\ + !*** ./node_modules/core-js/internals/correct-prototype-getter.js ***! + \********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + module3.exports = !fails(function() { + function F() { + } + F.prototype.constructor = null; + return Object.getPrototypeOf(new F()) !== F.prototype; + }); + } + ), + /***/ + "./node_modules/core-js/internals/create-iterator-constructor.js": ( + /*!***********************************************************************!*\ + !*** ./node_modules/core-js/internals/create-iterator-constructor.js ***! + \***********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var IteratorPrototype = __webpack_require__( + /*! ../internals/iterators-core */ + "./node_modules/core-js/internals/iterators-core.js" + ).IteratorPrototype; + var create = __webpack_require__( + /*! ../internals/object-create */ + "./node_modules/core-js/internals/object-create.js" + ); + var createPropertyDescriptor = __webpack_require__( + /*! ../internals/create-property-descriptor */ + "./node_modules/core-js/internals/create-property-descriptor.js" + ); + var setToStringTag = __webpack_require__( + /*! ../internals/set-to-string-tag */ + "./node_modules/core-js/internals/set-to-string-tag.js" + ); + var Iterators = __webpack_require__( + /*! ../internals/iterators */ + "./node_modules/core-js/internals/iterators.js" + ); + var returnThis = function() { + return this; + }; + module3.exports = function(IteratorConstructor, NAME, next) { + var TO_STRING_TAG = NAME + " Iterator"; + IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) }); + setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); + Iterators[TO_STRING_TAG] = returnThis; + return IteratorConstructor; + }; + } + ), + /***/ + "./node_modules/core-js/internals/create-property-descriptor.js": ( + /*!**********************************************************************!*\ + !*** ./node_modules/core-js/internals/create-property-descriptor.js ***! + \**********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = function(bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value + }; + }; + } + ), + /***/ + "./node_modules/core-js/internals/create-property.js": ( + /*!***********************************************************!*\ + !*** ./node_modules/core-js/internals/create-property.js ***! + \***********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var toPrimitive = __webpack_require__( + /*! ../internals/to-primitive */ + "./node_modules/core-js/internals/to-primitive.js" + ); + var definePropertyModule = __webpack_require__( + /*! ../internals/object-define-property */ + "./node_modules/core-js/internals/object-define-property.js" + ); + var createPropertyDescriptor = __webpack_require__( + /*! ../internals/create-property-descriptor */ + "./node_modules/core-js/internals/create-property-descriptor.js" + ); + module3.exports = function(object, key2, value) { + var propertyKey = toPrimitive(key2); + if (propertyKey in object) + definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); + else + object[propertyKey] = value; + }; + } + ), + /***/ + "./node_modules/core-js/internals/define-iterator.js": ( + /*!***********************************************************!*\ + !*** ./node_modules/core-js/internals/define-iterator.js ***! + \***********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var $ = __webpack_require__( + /*! ../internals/export */ + "./node_modules/core-js/internals/export.js" + ); + var createIteratorConstructor = __webpack_require__( + /*! ../internals/create-iterator-constructor */ + "./node_modules/core-js/internals/create-iterator-constructor.js" + ); + var getPrototypeOf = __webpack_require__( + /*! ../internals/object-get-prototype-of */ + "./node_modules/core-js/internals/object-get-prototype-of.js" + ); + var setPrototypeOf = __webpack_require__( + /*! ../internals/object-set-prototype-of */ + "./node_modules/core-js/internals/object-set-prototype-of.js" + ); + var setToStringTag = __webpack_require__( + /*! ../internals/set-to-string-tag */ + "./node_modules/core-js/internals/set-to-string-tag.js" + ); + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + var redefine = __webpack_require__( + /*! ../internals/redefine */ + "./node_modules/core-js/internals/redefine.js" + ); + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var IS_PURE = __webpack_require__( + /*! ../internals/is-pure */ + "./node_modules/core-js/internals/is-pure.js" + ); + var Iterators = __webpack_require__( + /*! ../internals/iterators */ + "./node_modules/core-js/internals/iterators.js" + ); + var IteratorsCore = __webpack_require__( + /*! ../internals/iterators-core */ + "./node_modules/core-js/internals/iterators-core.js" + ); + var IteratorPrototype = IteratorsCore.IteratorPrototype; + var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; + var ITERATOR = wellKnownSymbol("iterator"); + var KEYS = "keys"; + var VALUES = "values"; + var ENTRIES = "entries"; + var returnThis = function() { + return this; + }; + module3.exports = function(Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { + createIteratorConstructor(IteratorConstructor, NAME, next); + var getIterationMethod = function(KIND) { + if (KIND === DEFAULT && defaultIterator) + return defaultIterator; + if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) + return IterablePrototype[KIND]; + switch (KIND) { + case KEYS: + return function keys() { + return new IteratorConstructor(this, KIND); + }; + case VALUES: + return function values() { + return new IteratorConstructor(this, KIND); + }; + case ENTRIES: + return function entries() { + return new IteratorConstructor(this, KIND); + }; + } + return function() { + return new IteratorConstructor(this); + }; + }; + var TO_STRING_TAG = NAME + " Iterator"; + var INCORRECT_VALUES_NAME = false; + var IterablePrototype = Iterable.prototype; + var nativeIterator = IterablePrototype[ITERATOR] || IterablePrototype["@@iterator"] || DEFAULT && IterablePrototype[DEFAULT]; + var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); + var anyNativeIterator = NAME == "Array" ? IterablePrototype.entries || nativeIterator : nativeIterator; + var CurrentIteratorPrototype, methods, KEY; + if (anyNativeIterator) { + CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); + if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { + if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { + if (setPrototypeOf) { + setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); + } else if (typeof CurrentIteratorPrototype[ITERATOR] != "function") { + hide(CurrentIteratorPrototype, ITERATOR, returnThis); + } + } + setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); + if (IS_PURE) + Iterators[TO_STRING_TAG] = returnThis; + } + } + if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { + INCORRECT_VALUES_NAME = true; + defaultIterator = function values() { + return nativeIterator.call(this); + }; + } + if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { + hide(IterablePrototype, ITERATOR, defaultIterator); + } + Iterators[NAME] = defaultIterator; + if (DEFAULT) { + methods = { + values: getIterationMethod(VALUES), + keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), + entries: getIterationMethod(ENTRIES) + }; + if (FORCED) + for (KEY in methods) { + if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { + redefine(IterablePrototype, KEY, methods[KEY]); + } + } + else + $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); + } + return methods; + }; + } + ), + /***/ + "./node_modules/core-js/internals/descriptors.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/core-js/internals/descriptors.js ***! + \*******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + module3.exports = !fails(function() { + return Object.defineProperty({}, "a", { get: function() { + return 7; + } }).a != 7; + }); + } + ), + /***/ + "./node_modules/core-js/internals/document-create-element.js": ( + /*!*******************************************************************!*\ + !*** ./node_modules/core-js/internals/document-create-element.js ***! + \*******************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var isObject2 = __webpack_require__( + /*! ../internals/is-object */ + "./node_modules/core-js/internals/is-object.js" + ); + var document2 = global2.document; + var exist = isObject2(document2) && isObject2(document2.createElement); + module3.exports = function(it) { + return exist ? document2.createElement(it) : {}; + }; + } + ), + /***/ + "./node_modules/core-js/internals/enum-bug-keys.js": ( + /*!*********************************************************!*\ + !*** ./node_modules/core-js/internals/enum-bug-keys.js ***! + \*********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = [ + "constructor", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "toLocaleString", + "toString", + "valueOf" + ]; + } + ), + /***/ + "./node_modules/core-js/internals/export.js": ( + /*!**************************************************!*\ + !*** ./node_modules/core-js/internals/export.js ***! + \**************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var getOwnPropertyDescriptor = __webpack_require__( + /*! ../internals/object-get-own-property-descriptor */ + "./node_modules/core-js/internals/object-get-own-property-descriptor.js" + ).f; + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + var redefine = __webpack_require__( + /*! ../internals/redefine */ + "./node_modules/core-js/internals/redefine.js" + ); + var setGlobal = __webpack_require__( + /*! ../internals/set-global */ + "./node_modules/core-js/internals/set-global.js" + ); + var copyConstructorProperties = __webpack_require__( + /*! ../internals/copy-constructor-properties */ + "./node_modules/core-js/internals/copy-constructor-properties.js" + ); + var isForced = __webpack_require__( + /*! ../internals/is-forced */ + "./node_modules/core-js/internals/is-forced.js" + ); + module3.exports = function(options, source) { + var TARGET = options.target; + var GLOBAL = options.global; + var STATIC = options.stat; + var FORCED, target, key2, targetProperty, sourceProperty, descriptor; + if (GLOBAL) { + target = global2; + } else if (STATIC) { + target = global2[TARGET] || setGlobal(TARGET, {}); + } else { + target = (global2[TARGET] || {}).prototype; + } + if (target) + for (key2 in source) { + sourceProperty = source[key2]; + if (options.noTargetGet) { + descriptor = getOwnPropertyDescriptor(target, key2); + targetProperty = descriptor && descriptor.value; + } else + targetProperty = target[key2]; + FORCED = isForced(GLOBAL ? key2 : TARGET + (STATIC ? "." : "#") + key2, options.forced); + if (!FORCED && targetProperty !== void 0) { + if (typeof sourceProperty === typeof targetProperty) + continue; + copyConstructorProperties(sourceProperty, targetProperty); + } + if (options.sham || targetProperty && targetProperty.sham) { + hide(sourceProperty, "sham", true); + } + redefine(target, key2, sourceProperty, options); + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/fails.js": ( + /*!*************************************************!*\ + !*** ./node_modules/core-js/internals/fails.js ***! + \*************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = function(exec) { + try { + return !!exec(); + } catch (error) { + return true; + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/function-to-string.js": ( + /*!**************************************************************!*\ + !*** ./node_modules/core-js/internals/function-to-string.js ***! + \**************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var shared = __webpack_require__( + /*! ../internals/shared */ + "./node_modules/core-js/internals/shared.js" + ); + module3.exports = shared("native-function-to-string", Function.toString); + } + ), + /***/ + "./node_modules/core-js/internals/get-iterator-method.js": ( + /*!***************************************************************!*\ + !*** ./node_modules/core-js/internals/get-iterator-method.js ***! + \***************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var classof = __webpack_require__( + /*! ../internals/classof */ + "./node_modules/core-js/internals/classof.js" + ); + var Iterators = __webpack_require__( + /*! ../internals/iterators */ + "./node_modules/core-js/internals/iterators.js" + ); + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var ITERATOR = wellKnownSymbol("iterator"); + module3.exports = function(it) { + if (it != void 0) + return it[ITERATOR] || it["@@iterator"] || Iterators[classof(it)]; + }; + } + ), + /***/ + "./node_modules/core-js/internals/global.js": ( + /*!**************************************************!*\ + !*** ./node_modules/core-js/internals/global.js ***! + \**************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + (function(global2) { + var O = "object"; + var check = function(it) { + return it && it.Math == Math && it; + }; + module3.exports = // eslint-disable-next-line no-undef + check(typeof globalThis == O && globalThis) || check(typeof window == O && window) || check(typeof self == O && self) || check(typeof global2 == O && global2) || // eslint-disable-next-line no-new-func + Function("return this")(); + }).call(this, __webpack_require__( + /*! ./../../webpack/buildin/global.js */ + "./node_modules/webpack/buildin/global.js" + )); + } + ), + /***/ + "./node_modules/core-js/internals/has.js": ( + /*!***********************************************!*\ + !*** ./node_modules/core-js/internals/has.js ***! + \***********************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + var hasOwnProperty = {}.hasOwnProperty; + module3.exports = function(it, key2) { + return hasOwnProperty.call(it, key2); + }; + } + ), + /***/ + "./node_modules/core-js/internals/hidden-keys.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/core-js/internals/hidden-keys.js ***! + \*******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = {}; + } + ), + /***/ + "./node_modules/core-js/internals/hide.js": ( + /*!************************************************!*\ + !*** ./node_modules/core-js/internals/hide.js ***! + \************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var DESCRIPTORS = __webpack_require__( + /*! ../internals/descriptors */ + "./node_modules/core-js/internals/descriptors.js" + ); + var definePropertyModule = __webpack_require__( + /*! ../internals/object-define-property */ + "./node_modules/core-js/internals/object-define-property.js" + ); + var createPropertyDescriptor = __webpack_require__( + /*! ../internals/create-property-descriptor */ + "./node_modules/core-js/internals/create-property-descriptor.js" + ); + module3.exports = DESCRIPTORS ? function(object, key2, value) { + return definePropertyModule.f(object, key2, createPropertyDescriptor(1, value)); + } : function(object, key2, value) { + object[key2] = value; + return object; + }; + } + ), + /***/ + "./node_modules/core-js/internals/html.js": ( + /*!************************************************!*\ + !*** ./node_modules/core-js/internals/html.js ***! + \************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var document2 = global2.document; + module3.exports = document2 && document2.documentElement; + } + ), + /***/ + "./node_modules/core-js/internals/ie8-dom-define.js": ( + /*!**********************************************************!*\ + !*** ./node_modules/core-js/internals/ie8-dom-define.js ***! + \**********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var DESCRIPTORS = __webpack_require__( + /*! ../internals/descriptors */ + "./node_modules/core-js/internals/descriptors.js" + ); + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + var createElement = __webpack_require__( + /*! ../internals/document-create-element */ + "./node_modules/core-js/internals/document-create-element.js" + ); + module3.exports = !DESCRIPTORS && !fails(function() { + return Object.defineProperty(createElement("div"), "a", { + get: function() { + return 7; + } + }).a != 7; + }); + } + ), + /***/ + "./node_modules/core-js/internals/indexed-object.js": ( + /*!**********************************************************!*\ + !*** ./node_modules/core-js/internals/indexed-object.js ***! + \**********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + var classof = __webpack_require__( + /*! ../internals/classof-raw */ + "./node_modules/core-js/internals/classof-raw.js" + ); + var split = "".split; + module3.exports = fails(function() { + return !Object("z").propertyIsEnumerable(0); + }) ? function(it) { + return classof(it) == "String" ? split.call(it, "") : Object(it); + } : Object; + } + ), + /***/ + "./node_modules/core-js/internals/internal-state.js": ( + /*!**********************************************************!*\ + !*** ./node_modules/core-js/internals/internal-state.js ***! + \**********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var NATIVE_WEAK_MAP = __webpack_require__( + /*! ../internals/native-weak-map */ + "./node_modules/core-js/internals/native-weak-map.js" + ); + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var isObject2 = __webpack_require__( + /*! ../internals/is-object */ + "./node_modules/core-js/internals/is-object.js" + ); + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + var objectHas = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var sharedKey = __webpack_require__( + /*! ../internals/shared-key */ + "./node_modules/core-js/internals/shared-key.js" + ); + var hiddenKeys = __webpack_require__( + /*! ../internals/hidden-keys */ + "./node_modules/core-js/internals/hidden-keys.js" + ); + var WeakMap2 = global2.WeakMap; + var set, get, has; + var enforce = function(it) { + return has(it) ? get(it) : set(it, {}); + }; + var getterFor = function(TYPE) { + return function(it) { + var state; + if (!isObject2(it) || (state = get(it)).type !== TYPE) { + throw TypeError("Incompatible receiver, " + TYPE + " required"); + } + return state; + }; + }; + if (NATIVE_WEAK_MAP) { + var store = new WeakMap2(); + var wmget = store.get; + var wmhas = store.has; + var wmset = store.set; + set = function(it, metadata) { + wmset.call(store, it, metadata); + return metadata; + }; + get = function(it) { + return wmget.call(store, it) || {}; + }; + has = function(it) { + return wmhas.call(store, it); + }; + } else { + var STATE = sharedKey("state"); + hiddenKeys[STATE] = true; + set = function(it, metadata) { + hide(it, STATE, metadata); + return metadata; + }; + get = function(it) { + return objectHas(it, STATE) ? it[STATE] : {}; + }; + has = function(it) { + return objectHas(it, STATE); + }; + } + module3.exports = { + set, + get, + has, + enforce, + getterFor + }; + } + ), + /***/ + "./node_modules/core-js/internals/is-array-iterator-method.js": ( + /*!********************************************************************!*\ + !*** ./node_modules/core-js/internals/is-array-iterator-method.js ***! + \********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var Iterators = __webpack_require__( + /*! ../internals/iterators */ + "./node_modules/core-js/internals/iterators.js" + ); + var ITERATOR = wellKnownSymbol("iterator"); + var ArrayPrototype = Array.prototype; + module3.exports = function(it) { + return it !== void 0 && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); + }; + } + ), + /***/ + "./node_modules/core-js/internals/is-forced.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/is-forced.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + var replacement = /#|\.prototype\./; + var isForced = function(feature, detection) { + var value = data[normalize2(feature)]; + return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == "function" ? fails(detection) : !!detection; + }; + var normalize2 = isForced.normalize = function(string) { + return String(string).replace(replacement, ".").toLowerCase(); + }; + var data = isForced.data = {}; + var NATIVE = isForced.NATIVE = "N"; + var POLYFILL = isForced.POLYFILL = "P"; + module3.exports = isForced; + } + ), + /***/ + "./node_modules/core-js/internals/is-object.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/is-object.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = function(it) { + return typeof it === "object" ? it !== null : typeof it === "function"; + }; + } + ), + /***/ + "./node_modules/core-js/internals/is-pure.js": ( + /*!***************************************************!*\ + !*** ./node_modules/core-js/internals/is-pure.js ***! + \***************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = false; + } + ), + /***/ + "./node_modules/core-js/internals/iterators-core.js": ( + /*!**********************************************************!*\ + !*** ./node_modules/core-js/internals/iterators-core.js ***! + \**********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var getPrototypeOf = __webpack_require__( + /*! ../internals/object-get-prototype-of */ + "./node_modules/core-js/internals/object-get-prototype-of.js" + ); + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var IS_PURE = __webpack_require__( + /*! ../internals/is-pure */ + "./node_modules/core-js/internals/is-pure.js" + ); + var ITERATOR = wellKnownSymbol("iterator"); + var BUGGY_SAFARI_ITERATORS = false; + var returnThis = function() { + return this; + }; + var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; + if ([].keys) { + arrayIterator = [].keys(); + if (!("next" in arrayIterator)) + BUGGY_SAFARI_ITERATORS = true; + else { + PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); + if (PrototypeOfArrayIteratorPrototype !== Object.prototype) + IteratorPrototype = PrototypeOfArrayIteratorPrototype; + } + } + if (IteratorPrototype == void 0) + IteratorPrototype = {}; + if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) + hide(IteratorPrototype, ITERATOR, returnThis); + module3.exports = { + IteratorPrototype, + BUGGY_SAFARI_ITERATORS + }; + } + ), + /***/ + "./node_modules/core-js/internals/iterators.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/iterators.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = {}; + } + ), + /***/ + "./node_modules/core-js/internals/native-symbol.js": ( + /*!*********************************************************!*\ + !*** ./node_modules/core-js/internals/native-symbol.js ***! + \*********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var fails = __webpack_require__( + /*! ../internals/fails */ + "./node_modules/core-js/internals/fails.js" + ); + module3.exports = !!Object.getOwnPropertySymbols && !fails(function() { + return !String(Symbol()); + }); + } + ), + /***/ + "./node_modules/core-js/internals/native-weak-map.js": ( + /*!***********************************************************!*\ + !*** ./node_modules/core-js/internals/native-weak-map.js ***! + \***********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var nativeFunctionToString = __webpack_require__( + /*! ../internals/function-to-string */ + "./node_modules/core-js/internals/function-to-string.js" + ); + var WeakMap2 = global2.WeakMap; + module3.exports = typeof WeakMap2 === "function" && /native code/.test(nativeFunctionToString.call(WeakMap2)); + } + ), + /***/ + "./node_modules/core-js/internals/object-create.js": ( + /*!*********************************************************!*\ + !*** ./node_modules/core-js/internals/object-create.js ***! + \*********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + var defineProperties = __webpack_require__( + /*! ../internals/object-define-properties */ + "./node_modules/core-js/internals/object-define-properties.js" + ); + var enumBugKeys = __webpack_require__( + /*! ../internals/enum-bug-keys */ + "./node_modules/core-js/internals/enum-bug-keys.js" + ); + var hiddenKeys = __webpack_require__( + /*! ../internals/hidden-keys */ + "./node_modules/core-js/internals/hidden-keys.js" + ); + var html2 = __webpack_require__( + /*! ../internals/html */ + "./node_modules/core-js/internals/html.js" + ); + var documentCreateElement = __webpack_require__( + /*! ../internals/document-create-element */ + "./node_modules/core-js/internals/document-create-element.js" + ); + var sharedKey = __webpack_require__( + /*! ../internals/shared-key */ + "./node_modules/core-js/internals/shared-key.js" + ); + var IE_PROTO = sharedKey("IE_PROTO"); + var PROTOTYPE = "prototype"; + var Empty = function() { + }; + var createDict = function() { + var iframe = documentCreateElement("iframe"); + var length = enumBugKeys.length; + var lt = "<"; + var script = "script"; + var gt = ">"; + var js = "java" + script + ":"; + var iframeDocument; + iframe.style.display = "none"; + html2.appendChild(iframe); + iframe.src = String(js); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + script + gt + "document.F=Object" + lt + "/" + script + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (length--) + delete createDict[PROTOTYPE][enumBugKeys[length]]; + return createDict(); + }; + module3.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + result[IE_PROTO] = O; + } else + result = createDict(); + return Properties === void 0 ? result : defineProperties(result, Properties); + }; + hiddenKeys[IE_PROTO] = true; + } + ), + /***/ + "./node_modules/core-js/internals/object-define-properties.js": ( + /*!********************************************************************!*\ + !*** ./node_modules/core-js/internals/object-define-properties.js ***! + \********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var DESCRIPTORS = __webpack_require__( + /*! ../internals/descriptors */ + "./node_modules/core-js/internals/descriptors.js" + ); + var definePropertyModule = __webpack_require__( + /*! ../internals/object-define-property */ + "./node_modules/core-js/internals/object-define-property.js" + ); + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + var objectKeys = __webpack_require__( + /*! ../internals/object-keys */ + "./node_modules/core-js/internals/object-keys.js" + ); + module3.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = objectKeys(Properties); + var length = keys.length; + var i = 0; + var key2; + while (length > i) + definePropertyModule.f(O, key2 = keys[i++], Properties[key2]); + return O; + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-define-property.js": ( + /*!******************************************************************!*\ + !*** ./node_modules/core-js/internals/object-define-property.js ***! + \******************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var DESCRIPTORS = __webpack_require__( + /*! ../internals/descriptors */ + "./node_modules/core-js/internals/descriptors.js" + ); + var IE8_DOM_DEFINE = __webpack_require__( + /*! ../internals/ie8-dom-define */ + "./node_modules/core-js/internals/ie8-dom-define.js" + ); + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + var toPrimitive = __webpack_require__( + /*! ../internals/to-primitive */ + "./node_modules/core-js/internals/to-primitive.js" + ); + var nativeDefineProperty = Object.defineProperty; + exports3.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) + try { + return nativeDefineProperty(O, P, Attributes); + } catch (error) { + } + if ("get" in Attributes || "set" in Attributes) + throw TypeError("Accessors not supported"); + if ("value" in Attributes) + O[P] = Attributes.value; + return O; + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-get-own-property-descriptor.js": ( + /*!******************************************************************************!*\ + !*** ./node_modules/core-js/internals/object-get-own-property-descriptor.js ***! + \******************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var DESCRIPTORS = __webpack_require__( + /*! ../internals/descriptors */ + "./node_modules/core-js/internals/descriptors.js" + ); + var propertyIsEnumerableModule = __webpack_require__( + /*! ../internals/object-property-is-enumerable */ + "./node_modules/core-js/internals/object-property-is-enumerable.js" + ); + var createPropertyDescriptor = __webpack_require__( + /*! ../internals/create-property-descriptor */ + "./node_modules/core-js/internals/create-property-descriptor.js" + ); + var toIndexedObject = __webpack_require__( + /*! ../internals/to-indexed-object */ + "./node_modules/core-js/internals/to-indexed-object.js" + ); + var toPrimitive = __webpack_require__( + /*! ../internals/to-primitive */ + "./node_modules/core-js/internals/to-primitive.js" + ); + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var IE8_DOM_DEFINE = __webpack_require__( + /*! ../internals/ie8-dom-define */ + "./node_modules/core-js/internals/ie8-dom-define.js" + ); + var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + exports3.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { + O = toIndexedObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) + try { + return nativeGetOwnPropertyDescriptor(O, P); + } catch (error) { + } + if (has(O, P)) + return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-get-own-property-names.js": ( + /*!*************************************************************************!*\ + !*** ./node_modules/core-js/internals/object-get-own-property-names.js ***! + \*************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var internalObjectKeys = __webpack_require__( + /*! ../internals/object-keys-internal */ + "./node_modules/core-js/internals/object-keys-internal.js" + ); + var enumBugKeys = __webpack_require__( + /*! ../internals/enum-bug-keys */ + "./node_modules/core-js/internals/enum-bug-keys.js" + ); + var hiddenKeys = enumBugKeys.concat("length", "prototype"); + exports3.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return internalObjectKeys(O, hiddenKeys); + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-get-own-property-symbols.js": ( + /*!***************************************************************************!*\ + !*** ./node_modules/core-js/internals/object-get-own-property-symbols.js ***! + \***************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + exports3.f = Object.getOwnPropertySymbols; + } + ), + /***/ + "./node_modules/core-js/internals/object-get-prototype-of.js": ( + /*!*******************************************************************!*\ + !*** ./node_modules/core-js/internals/object-get-prototype-of.js ***! + \*******************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var toObject = __webpack_require__( + /*! ../internals/to-object */ + "./node_modules/core-js/internals/to-object.js" + ); + var sharedKey = __webpack_require__( + /*! ../internals/shared-key */ + "./node_modules/core-js/internals/shared-key.js" + ); + var CORRECT_PROTOTYPE_GETTER = __webpack_require__( + /*! ../internals/correct-prototype-getter */ + "./node_modules/core-js/internals/correct-prototype-getter.js" + ); + var IE_PROTO = sharedKey("IE_PROTO"); + var ObjectPrototype = Object.prototype; + module3.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function(O) { + O = toObject(O); + if (has(O, IE_PROTO)) + return O[IE_PROTO]; + if (typeof O.constructor == "function" && O instanceof O.constructor) { + return O.constructor.prototype; + } + return O instanceof Object ? ObjectPrototype : null; + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-keys-internal.js": ( + /*!****************************************************************!*\ + !*** ./node_modules/core-js/internals/object-keys-internal.js ***! + \****************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var toIndexedObject = __webpack_require__( + /*! ../internals/to-indexed-object */ + "./node_modules/core-js/internals/to-indexed-object.js" + ); + var arrayIncludes = __webpack_require__( + /*! ../internals/array-includes */ + "./node_modules/core-js/internals/array-includes.js" + ); + var hiddenKeys = __webpack_require__( + /*! ../internals/hidden-keys */ + "./node_modules/core-js/internals/hidden-keys.js" + ); + var arrayIndexOf = arrayIncludes(false); + module3.exports = function(object, names) { + var O = toIndexedObject(object); + var i = 0; + var result = []; + var key2; + for (key2 in O) + !has(hiddenKeys, key2) && has(O, key2) && result.push(key2); + while (names.length > i) + if (has(O, key2 = names[i++])) { + ~arrayIndexOf(result, key2) || result.push(key2); + } + return result; + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-keys.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/core-js/internals/object-keys.js ***! + \*******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var internalObjectKeys = __webpack_require__( + /*! ../internals/object-keys-internal */ + "./node_modules/core-js/internals/object-keys-internal.js" + ); + var enumBugKeys = __webpack_require__( + /*! ../internals/enum-bug-keys */ + "./node_modules/core-js/internals/enum-bug-keys.js" + ); + module3.exports = Object.keys || function keys(O) { + return internalObjectKeys(O, enumBugKeys); + }; + } + ), + /***/ + "./node_modules/core-js/internals/object-property-is-enumerable.js": ( + /*!*************************************************************************!*\ + !*** ./node_modules/core-js/internals/object-property-is-enumerable.js ***! + \*************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var nativePropertyIsEnumerable = {}.propertyIsEnumerable; + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); + exports3.f = NASHORN_BUG ? function propertyIsEnumerable(V) { + var descriptor = getOwnPropertyDescriptor(this, V); + return !!descriptor && descriptor.enumerable; + } : nativePropertyIsEnumerable; + } + ), + /***/ + "./node_modules/core-js/internals/object-set-prototype-of.js": ( + /*!*******************************************************************!*\ + !*** ./node_modules/core-js/internals/object-set-prototype-of.js ***! + \*******************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var validateSetPrototypeOfArguments = __webpack_require__( + /*! ../internals/validate-set-prototype-of-arguments */ + "./node_modules/core-js/internals/validate-set-prototype-of-arguments.js" + ); + module3.exports = Object.setPrototypeOf || ("__proto__" in {} ? function() { + var correctSetter = false; + var test = {}; + var setter; + try { + setter = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__").set; + setter.call(test, []); + correctSetter = test instanceof Array; + } catch (error) { + } + return function setPrototypeOf(O, proto) { + validateSetPrototypeOfArguments(O, proto); + if (correctSetter) + setter.call(O, proto); + else + O.__proto__ = proto; + return O; + }; + }() : void 0); + } + ), + /***/ + "./node_modules/core-js/internals/own-keys.js": ( + /*!****************************************************!*\ + !*** ./node_modules/core-js/internals/own-keys.js ***! + \****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var getOwnPropertyNamesModule = __webpack_require__( + /*! ../internals/object-get-own-property-names */ + "./node_modules/core-js/internals/object-get-own-property-names.js" + ); + var getOwnPropertySymbolsModule = __webpack_require__( + /*! ../internals/object-get-own-property-symbols */ + "./node_modules/core-js/internals/object-get-own-property-symbols.js" + ); + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + var Reflect2 = global2.Reflect; + module3.exports = Reflect2 && Reflect2.ownKeys || function ownKeys(it) { + var keys = getOwnPropertyNamesModule.f(anObject(it)); + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; + }; + } + ), + /***/ + "./node_modules/core-js/internals/path.js": ( + /*!************************************************!*\ + !*** ./node_modules/core-js/internals/path.js ***! + \************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + module3.exports = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + } + ), + /***/ + "./node_modules/core-js/internals/redefine.js": ( + /*!****************************************************!*\ + !*** ./node_modules/core-js/internals/redefine.js ***! + \****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var shared = __webpack_require__( + /*! ../internals/shared */ + "./node_modules/core-js/internals/shared.js" + ); + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var setGlobal = __webpack_require__( + /*! ../internals/set-global */ + "./node_modules/core-js/internals/set-global.js" + ); + var nativeFunctionToString = __webpack_require__( + /*! ../internals/function-to-string */ + "./node_modules/core-js/internals/function-to-string.js" + ); + var InternalStateModule = __webpack_require__( + /*! ../internals/internal-state */ + "./node_modules/core-js/internals/internal-state.js" + ); + var getInternalState = InternalStateModule.get; + var enforceInternalState = InternalStateModule.enforce; + var TEMPLATE = String(nativeFunctionToString).split("toString"); + shared("inspectSource", function(it) { + return nativeFunctionToString.call(it); + }); + (module3.exports = function(O, key2, value, options) { + var unsafe = options ? !!options.unsafe : false; + var simple2 = options ? !!options.enumerable : false; + var noTargetGet = options ? !!options.noTargetGet : false; + if (typeof value == "function") { + if (typeof key2 == "string" && !has(value, "name")) + hide(value, "name", key2); + enforceInternalState(value).source = TEMPLATE.join(typeof key2 == "string" ? key2 : ""); + } + if (O === global2) { + if (simple2) + O[key2] = value; + else + setGlobal(key2, value); + return; + } else if (!unsafe) { + delete O[key2]; + } else if (!noTargetGet && O[key2]) { + simple2 = true; + } + if (simple2) + O[key2] = value; + else + hide(O, key2, value); + })(Function.prototype, "toString", function toString() { + return typeof this == "function" && getInternalState(this).source || nativeFunctionToString.call(this); + }); + } + ), + /***/ + "./node_modules/core-js/internals/require-object-coercible.js": ( + /*!********************************************************************!*\ + !*** ./node_modules/core-js/internals/require-object-coercible.js ***! + \********************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + module3.exports = function(it) { + if (it == void 0) + throw TypeError("Can't call method on " + it); + return it; + }; + } + ), + /***/ + "./node_modules/core-js/internals/set-global.js": ( + /*!******************************************************!*\ + !*** ./node_modules/core-js/internals/set-global.js ***! + \******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var hide = __webpack_require__( + /*! ../internals/hide */ + "./node_modules/core-js/internals/hide.js" + ); + module3.exports = function(key2, value) { + try { + hide(global2, key2, value); + } catch (error) { + global2[key2] = value; + } + return value; + }; + } + ), + /***/ + "./node_modules/core-js/internals/set-to-string-tag.js": ( + /*!*************************************************************!*\ + !*** ./node_modules/core-js/internals/set-to-string-tag.js ***! + \*************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var defineProperty = __webpack_require__( + /*! ../internals/object-define-property */ + "./node_modules/core-js/internals/object-define-property.js" + ).f; + var has = __webpack_require__( + /*! ../internals/has */ + "./node_modules/core-js/internals/has.js" + ); + var wellKnownSymbol = __webpack_require__( + /*! ../internals/well-known-symbol */ + "./node_modules/core-js/internals/well-known-symbol.js" + ); + var TO_STRING_TAG = wellKnownSymbol("toStringTag"); + module3.exports = function(it, TAG, STATIC) { + if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) { + defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG }); + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/shared-key.js": ( + /*!******************************************************!*\ + !*** ./node_modules/core-js/internals/shared-key.js ***! + \******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var shared = __webpack_require__( + /*! ../internals/shared */ + "./node_modules/core-js/internals/shared.js" + ); + var uid = __webpack_require__( + /*! ../internals/uid */ + "./node_modules/core-js/internals/uid.js" + ); + var keys = shared("keys"); + module3.exports = function(key2) { + return keys[key2] || (keys[key2] = uid(key2)); + }; + } + ), + /***/ + "./node_modules/core-js/internals/shared.js": ( + /*!**************************************************!*\ + !*** ./node_modules/core-js/internals/shared.js ***! + \**************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var setGlobal = __webpack_require__( + /*! ../internals/set-global */ + "./node_modules/core-js/internals/set-global.js" + ); + var IS_PURE = __webpack_require__( + /*! ../internals/is-pure */ + "./node_modules/core-js/internals/is-pure.js" + ); + var SHARED = "__core-js_shared__"; + var store = global2[SHARED] || setGlobal(SHARED, {}); + (module3.exports = function(key2, value) { + return store[key2] || (store[key2] = value !== void 0 ? value : {}); + })("versions", []).push({ + version: "3.1.3", + mode: IS_PURE ? "pure" : "global", + copyright: "\xA9 2019 Denis Pushkarev (zloirock.ru)" + }); + } + ), + /***/ + "./node_modules/core-js/internals/string-at.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/string-at.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var toInteger = __webpack_require__( + /*! ../internals/to-integer */ + "./node_modules/core-js/internals/to-integer.js" + ); + var requireObjectCoercible = __webpack_require__( + /*! ../internals/require-object-coercible */ + "./node_modules/core-js/internals/require-object-coercible.js" + ); + module3.exports = function(that, pos, CONVERT_TO_STRING) { + var S = String(requireObjectCoercible(that)); + var position = toInteger(pos); + var size = S.length; + var first2, second; + if (position < 0 || position >= size) + return CONVERT_TO_STRING ? "" : void 0; + first2 = S.charCodeAt(position); + return first2 < 55296 || first2 > 56319 || position + 1 === size || (second = S.charCodeAt(position + 1)) < 56320 || second > 57343 ? CONVERT_TO_STRING ? S.charAt(position) : first2 : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first2 - 55296 << 10) + (second - 56320) + 65536; + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-absolute-index.js": ( + /*!*************************************************************!*\ + !*** ./node_modules/core-js/internals/to-absolute-index.js ***! + \*************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var toInteger = __webpack_require__( + /*! ../internals/to-integer */ + "./node_modules/core-js/internals/to-integer.js" + ); + var max = Math.max; + var min = Math.min; + module3.exports = function(index2, length) { + var integer = toInteger(index2); + return integer < 0 ? max(integer + length, 0) : min(integer, length); + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-indexed-object.js": ( + /*!*************************************************************!*\ + !*** ./node_modules/core-js/internals/to-indexed-object.js ***! + \*************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var IndexedObject = __webpack_require__( + /*! ../internals/indexed-object */ + "./node_modules/core-js/internals/indexed-object.js" + ); + var requireObjectCoercible = __webpack_require__( + /*! ../internals/require-object-coercible */ + "./node_modules/core-js/internals/require-object-coercible.js" + ); + module3.exports = function(it) { + return IndexedObject(requireObjectCoercible(it)); + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-integer.js": ( + /*!******************************************************!*\ + !*** ./node_modules/core-js/internals/to-integer.js ***! + \******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + var ceil = Math.ceil; + var floor = Math.floor; + module3.exports = function(argument) { + return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-length.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/to-length.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var toInteger = __webpack_require__( + /*! ../internals/to-integer */ + "./node_modules/core-js/internals/to-integer.js" + ); + var min = Math.min; + module3.exports = function(argument) { + return argument > 0 ? min(toInteger(argument), 9007199254740991) : 0; + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-object.js": ( + /*!*****************************************************!*\ + !*** ./node_modules/core-js/internals/to-object.js ***! + \*****************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var requireObjectCoercible = __webpack_require__( + /*! ../internals/require-object-coercible */ + "./node_modules/core-js/internals/require-object-coercible.js" + ); + module3.exports = function(argument) { + return Object(requireObjectCoercible(argument)); + }; + } + ), + /***/ + "./node_modules/core-js/internals/to-primitive.js": ( + /*!********************************************************!*\ + !*** ./node_modules/core-js/internals/to-primitive.js ***! + \********************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var isObject2 = __webpack_require__( + /*! ../internals/is-object */ + "./node_modules/core-js/internals/is-object.js" + ); + module3.exports = function(it, S) { + if (!isObject2(it)) + return it; + var fn, val; + if (S && typeof (fn = it.toString) == "function" && !isObject2(val = fn.call(it))) + return val; + if (typeof (fn = it.valueOf) == "function" && !isObject2(val = fn.call(it))) + return val; + if (!S && typeof (fn = it.toString) == "function" && !isObject2(val = fn.call(it))) + return val; + throw TypeError("Can't convert object to primitive value"); + }; + } + ), + /***/ + "./node_modules/core-js/internals/uid.js": ( + /*!***********************************************!*\ + !*** ./node_modules/core-js/internals/uid.js ***! + \***********************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + var id = 0; + var postfix = Math.random(); + module3.exports = function(key2) { + return "Symbol(".concat(key2 === void 0 ? "" : key2, ")_", (++id + postfix).toString(36)); + }; + } + ), + /***/ + "./node_modules/core-js/internals/validate-set-prototype-of-arguments.js": ( + /*!*******************************************************************************!*\ + !*** ./node_modules/core-js/internals/validate-set-prototype-of-arguments.js ***! + \*******************************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var isObject2 = __webpack_require__( + /*! ../internals/is-object */ + "./node_modules/core-js/internals/is-object.js" + ); + var anObject = __webpack_require__( + /*! ../internals/an-object */ + "./node_modules/core-js/internals/an-object.js" + ); + module3.exports = function(O, proto) { + anObject(O); + if (!isObject2(proto) && proto !== null) { + throw TypeError("Can't set " + String(proto) + " as a prototype"); + } + }; + } + ), + /***/ + "./node_modules/core-js/internals/well-known-symbol.js": ( + /*!*************************************************************!*\ + !*** ./node_modules/core-js/internals/well-known-symbol.js ***! + \*************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var global2 = __webpack_require__( + /*! ../internals/global */ + "./node_modules/core-js/internals/global.js" + ); + var shared = __webpack_require__( + /*! ../internals/shared */ + "./node_modules/core-js/internals/shared.js" + ); + var uid = __webpack_require__( + /*! ../internals/uid */ + "./node_modules/core-js/internals/uid.js" + ); + var NATIVE_SYMBOL = __webpack_require__( + /*! ../internals/native-symbol */ + "./node_modules/core-js/internals/native-symbol.js" + ); + var Symbol2 = global2.Symbol; + var store = shared("wks"); + module3.exports = function(name) { + return store[name] || (store[name] = NATIVE_SYMBOL && Symbol2[name] || (NATIVE_SYMBOL ? Symbol2 : uid)("Symbol." + name)); + }; + } + ), + /***/ + "./node_modules/core-js/modules/es.array.from.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/core-js/modules/es.array.from.js ***! + \*******************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + var $ = __webpack_require__( + /*! ../internals/export */ + "./node_modules/core-js/internals/export.js" + ); + var from = __webpack_require__( + /*! ../internals/array-from */ + "./node_modules/core-js/internals/array-from.js" + ); + var checkCorrectnessOfIteration = __webpack_require__( + /*! ../internals/check-correctness-of-iteration */ + "./node_modules/core-js/internals/check-correctness-of-iteration.js" + ); + var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function(iterable) { + Array.from(iterable); + }); + $({ target: "Array", stat: true, forced: INCORRECT_ITERATION }, { + from + }); + } + ), + /***/ + "./node_modules/core-js/modules/es.string.iterator.js": ( + /*!************************************************************!*\ + !*** ./node_modules/core-js/modules/es.string.iterator.js ***! + \************************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var codePointAt = __webpack_require__( + /*! ../internals/string-at */ + "./node_modules/core-js/internals/string-at.js" + ); + var InternalStateModule = __webpack_require__( + /*! ../internals/internal-state */ + "./node_modules/core-js/internals/internal-state.js" + ); + var defineIterator = __webpack_require__( + /*! ../internals/define-iterator */ + "./node_modules/core-js/internals/define-iterator.js" + ); + var STRING_ITERATOR = "String Iterator"; + var setInternalState = InternalStateModule.set; + var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + defineIterator(String, "String", function(iterated) { + setInternalState(this, { + type: STRING_ITERATOR, + string: String(iterated), + index: 0 + }); + }, function next() { + var state = getInternalState(this); + var string = state.string; + var index2 = state.index; + var point; + if (index2 >= string.length) + return { value: void 0, done: true }; + point = codePointAt(string, index2, true); + state.index += point.length; + return { value: point, done: false }; + }); + } + ), + /***/ + "./node_modules/webpack/buildin/global.js": ( + /*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ + /*! no static exports found */ + /***/ + function(module3, exports3) { + var g; + g = /* @__PURE__ */ function() { + return this; + }(); + try { + g = g || Function("return this")() || (1, eval)("this"); + } catch (e) { + if (typeof window === "object") + g = window; + } + module3.exports = g; + } + ), + /***/ + "./src/default-attrs.json": ( + /*!********************************!*\ + !*** ./src/default-attrs.json ***! + \********************************/ + /*! exports provided: xmlns, width, height, viewBox, fill, stroke, stroke-width, stroke-linecap, stroke-linejoin, default */ + /***/ + function(module3) { + module3.exports = { "xmlns": "http://www.w3.org/2000/svg", "width": 24, "height": 24, "viewBox": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round" }; + } + ), + /***/ + "./src/icon.js": ( + /*!*********************!*\ + !*** ./src/icon.js ***! + \*********************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + Object.defineProperty(exports3, "__esModule", { + value: true + }); + var _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key2 in source) { + if (Object.prototype.hasOwnProperty.call(source, key2)) { + target[key2] = source[key2]; + } + } + } + return target; + }; + var _createClass = /* @__PURE__ */ function() { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function(Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + var _dedupe = __webpack_require__( + /*! classnames/dedupe */ + "./node_modules/classnames/dedupe.js" + ); + var _dedupe2 = _interopRequireDefault(_dedupe); + var _defaultAttrs = __webpack_require__( + /*! ./default-attrs.json */ + "./src/default-attrs.json" + ); + var _defaultAttrs2 = _interopRequireDefault(_defaultAttrs); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance10, Constructor) { + if (!(instance10 instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + var Icon = function() { + function Icon2(name, contents) { + var tags = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : []; + _classCallCheck(this, Icon2); + this.name = name; + this.contents = contents; + this.tags = tags; + this.attrs = _extends({}, _defaultAttrs2.default, { class: "feather feather-" + name }); + } + _createClass(Icon2, [{ + key: "toSvg", + value: function toSvg() { + var attrs = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + var combinedAttrs = _extends({}, this.attrs, attrs, { class: (0, _dedupe2.default)(this.attrs.class, attrs.class) }); + return "" + this.contents + ""; + } + /** + * Return string representation of an `Icon`. + * + * Added for backward compatibility. If old code expects `feather.icons.` + * to be a string, `toString()` will get implicitly called. + * + * @returns {string} + */ + }, { + key: "toString", + value: function toString() { + return this.contents; + } + }]); + return Icon2; + }(); + function attrsToString(attrs) { + return Object.keys(attrs).map(function(key2) { + return key2 + '="' + attrs[key2] + '"'; + }).join(" "); + } + exports3.default = Icon; + } + ), + /***/ + "./src/icons.js": ( + /*!**********************!*\ + !*** ./src/icons.js ***! + \**********************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + Object.defineProperty(exports3, "__esModule", { + value: true + }); + var _icon = __webpack_require__( + /*! ./icon */ + "./src/icon.js" + ); + var _icon2 = _interopRequireDefault(_icon); + var _icons = __webpack_require__( + /*! ../dist/icons.json */ + "./dist/icons.json" + ); + var _icons2 = _interopRequireDefault(_icons); + var _tags = __webpack_require__( + /*! ./tags.json */ + "./src/tags.json" + ); + var _tags2 = _interopRequireDefault(_tags); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports3.default = Object.keys(_icons2.default).map(function(key2) { + return new _icon2.default(key2, _icons2.default[key2], _tags2.default[key2]); + }).reduce(function(object, icon) { + object[icon.name] = icon; + return object; + }, {}); + } + ), + /***/ + "./src/index.js": ( + /*!**********************!*\ + !*** ./src/index.js ***! + \**********************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + var _icons = __webpack_require__( + /*! ./icons */ + "./src/icons.js" + ); + var _icons2 = _interopRequireDefault(_icons); + var _toSvg = __webpack_require__( + /*! ./to-svg */ + "./src/to-svg.js" + ); + var _toSvg2 = _interopRequireDefault(_toSvg); + var _replace = __webpack_require__( + /*! ./replace */ + "./src/replace.js" + ); + var _replace2 = _interopRequireDefault(_replace); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + module3.exports = { icons: _icons2.default, toSvg: _toSvg2.default, replace: _replace2.default }; + } + ), + /***/ + "./src/replace.js": ( + /*!************************!*\ + !*** ./src/replace.js ***! + \************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + Object.defineProperty(exports3, "__esModule", { + value: true + }); + var _extends = Object.assign || function(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key2 in source) { + if (Object.prototype.hasOwnProperty.call(source, key2)) { + target[key2] = source[key2]; + } + } + } + return target; + }; + var _dedupe = __webpack_require__( + /*! classnames/dedupe */ + "./node_modules/classnames/dedupe.js" + ); + var _dedupe2 = _interopRequireDefault(_dedupe); + var _icons = __webpack_require__( + /*! ./icons */ + "./src/icons.js" + ); + var _icons2 = _interopRequireDefault(_icons); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function replace() { + var attrs = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + if (typeof document === "undefined") { + throw new Error("`feather.replace()` only works in a browser environment."); + } + var elementsToReplace = document.querySelectorAll("[data-feather]"); + Array.from(elementsToReplace).forEach(function(element2) { + return replaceElement(element2, attrs); + }); + } + function replaceElement(element2) { + var attrs = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var elementAttrs = getAttrs(element2); + var name = elementAttrs["data-feather"]; + delete elementAttrs["data-feather"]; + var svgString = _icons2.default[name].toSvg(_extends({}, attrs, elementAttrs, { class: (0, _dedupe2.default)(attrs.class, elementAttrs.class) })); + var svgDocument = new DOMParser().parseFromString(svgString, "image/svg+xml"); + var svgElement = svgDocument.querySelector("svg"); + element2.parentNode.replaceChild(svgElement, element2); + } + function getAttrs(element2) { + return Array.from(element2.attributes).reduce(function(attrs, attr2) { + attrs[attr2.name] = attr2.value; + return attrs; + }, {}); + } + exports3.default = replace; + } + ), + /***/ + "./src/tags.json": ( + /*!***********************!*\ + !*** ./src/tags.json ***! + \***********************/ + /*! exports provided: activity, airplay, alert-circle, alert-octagon, alert-triangle, align-center, align-justify, align-left, align-right, anchor, archive, at-sign, award, aperture, bar-chart, bar-chart-2, battery, battery-charging, bell, bell-off, bluetooth, book-open, book, bookmark, box, briefcase, calendar, camera, cast, chevron-down, chevron-up, circle, clipboard, clock, cloud-drizzle, cloud-lightning, cloud-rain, cloud-snow, cloud, codepen, codesandbox, code, coffee, columns, command, compass, copy, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, cpu, credit-card, crop, crosshair, database, delete, disc, dollar-sign, droplet, edit, edit-2, edit-3, eye, eye-off, external-link, facebook, fast-forward, figma, file-minus, file-plus, file-text, film, filter, flag, folder-minus, folder-plus, folder, framer, frown, gift, git-branch, git-commit, git-merge, git-pull-request, github, gitlab, globe, hard-drive, hash, headphones, heart, help-circle, hexagon, home, image, inbox, instagram, key, layers, layout, life-buoy, link, link-2, linkedin, list, lock, log-in, log-out, mail, map-pin, map, maximize, maximize-2, meh, menu, message-circle, message-square, mic-off, mic, minimize, minimize-2, minus, monitor, moon, more-horizontal, more-vertical, mouse-pointer, move, music, navigation, navigation-2, octagon, package, paperclip, pause, pause-circle, pen-tool, percent, phone-call, phone-forwarded, phone-incoming, phone-missed, phone-off, phone-outgoing, phone, play, pie-chart, play-circle, plus, plus-circle, plus-square, pocket, power, printer, radio, refresh-cw, refresh-ccw, repeat, rewind, rotate-ccw, rotate-cw, rss, save, scissors, search, send, settings, share-2, shield, shield-off, shopping-bag, shopping-cart, shuffle, skip-back, skip-forward, slack, slash, sliders, smartphone, smile, speaker, star, stop-circle, sun, sunrise, sunset, tablet, tag, target, terminal, thermometer, thumbs-down, thumbs-up, toggle-left, toggle-right, tool, trash, trash-2, triangle, truck, tv, twitch, twitter, type, umbrella, unlock, user-check, user-minus, user-plus, user-x, user, users, video-off, video, voicemail, volume, volume-1, volume-2, volume-x, watch, wifi-off, wifi, wind, x-circle, x-octagon, x-square, x, youtube, zap-off, zap, zoom-in, zoom-out, default */ + /***/ + function(module3) { + module3.exports = { "activity": ["pulse", "health", "action", "motion"], "airplay": ["stream", "cast", "mirroring"], "alert-circle": ["warning", "alert", "danger"], "alert-octagon": ["warning", "alert", "danger"], "alert-triangle": ["warning", "alert", "danger"], "align-center": ["text alignment", "center"], "align-justify": ["text alignment", "justified"], "align-left": ["text alignment", "left"], "align-right": ["text alignment", "right"], "anchor": [], "archive": ["index", "box"], "at-sign": ["mention", "at", "email", "message"], "award": ["achievement", "badge"], "aperture": ["camera", "photo"], "bar-chart": ["statistics", "diagram", "graph"], "bar-chart-2": ["statistics", "diagram", "graph"], "battery": ["power", "electricity"], "battery-charging": ["power", "electricity"], "bell": ["alarm", "notification", "sound"], "bell-off": ["alarm", "notification", "silent"], "bluetooth": ["wireless"], "book-open": ["read", "library"], "book": ["read", "dictionary", "booklet", "magazine", "library"], "bookmark": ["read", "clip", "marker", "tag"], "box": ["cube"], "briefcase": ["work", "bag", "baggage", "folder"], "calendar": ["date"], "camera": ["photo"], "cast": ["chromecast", "airplay"], "chevron-down": ["expand"], "chevron-up": ["collapse"], "circle": ["off", "zero", "record"], "clipboard": ["copy"], "clock": ["time", "watch", "alarm"], "cloud-drizzle": ["weather", "shower"], "cloud-lightning": ["weather", "bolt"], "cloud-rain": ["weather"], "cloud-snow": ["weather", "blizzard"], "cloud": ["weather"], "codepen": ["logo"], "codesandbox": ["logo"], "code": ["source", "programming"], "coffee": ["drink", "cup", "mug", "tea", "cafe", "hot", "beverage"], "columns": ["layout"], "command": ["keyboard", "cmd", "terminal", "prompt"], "compass": ["navigation", "safari", "travel", "direction"], "copy": ["clone", "duplicate"], "corner-down-left": ["arrow", "return"], "corner-down-right": ["arrow"], "corner-left-down": ["arrow"], "corner-left-up": ["arrow"], "corner-right-down": ["arrow"], "corner-right-up": ["arrow"], "corner-up-left": ["arrow"], "corner-up-right": ["arrow"], "cpu": ["processor", "technology"], "credit-card": ["purchase", "payment", "cc"], "crop": ["photo", "image"], "crosshair": ["aim", "target"], "database": ["storage", "memory"], "delete": ["remove"], "disc": ["album", "cd", "dvd", "music"], "dollar-sign": ["currency", "money", "payment"], "droplet": ["water"], "edit": ["pencil", "change"], "edit-2": ["pencil", "change"], "edit-3": ["pencil", "change"], "eye": ["view", "watch"], "eye-off": ["view", "watch", "hide", "hidden"], "external-link": ["outbound"], "facebook": ["logo", "social"], "fast-forward": ["music"], "figma": ["logo", "design", "tool"], "file-minus": ["delete", "remove", "erase"], "file-plus": ["add", "create", "new"], "file-text": ["data", "txt", "pdf"], "film": ["movie", "video"], "filter": ["funnel", "hopper"], "flag": ["report"], "folder-minus": ["directory"], "folder-plus": ["directory"], "folder": ["directory"], "framer": ["logo", "design", "tool"], "frown": ["emoji", "face", "bad", "sad", "emotion"], "gift": ["present", "box", "birthday", "party"], "git-branch": ["code", "version control"], "git-commit": ["code", "version control"], "git-merge": ["code", "version control"], "git-pull-request": ["code", "version control"], "github": ["logo", "version control"], "gitlab": ["logo", "version control"], "globe": ["world", "browser", "language", "translate"], "hard-drive": ["computer", "server", "memory", "data"], "hash": ["hashtag", "number", "pound"], "headphones": ["music", "audio", "sound"], "heart": ["like", "love", "emotion"], "help-circle": ["question mark"], "hexagon": ["shape", "node.js", "logo"], "home": ["house", "living"], "image": ["picture"], "inbox": ["email"], "instagram": ["logo", "camera"], "key": ["password", "login", "authentication", "secure"], "layers": ["stack"], "layout": ["window", "webpage"], "life-buoy": ["help", "life ring", "support"], "link": ["chain", "url"], "link-2": ["chain", "url"], "linkedin": ["logo", "social media"], "list": ["options"], "lock": ["security", "password", "secure"], "log-in": ["sign in", "arrow", "enter"], "log-out": ["sign out", "arrow", "exit"], "mail": ["email", "message"], "map-pin": ["location", "navigation", "travel", "marker"], "map": ["location", "navigation", "travel"], "maximize": ["fullscreen"], "maximize-2": ["fullscreen", "arrows", "expand"], "meh": ["emoji", "face", "neutral", "emotion"], "menu": ["bars", "navigation", "hamburger"], "message-circle": ["comment", "chat"], "message-square": ["comment", "chat"], "mic-off": ["record", "sound", "mute"], "mic": ["record", "sound", "listen"], "minimize": ["exit fullscreen", "close"], "minimize-2": ["exit fullscreen", "arrows", "close"], "minus": ["subtract"], "monitor": ["tv", "screen", "display"], "moon": ["dark", "night"], "more-horizontal": ["ellipsis"], "more-vertical": ["ellipsis"], "mouse-pointer": ["arrow", "cursor"], "move": ["arrows"], "music": ["note"], "navigation": ["location", "travel"], "navigation-2": ["location", "travel"], "octagon": ["stop"], "package": ["box", "container"], "paperclip": ["attachment"], "pause": ["music", "stop"], "pause-circle": ["music", "audio", "stop"], "pen-tool": ["vector", "drawing"], "percent": ["discount"], "phone-call": ["ring"], "phone-forwarded": ["call"], "phone-incoming": ["call"], "phone-missed": ["call"], "phone-off": ["call", "mute"], "phone-outgoing": ["call"], "phone": ["call"], "play": ["music", "start"], "pie-chart": ["statistics", "diagram"], "play-circle": ["music", "start"], "plus": ["add", "new"], "plus-circle": ["add", "new"], "plus-square": ["add", "new"], "pocket": ["logo", "save"], "power": ["on", "off"], "printer": ["fax", "office", "device"], "radio": ["signal"], "refresh-cw": ["synchronise", "arrows"], "refresh-ccw": ["arrows"], "repeat": ["loop", "arrows"], "rewind": ["music"], "rotate-ccw": ["arrow"], "rotate-cw": ["arrow"], "rss": ["feed", "subscribe"], "save": ["floppy disk"], "scissors": ["cut"], "search": ["find", "magnifier", "magnifying glass"], "send": ["message", "mail", "email", "paper airplane", "paper aeroplane"], "settings": ["cog", "edit", "gear", "preferences"], "share-2": ["network", "connections"], "shield": ["security", "secure"], "shield-off": ["security", "insecure"], "shopping-bag": ["ecommerce", "cart", "purchase", "store"], "shopping-cart": ["ecommerce", "cart", "purchase", "store"], "shuffle": ["music"], "skip-back": ["music"], "skip-forward": ["music"], "slack": ["logo"], "slash": ["ban", "no"], "sliders": ["settings", "controls"], "smartphone": ["cellphone", "device"], "smile": ["emoji", "face", "happy", "good", "emotion"], "speaker": ["audio", "music"], "star": ["bookmark", "favorite", "like"], "stop-circle": ["media", "music"], "sun": ["brightness", "weather", "light"], "sunrise": ["weather", "time", "morning", "day"], "sunset": ["weather", "time", "evening", "night"], "tablet": ["device"], "tag": ["label"], "target": ["logo", "bullseye"], "terminal": ["code", "command line", "prompt"], "thermometer": ["temperature", "celsius", "fahrenheit", "weather"], "thumbs-down": ["dislike", "bad", "emotion"], "thumbs-up": ["like", "good", "emotion"], "toggle-left": ["on", "off", "switch"], "toggle-right": ["on", "off", "switch"], "tool": ["settings", "spanner"], "trash": ["garbage", "delete", "remove", "bin"], "trash-2": ["garbage", "delete", "remove", "bin"], "triangle": ["delta"], "truck": ["delivery", "van", "shipping", "transport", "lorry"], "tv": ["television", "stream"], "twitch": ["logo"], "twitter": ["logo", "social"], "type": ["text"], "umbrella": ["rain", "weather"], "unlock": ["security"], "user-check": ["followed", "subscribed"], "user-minus": ["delete", "remove", "unfollow", "unsubscribe"], "user-plus": ["new", "add", "create", "follow", "subscribe"], "user-x": ["delete", "remove", "unfollow", "unsubscribe", "unavailable"], "user": ["person", "account"], "users": ["group"], "video-off": ["camera", "movie", "film"], "video": ["camera", "movie", "film"], "voicemail": ["phone"], "volume": ["music", "sound", "mute"], "volume-1": ["music", "sound"], "volume-2": ["music", "sound"], "volume-x": ["music", "sound", "mute"], "watch": ["clock", "time"], "wifi-off": ["disabled"], "wifi": ["connection", "signal", "wireless"], "wind": ["weather", "air"], "x-circle": ["cancel", "close", "delete", "remove", "times", "clear"], "x-octagon": ["delete", "stop", "alert", "warning", "times", "clear"], "x-square": ["cancel", "close", "delete", "remove", "times", "clear"], "x": ["cancel", "close", "delete", "remove", "times", "clear"], "youtube": ["logo", "video", "play"], "zap-off": ["flash", "camera", "lightning"], "zap": ["flash", "camera", "lightning"], "zoom-in": ["magnifying glass"], "zoom-out": ["magnifying glass"] }; + } + ), + /***/ + "./src/to-svg.js": ( + /*!***********************!*\ + !*** ./src/to-svg.js ***! + \***********************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + "use strict"; + Object.defineProperty(exports3, "__esModule", { + value: true + }); + var _icons = __webpack_require__( + /*! ./icons */ + "./src/icons.js" + ); + var _icons2 = _interopRequireDefault(_icons); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function toSvg(name) { + var attrs = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + console.warn("feather.toSvg() is deprecated. Please use feather.icons[name].toSvg() instead."); + if (!name) { + throw new Error("The required `key` (icon name) parameter is missing."); + } + if (!_icons2.default[name]) { + throw new Error("No icon matching '" + name + "'. See the complete list of icons at https://feathericons.com"); + } + return _icons2.default[name].toSvg(attrs); + } + exports3.default = toSvg; + } + ), + /***/ + 0: ( + /*!**************************************************!*\ + !*** multi core-js/es/array/from ./src/index.js ***! + \**************************************************/ + /*! no static exports found */ + /***/ + function(module3, exports3, __webpack_require__) { + __webpack_require__( + /*! core-js/es/array/from */ + "./node_modules/core-js/es/array/from.js" + ); + module3.exports = __webpack_require__( + /*! /home/runner/work/feather/feather/src/index.js */ + "./src/index.js" + ); + } + ) + /******/ + }) + ); + }); + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => ObsidianGit +}); +module.exports = __toCommonJS(main_exports); +init_polyfill_buffer(); + +// node_modules/.pnpm/isomorphic-git@1.25.3/node_modules/isomorphic-git/index.js +init_polyfill_buffer(); +var import_async_lock = __toESM(require_async_lock(), 1); +var import_sha1 = __toESM(require_sha1(), 1); +var import_crc_32 = __toESM(require_crc32(), 1); +var import_pako = __toESM(require_pako(), 1); +var import_pify = __toESM(require_pify(), 1); +var import_ignore = __toESM(require_ignore(), 1); +var import_clean_git_ref = __toESM(require_lib2(), 1); +var import_diff3 = __toESM(require_diff3(), 1); +var BaseError = class _BaseError extends Error { + constructor(message) { + super(message); + this.caller = ""; + } + toJSON() { + return { + code: this.code, + data: this.data, + caller: this.caller, + message: this.message, + stack: this.stack + }; + } + fromJSON(json) { + const e = new _BaseError(json.message); + e.code = json.code; + e.data = json.data; + e.caller = json.caller; + e.stack = json.stack; + return e; + } + get isIsomorphicGitError() { + return true; + } +}; +var UnmergedPathsError = class _UnmergedPathsError extends BaseError { + /** + * @param {Array} filepaths + */ + constructor(filepaths) { + super( + `Modifying the index is not possible because you have unmerged files: ${filepaths.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.` + ); + this.code = this.name = _UnmergedPathsError.code; + this.data = { filepaths }; + } +}; +UnmergedPathsError.code = "UnmergedPathsError"; +var InternalError = class _InternalError extends BaseError { + /** + * @param {string} message + */ + constructor(message) { + super( + `An internal error caused this command to fail. Please file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${message}` + ); + this.code = this.name = _InternalError.code; + this.data = { message }; + } +}; +InternalError.code = "InternalError"; +var UnsafeFilepathError = class _UnsafeFilepathError extends BaseError { + /** + * @param {string} filepath + */ + constructor(filepath) { + super(`The filepath "${filepath}" contains unsafe character sequences`); + this.code = this.name = _UnsafeFilepathError.code; + this.data = { filepath }; + } +}; +UnsafeFilepathError.code = "UnsafeFilepathError"; +var BufferCursor = class { + constructor(buffer2) { + this.buffer = buffer2; + this._start = 0; + } + eof() { + return this._start >= this.buffer.length; + } + tell() { + return this._start; + } + seek(n) { + this._start = n; + } + slice(n) { + const r = this.buffer.slice(this._start, this._start + n); + this._start += n; + return r; + } + toString(enc, length) { + const r = this.buffer.toString(enc, this._start, this._start + length); + this._start += length; + return r; + } + write(value, length, enc) { + const r = this.buffer.write(value, this._start, length, enc); + this._start += length; + return r; + } + copy(source, start, end) { + const r = source.copy(this.buffer, this._start, start, end); + this._start += r; + return r; + } + readUInt8() { + const r = this.buffer.readUInt8(this._start); + this._start += 1; + return r; + } + writeUInt8(value) { + const r = this.buffer.writeUInt8(value, this._start); + this._start += 1; + return r; + } + readUInt16BE() { + const r = this.buffer.readUInt16BE(this._start); + this._start += 2; + return r; + } + writeUInt16BE(value) { + const r = this.buffer.writeUInt16BE(value, this._start); + this._start += 2; + return r; + } + readUInt32BE() { + const r = this.buffer.readUInt32BE(this._start); + this._start += 4; + return r; + } + writeUInt32BE(value) { + const r = this.buffer.writeUInt32BE(value, this._start); + this._start += 4; + return r; + } +}; +function compareStrings(a, b) { + return -(a < b) || +(a > b); +} +function comparePath(a, b) { + return compareStrings(a.path, b.path); +} +function normalizeMode(mode) { + let type = mode > 0 ? mode >> 12 : 0; + if (type !== 4 && type !== 8 && type !== 10 && type !== 14) { + type = 8; + } + let permissions = mode & 511; + if (permissions & 73) { + permissions = 493; + } else { + permissions = 420; + } + if (type !== 8) + permissions = 0; + return (type << 12) + permissions; +} +var MAX_UINT32 = 2 ** 32; +function SecondsNanoseconds(givenSeconds, givenNanoseconds, milliseconds, date) { + if (givenSeconds !== void 0 && givenNanoseconds !== void 0) { + return [givenSeconds, givenNanoseconds]; + } + if (milliseconds === void 0) { + milliseconds = date.valueOf(); + } + const seconds = Math.floor(milliseconds / 1e3); + const nanoseconds = (milliseconds - seconds * 1e3) * 1e6; + return [seconds, nanoseconds]; +} +function normalizeStats(e) { + const [ctimeSeconds, ctimeNanoseconds] = SecondsNanoseconds( + e.ctimeSeconds, + e.ctimeNanoseconds, + e.ctimeMs, + e.ctime + ); + const [mtimeSeconds, mtimeNanoseconds] = SecondsNanoseconds( + e.mtimeSeconds, + e.mtimeNanoseconds, + e.mtimeMs, + e.mtime + ); + return { + ctimeSeconds: ctimeSeconds % MAX_UINT32, + ctimeNanoseconds: ctimeNanoseconds % MAX_UINT32, + mtimeSeconds: mtimeSeconds % MAX_UINT32, + mtimeNanoseconds: mtimeNanoseconds % MAX_UINT32, + dev: e.dev % MAX_UINT32, + ino: e.ino % MAX_UINT32, + mode: normalizeMode(e.mode % MAX_UINT32), + uid: e.uid % MAX_UINT32, + gid: e.gid % MAX_UINT32, + // size of -1 happens over a BrowserFS HTTP Backend that doesn't serve Content-Length headers + // (like the Karma webserver) because BrowserFS HTTP Backend uses HTTP HEAD requests to do fs.stat + size: e.size > -1 ? e.size % MAX_UINT32 : 0 + }; +} +function toHex(buffer2) { + let hex = ""; + for (const byte of new Uint8Array(buffer2)) { + if (byte < 16) + hex += "0"; + hex += byte.toString(16); + } + return hex; +} +var supportsSubtleSHA1 = null; +async function shasum(buffer2) { + if (supportsSubtleSHA1 === null) { + supportsSubtleSHA1 = await testSubtleSHA1(); + } + return supportsSubtleSHA1 ? subtleSHA1(buffer2) : shasumSync(buffer2); +} +function shasumSync(buffer2) { + return new import_sha1.default().update(buffer2).digest("hex"); +} +async function subtleSHA1(buffer2) { + const hash2 = await crypto.subtle.digest("SHA-1", buffer2); + return toHex(hash2); +} +async function testSubtleSHA1() { + try { + const hash2 = await subtleSHA1(new Uint8Array([])); + if (hash2 === "da39a3ee5e6b4b0d3255bfef95601890afd80709") + return true; + } catch (_) { + } + return false; +} +function parseCacheEntryFlags(bits) { + return { + assumeValid: Boolean(bits & 32768), + extended: Boolean(bits & 16384), + stage: (bits & 12288) >> 12, + nameLength: bits & 4095 + }; +} +function renderCacheEntryFlags(entry) { + const flags = entry.flags; + flags.extended = false; + flags.nameLength = Math.min(Buffer.from(entry.path).length, 4095); + return (flags.assumeValid ? 32768 : 0) + (flags.extended ? 16384 : 0) + ((flags.stage & 3) << 12) + (flags.nameLength & 4095); +} +var GitIndex = class _GitIndex { + /*:: + _entries: Map + _dirty: boolean // Used to determine if index needs to be saved to filesystem + */ + constructor(entries, unmergedPaths) { + this._dirty = false; + this._unmergedPaths = unmergedPaths || /* @__PURE__ */ new Set(); + this._entries = entries || /* @__PURE__ */ new Map(); + } + _addEntry(entry) { + if (entry.flags.stage === 0) { + entry.stages = [entry]; + this._entries.set(entry.path, entry); + this._unmergedPaths.delete(entry.path); + } else { + let existingEntry = this._entries.get(entry.path); + if (!existingEntry) { + this._entries.set(entry.path, entry); + existingEntry = entry; + } + existingEntry.stages[entry.flags.stage] = entry; + this._unmergedPaths.add(entry.path); + } + } + static async from(buffer2) { + if (Buffer.isBuffer(buffer2)) { + return _GitIndex.fromBuffer(buffer2); + } else if (buffer2 === null) { + return new _GitIndex(null); + } else { + throw new InternalError("invalid type passed to GitIndex.from"); + } + } + static async fromBuffer(buffer2) { + if (buffer2.length === 0) { + throw new InternalError("Index file is empty (.git/index)"); + } + const index2 = new _GitIndex(); + const reader = new BufferCursor(buffer2); + const magic = reader.toString("utf8", 4); + if (magic !== "DIRC") { + throw new InternalError(`Invalid dircache magic file number: ${magic}`); + } + const shaComputed = await shasum(buffer2.slice(0, -20)); + const shaClaimed = buffer2.slice(-20).toString("hex"); + if (shaClaimed !== shaComputed) { + throw new InternalError( + `Invalid checksum in GitIndex buffer: expected ${shaClaimed} but saw ${shaComputed}` + ); + } + const version2 = reader.readUInt32BE(); + if (version2 !== 2) { + throw new InternalError(`Unsupported dircache version: ${version2}`); + } + const numEntries = reader.readUInt32BE(); + let i = 0; + while (!reader.eof() && i < numEntries) { + const entry = {}; + entry.ctimeSeconds = reader.readUInt32BE(); + entry.ctimeNanoseconds = reader.readUInt32BE(); + entry.mtimeSeconds = reader.readUInt32BE(); + entry.mtimeNanoseconds = reader.readUInt32BE(); + entry.dev = reader.readUInt32BE(); + entry.ino = reader.readUInt32BE(); + entry.mode = reader.readUInt32BE(); + entry.uid = reader.readUInt32BE(); + entry.gid = reader.readUInt32BE(); + entry.size = reader.readUInt32BE(); + entry.oid = reader.slice(20).toString("hex"); + const flags = reader.readUInt16BE(); + entry.flags = parseCacheEntryFlags(flags); + const pathlength = buffer2.indexOf(0, reader.tell() + 1) - reader.tell(); + if (pathlength < 1) { + throw new InternalError(`Got a path length of: ${pathlength}`); + } + entry.path = reader.toString("utf8", pathlength); + if (entry.path.includes("..\\") || entry.path.includes("../")) { + throw new UnsafeFilepathError(entry.path); + } + let padding = 8 - (reader.tell() - 12) % 8; + if (padding === 0) + padding = 8; + while (padding--) { + const tmp = reader.readUInt8(); + if (tmp !== 0) { + throw new InternalError( + `Expected 1-8 null characters but got '${tmp}' after ${entry.path}` + ); + } else if (reader.eof()) { + throw new InternalError("Unexpected end of file"); + } + } + entry.stages = []; + index2._addEntry(entry); + i++; + } + return index2; + } + get unmergedPaths() { + return [...this._unmergedPaths]; + } + get entries() { + return [...this._entries.values()].sort(comparePath); + } + get entriesMap() { + return this._entries; + } + get entriesFlat() { + return [...this.entries].flatMap((entry) => { + return entry.stages.length > 1 ? entry.stages.filter((x) => x) : entry; + }); + } + *[Symbol.iterator]() { + for (const entry of this.entries) { + yield entry; + } + } + insert({ filepath, stats, oid, stage = 0 }) { + if (!stats) { + stats = { + ctimeSeconds: 0, + ctimeNanoseconds: 0, + mtimeSeconds: 0, + mtimeNanoseconds: 0, + dev: 0, + ino: 0, + mode: 0, + uid: 0, + gid: 0, + size: 0 + }; + } + stats = normalizeStats(stats); + const bfilepath = Buffer.from(filepath); + const entry = { + ctimeSeconds: stats.ctimeSeconds, + ctimeNanoseconds: stats.ctimeNanoseconds, + mtimeSeconds: stats.mtimeSeconds, + mtimeNanoseconds: stats.mtimeNanoseconds, + dev: stats.dev, + ino: stats.ino, + // We provide a fallback value for `mode` here because not all fs + // implementations assign it, but we use it in GitTree. + // '100644' is for a "regular non-executable file" + mode: stats.mode || 33188, + uid: stats.uid, + gid: stats.gid, + size: stats.size, + path: filepath, + oid, + flags: { + assumeValid: false, + extended: false, + stage, + nameLength: bfilepath.length < 4095 ? bfilepath.length : 4095 + }, + stages: [] + }; + this._addEntry(entry); + this._dirty = true; + } + delete({ filepath }) { + if (this._entries.has(filepath)) { + this._entries.delete(filepath); + } else { + for (const key2 of this._entries.keys()) { + if (key2.startsWith(filepath + "/")) { + this._entries.delete(key2); + } + } + } + if (this._unmergedPaths.has(filepath)) { + this._unmergedPaths.delete(filepath); + } + this._dirty = true; + } + clear() { + this._entries.clear(); + this._dirty = true; + } + has({ filepath }) { + return this._entries.has(filepath); + } + render() { + return this.entries.map((entry) => `${entry.mode.toString(8)} ${entry.oid} ${entry.path}`).join("\n"); + } + static async _entryToBuffer(entry) { + const bpath = Buffer.from(entry.path); + const length = Math.ceil((62 + bpath.length + 1) / 8) * 8; + const written = Buffer.alloc(length); + const writer = new BufferCursor(written); + const stat = normalizeStats(entry); + writer.writeUInt32BE(stat.ctimeSeconds); + writer.writeUInt32BE(stat.ctimeNanoseconds); + writer.writeUInt32BE(stat.mtimeSeconds); + writer.writeUInt32BE(stat.mtimeNanoseconds); + writer.writeUInt32BE(stat.dev); + writer.writeUInt32BE(stat.ino); + writer.writeUInt32BE(stat.mode); + writer.writeUInt32BE(stat.uid); + writer.writeUInt32BE(stat.gid); + writer.writeUInt32BE(stat.size); + writer.write(entry.oid, 20, "hex"); + writer.writeUInt16BE(renderCacheEntryFlags(entry)); + writer.write(entry.path, bpath.length, "utf8"); + return written; + } + async toObject() { + const header = Buffer.alloc(12); + const writer = new BufferCursor(header); + writer.write("DIRC", 4, "utf8"); + writer.writeUInt32BE(2); + writer.writeUInt32BE(this.entriesFlat.length); + let entryBuffers = []; + for (const entry of this.entries) { + entryBuffers.push(_GitIndex._entryToBuffer(entry)); + if (entry.stages.length > 1) { + for (const stage of entry.stages) { + if (stage && stage !== entry) { + entryBuffers.push(_GitIndex._entryToBuffer(stage)); + } + } + } + } + entryBuffers = await Promise.all(entryBuffers); + const body = Buffer.concat(entryBuffers); + const main = Buffer.concat([header, body]); + const sum = await shasum(main); + return Buffer.concat([main, Buffer.from(sum, "hex")]); + } +}; +function compareStats(entry, stats) { + const e = normalizeStats(entry); + const s = normalizeStats(stats); + const staleness = e.mode !== s.mode || e.mtimeSeconds !== s.mtimeSeconds || e.ctimeSeconds !== s.ctimeSeconds || e.uid !== s.uid || e.gid !== s.gid || e.ino !== s.ino || e.size !== s.size; + return staleness; +} +var lock = null; +var IndexCache = Symbol("IndexCache"); +function createCache() { + return { + map: /* @__PURE__ */ new Map(), + stats: /* @__PURE__ */ new Map() + }; +} +async function updateCachedIndexFile(fs, filepath, cache) { + const stat = await fs.lstat(filepath); + const rawIndexFile = await fs.read(filepath); + const index2 = await GitIndex.from(rawIndexFile); + cache.map.set(filepath, index2); + cache.stats.set(filepath, stat); +} +async function isIndexStale(fs, filepath, cache) { + const savedStats = cache.stats.get(filepath); + if (savedStats === void 0) + return true; + const currStats = await fs.lstat(filepath); + if (savedStats === null) + return false; + if (currStats === null) + return false; + return compareStats(savedStats, currStats); +} +var GitIndexManager = class { + /** + * + * @param {object} opts + * @param {import('../models/FileSystem.js').FileSystem} opts.fs + * @param {string} opts.gitdir + * @param {object} opts.cache + * @param {bool} opts.allowUnmerged + * @param {function(GitIndex): any} closure + */ + static async acquire({ fs, gitdir, cache, allowUnmerged = true }, closure) { + if (!cache[IndexCache]) + cache[IndexCache] = createCache(); + const filepath = `${gitdir}/index`; + if (lock === null) + lock = new import_async_lock.default({ maxPending: Infinity }); + let result; + let unmergedPaths = []; + await lock.acquire(filepath, async () => { + if (await isIndexStale(fs, filepath, cache[IndexCache])) { + await updateCachedIndexFile(fs, filepath, cache[IndexCache]); + } + const index2 = cache[IndexCache].map.get(filepath); + unmergedPaths = index2.unmergedPaths; + if (unmergedPaths.length && !allowUnmerged) + throw new UnmergedPathsError(unmergedPaths); + result = await closure(index2); + if (index2._dirty) { + const buffer2 = await index2.toObject(); + await fs.write(filepath, buffer2); + cache[IndexCache].stats.set(filepath, await fs.lstat(filepath)); + index2._dirty = false; + } + }); + return result; + } +}; +function basename(path2) { + const last2 = Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\")); + if (last2 > -1) { + path2 = path2.slice(last2 + 1); + } + return path2; +} +function dirname(path2) { + const last2 = Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\")); + if (last2 === -1) + return "."; + if (last2 === 0) + return "/"; + return path2.slice(0, last2); +} +function flatFileListToDirectoryStructure(files) { + const inodes = /* @__PURE__ */ new Map(); + const mkdir = function(name) { + if (!inodes.has(name)) { + const dir = { + type: "tree", + fullpath: name, + basename: basename(name), + metadata: {}, + children: [] + }; + inodes.set(name, dir); + dir.parent = mkdir(dirname(name)); + if (dir.parent && dir.parent !== dir) + dir.parent.children.push(dir); + } + return inodes.get(name); + }; + const mkfile = function(name, metadata) { + if (!inodes.has(name)) { + const file = { + type: "blob", + fullpath: name, + basename: basename(name), + metadata, + // This recursively generates any missing parent folders. + parent: mkdir(dirname(name)), + children: [] + }; + if (file.parent) + file.parent.children.push(file); + inodes.set(name, file); + } + return inodes.get(name); + }; + mkdir("."); + for (const file of files) { + mkfile(file.path, file); + } + return inodes; +} +function mode2type(mode) { + switch (mode) { + case 16384: + return "tree"; + case 33188: + return "blob"; + case 33261: + return "blob"; + case 40960: + return "blob"; + case 57344: + return "commit"; + } + throw new InternalError(`Unexpected GitTree entry mode: ${mode.toString(8)}`); +} +var GitWalkerIndex = class { + constructor({ fs, gitdir, cache }) { + this.treePromise = GitIndexManager.acquire( + { fs, gitdir, cache }, + async function(index2) { + return flatFileListToDirectoryStructure(index2.entries); + } + ); + const walker = this; + this.ConstructEntry = class StageEntry { + constructor(fullpath) { + this._fullpath = fullpath; + this._type = false; + this._mode = false; + this._stat = false; + this._oid = false; + } + async type() { + return walker.type(this); + } + async mode() { + return walker.mode(this); + } + async stat() { + return walker.stat(this); + } + async content() { + return walker.content(this); + } + async oid() { + return walker.oid(this); + } + }; + } + async readdir(entry) { + const filepath = entry._fullpath; + const tree = await this.treePromise; + const inode = tree.get(filepath); + if (!inode) + return null; + if (inode.type === "blob") + return null; + if (inode.type !== "tree") { + throw new Error(`ENOTDIR: not a directory, scandir '${filepath}'`); + } + const names = inode.children.map((inode2) => inode2.fullpath); + names.sort(compareStrings); + return names; + } + async type(entry) { + if (entry._type === false) { + await entry.stat(); + } + return entry._type; + } + async mode(entry) { + if (entry._mode === false) { + await entry.stat(); + } + return entry._mode; + } + async stat(entry) { + if (entry._stat === false) { + const tree = await this.treePromise; + const inode = tree.get(entry._fullpath); + if (!inode) { + throw new Error( + `ENOENT: no such file or directory, lstat '${entry._fullpath}'` + ); + } + const stats = inode.type === "tree" ? {} : normalizeStats(inode.metadata); + entry._type = inode.type === "tree" ? "tree" : mode2type(stats.mode); + entry._mode = stats.mode; + if (inode.type === "tree") { + entry._stat = void 0; + } else { + entry._stat = stats; + } + } + return entry._stat; + } + async content(_entry) { + } + async oid(entry) { + if (entry._oid === false) { + const tree = await this.treePromise; + const inode = tree.get(entry._fullpath); + entry._oid = inode.metadata.oid; + } + return entry._oid; + } +}; +var GitWalkSymbol = Symbol("GitWalkSymbol"); +function STAGE() { + const o = /* @__PURE__ */ Object.create(null); + Object.defineProperty(o, GitWalkSymbol, { + value: function({ fs, gitdir, cache }) { + return new GitWalkerIndex({ fs, gitdir, cache }); + } + }); + Object.freeze(o); + return o; +} +var NotFoundError = class _NotFoundError extends BaseError { + /** + * @param {string} what + */ + constructor(what) { + super(`Could not find ${what}.`); + this.code = this.name = _NotFoundError.code; + this.data = { what }; + } +}; +NotFoundError.code = "NotFoundError"; +var ObjectTypeError = class _ObjectTypeError extends BaseError { + /** + * @param {string} oid + * @param {'blob'|'commit'|'tag'|'tree'} actual + * @param {'blob'|'commit'|'tag'|'tree'} expected + * @param {string} [filepath] + */ + constructor(oid, actual, expected, filepath) { + super( + `Object ${oid} ${filepath ? `at ${filepath}` : ""}was anticipated to be a ${expected} but it is a ${actual}.` + ); + this.code = this.name = _ObjectTypeError.code; + this.data = { oid, actual, expected, filepath }; + } +}; +ObjectTypeError.code = "ObjectTypeError"; +var InvalidOidError = class _InvalidOidError extends BaseError { + /** + * @param {string} value + */ + constructor(value) { + super(`Expected a 40-char hex object id but saw "${value}".`); + this.code = this.name = _InvalidOidError.code; + this.data = { value }; + } +}; +InvalidOidError.code = "InvalidOidError"; +var NoRefspecError = class _NoRefspecError extends BaseError { + /** + * @param {string} remote + */ + constructor(remote) { + super(`Could not find a fetch refspec for remote "${remote}". Make sure the config file has an entry like the following: +[remote "${remote}"] + fetch = +refs/heads/*:refs/remotes/origin/* +`); + this.code = this.name = _NoRefspecError.code; + this.data = { remote }; + } +}; +NoRefspecError.code = "NoRefspecError"; +var GitPackedRefs = class _GitPackedRefs { + constructor(text2) { + this.refs = /* @__PURE__ */ new Map(); + this.parsedConfig = []; + if (text2) { + let key2 = null; + this.parsedConfig = text2.trim().split("\n").map((line) => { + if (/^\s*#/.test(line)) { + return { line, comment: true }; + } + const i = line.indexOf(" "); + if (line.startsWith("^")) { + const value = line.slice(1); + this.refs.set(key2 + "^{}", value); + return { line, ref: key2, peeled: value }; + } else { + const value = line.slice(0, i); + key2 = line.slice(i + 1); + this.refs.set(key2, value); + return { line, ref: key2, oid: value }; + } + }); + } + return this; + } + static from(text2) { + return new _GitPackedRefs(text2); + } + delete(ref) { + this.parsedConfig = this.parsedConfig.filter((entry) => entry.ref !== ref); + this.refs.delete(ref); + } + toString() { + return this.parsedConfig.map(({ line }) => line).join("\n") + "\n"; + } +}; +var GitRefSpec = class _GitRefSpec { + constructor({ remotePath, localPath, force, matchPrefix }) { + Object.assign(this, { + remotePath, + localPath, + force, + matchPrefix + }); + } + static from(refspec) { + const [ + forceMatch, + remotePath, + remoteGlobMatch, + localPath, + localGlobMatch + ] = refspec.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1); + const force = forceMatch === "+"; + const remoteIsGlob = remoteGlobMatch === "*"; + const localIsGlob = localGlobMatch === "*"; + if (remoteIsGlob !== localIsGlob) { + throw new InternalError("Invalid refspec"); + } + return new _GitRefSpec({ + remotePath, + localPath, + force, + matchPrefix: remoteIsGlob + }); + } + translate(remoteBranch) { + if (this.matchPrefix) { + if (remoteBranch.startsWith(this.remotePath)) { + return this.localPath + remoteBranch.replace(this.remotePath, ""); + } + } else { + if (remoteBranch === this.remotePath) + return this.localPath; + } + return null; + } + reverseTranslate(localBranch) { + if (this.matchPrefix) { + if (localBranch.startsWith(this.localPath)) { + return this.remotePath + localBranch.replace(this.localPath, ""); + } + } else { + if (localBranch === this.localPath) + return this.remotePath; + } + return null; + } +}; +var GitRefSpecSet = class _GitRefSpecSet { + constructor(rules = []) { + this.rules = rules; + } + static from(refspecs) { + const rules = []; + for (const refspec of refspecs) { + rules.push(GitRefSpec.from(refspec)); + } + return new _GitRefSpecSet(rules); + } + add(refspec) { + const rule = GitRefSpec.from(refspec); + this.rules.push(rule); + } + translate(remoteRefs) { + const result = []; + for (const rule of this.rules) { + for (const remoteRef of remoteRefs) { + const localRef = rule.translate(remoteRef); + if (localRef) { + result.push([remoteRef, localRef]); + } + } + } + return result; + } + translateOne(remoteRef) { + let result = null; + for (const rule of this.rules) { + const localRef = rule.translate(remoteRef); + if (localRef) { + result = localRef; + } + } + return result; + } + localNamespaces() { + return this.rules.filter((rule) => rule.matchPrefix).map((rule) => rule.localPath.replace(/\/$/, "")); + } +}; +function compareRefNames(a, b) { + const _a2 = a.replace(/\^\{\}$/, ""); + const _b = b.replace(/\^\{\}$/, ""); + const tmp = -(_a2 < _b) || +(_a2 > _b); + if (tmp === 0) { + return a.endsWith("^{}") ? 1 : -1; + } + return tmp; +} +var memo = /* @__PURE__ */ new Map(); +function normalizePath(path2) { + let normalizedPath = memo.get(path2); + if (!normalizedPath) { + normalizedPath = normalizePathInternal(path2); + memo.set(path2, normalizedPath); + } + return normalizedPath; +} +function normalizePathInternal(path2) { + path2 = path2.split("/./").join("/").replace(/\/{2,}/g, "/"); + if (path2 === "/.") + return "/"; + if (path2 === "./") + return "."; + if (path2.startsWith("./")) + path2 = path2.slice(2); + if (path2.endsWith("/.")) + path2 = path2.slice(0, -2); + if (path2.length > 1 && path2.endsWith("/")) + path2 = path2.slice(0, -1); + if (path2 === "") + return "."; + return path2; +} +function join(...parts) { + return normalizePath(parts.map(normalizePath).join("/")); +} +var num = (val) => { + val = val.toLowerCase(); + let n = parseInt(val); + if (val.endsWith("k")) + n *= 1024; + if (val.endsWith("m")) + n *= 1024 * 1024; + if (val.endsWith("g")) + n *= 1024 * 1024 * 1024; + return n; +}; +var bool = (val) => { + val = val.trim().toLowerCase(); + if (val === "true" || val === "yes" || val === "on") + return true; + if (val === "false" || val === "no" || val === "off") + return false; + throw Error( + `Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${val}` + ); +}; +var schema = { + core: { + filemode: bool, + bare: bool, + logallrefupdates: bool, + symlinks: bool, + ignorecase: bool, + bigFileThreshold: num + } +}; +var SECTION_LINE_REGEX = /^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/; +var SECTION_REGEX = /^[A-Za-z0-9-.]+$/; +var VARIABLE_LINE_REGEX = /^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/; +var VARIABLE_NAME_REGEX = /^[A-Za-z][A-Za-z-]*$/; +var VARIABLE_VALUE_COMMENT_REGEX = /^(.*?)( *[#;].*)$/; +var extractSectionLine = (line) => { + const matches = SECTION_LINE_REGEX.exec(line); + if (matches != null) { + const [section, subsection] = matches.slice(1); + return [section, subsection]; + } + return null; +}; +var extractVariableLine = (line) => { + const matches = VARIABLE_LINE_REGEX.exec(line); + if (matches != null) { + const [name, rawValue = "true"] = matches.slice(1); + const valueWithoutComments = removeComments(rawValue); + const valueWithoutQuotes = removeQuotes(valueWithoutComments); + return [name, valueWithoutQuotes]; + } + return null; +}; +var removeComments = (rawValue) => { + const commentMatches = VARIABLE_VALUE_COMMENT_REGEX.exec(rawValue); + if (commentMatches == null) { + return rawValue; + } + const [valueWithoutComment, comment] = commentMatches.slice(1); + if (hasOddNumberOfQuotes(valueWithoutComment) && hasOddNumberOfQuotes(comment)) { + return `${valueWithoutComment}${comment}`; + } + return valueWithoutComment; +}; +var hasOddNumberOfQuotes = (text2) => { + const numberOfQuotes = (text2.match(/(?:^|[^\\])"/g) || []).length; + return numberOfQuotes % 2 !== 0; +}; +var removeQuotes = (text2) => { + return text2.split("").reduce((newText, c, idx, text3) => { + const isQuote = c === '"' && text3[idx - 1] !== "\\"; + const isEscapeForQuote = c === "\\" && text3[idx + 1] === '"'; + if (isQuote || isEscapeForQuote) { + return newText; + } + return newText + c; + }, ""); +}; +var lower = (text2) => { + return text2 != null ? text2.toLowerCase() : null; +}; +var getPath = (section, subsection, name) => { + return [lower(section), subsection, lower(name)].filter((a) => a != null).join("."); +}; +var normalizePath$1 = (path2) => { + const pathSegments = path2.split("."); + const section = pathSegments.shift(); + const name = pathSegments.pop(); + const subsection = pathSegments.length ? pathSegments.join(".") : void 0; + return { + section, + subsection, + name, + path: getPath(section, subsection, name), + sectionPath: getPath(section, subsection, null) + }; +}; +var findLastIndex = (array, callback) => { + return array.reduce((lastIndex, item, index2) => { + return callback(item) ? index2 : lastIndex; + }, -1); +}; +var GitConfig = class _GitConfig { + constructor(text2) { + let section = null; + let subsection = null; + this.parsedConfig = text2.split("\n").map((line) => { + let name = null; + let value = null; + const trimmedLine = line.trim(); + const extractedSection = extractSectionLine(trimmedLine); + const isSection = extractedSection != null; + if (isSection) { + ; + [section, subsection] = extractedSection; + } else { + const extractedVariable = extractVariableLine(trimmedLine); + const isVariable = extractedVariable != null; + if (isVariable) { + ; + [name, value] = extractedVariable; + } + } + const path2 = getPath(section, subsection, name); + return { line, isSection, section, subsection, name, value, path: path2 }; + }); + } + static from(text2) { + return new _GitConfig(text2); + } + async get(path2, getall = false) { + const normalizedPath = normalizePath$1(path2).path; + const allValues = this.parsedConfig.filter((config) => config.path === normalizedPath).map(({ section, name, value }) => { + const fn = schema[section] && schema[section][name]; + return fn ? fn(value) : value; + }); + return getall ? allValues : allValues.pop(); + } + async getall(path2) { + return this.get(path2, true); + } + async getSubsections(section) { + return this.parsedConfig.filter((config) => config.section === section && config.isSection).map((config) => config.subsection); + } + async deleteSection(section, subsection) { + this.parsedConfig = this.parsedConfig.filter( + (config) => !(config.section === section && config.subsection === subsection) + ); + } + async append(path2, value) { + return this.set(path2, value, true); + } + async set(path2, value, append3 = false) { + const { + section, + subsection, + name, + path: normalizedPath, + sectionPath + } = normalizePath$1(path2); + const configIndex = findLastIndex( + this.parsedConfig, + (config) => config.path === normalizedPath + ); + if (value == null) { + if (configIndex !== -1) { + this.parsedConfig.splice(configIndex, 1); + } + } else { + if (configIndex !== -1) { + const config = this.parsedConfig[configIndex]; + const modifiedConfig = Object.assign({}, config, { + name, + value, + modified: true + }); + if (append3) { + this.parsedConfig.splice(configIndex + 1, 0, modifiedConfig); + } else { + this.parsedConfig[configIndex] = modifiedConfig; + } + } else { + const sectionIndex = this.parsedConfig.findIndex( + (config) => config.path === sectionPath + ); + const newConfig = { + section, + subsection, + name, + value, + modified: true, + path: normalizedPath + }; + if (SECTION_REGEX.test(section) && VARIABLE_NAME_REGEX.test(name)) { + if (sectionIndex >= 0) { + this.parsedConfig.splice(sectionIndex + 1, 0, newConfig); + } else { + const newSection = { + section, + subsection, + modified: true, + path: sectionPath + }; + this.parsedConfig.push(newSection, newConfig); + } + } + } + } + } + toString() { + return this.parsedConfig.map(({ line, section, subsection, name, value, modified: modified2 = false }) => { + if (!modified2) { + return line; + } + if (name != null && value != null) { + if (typeof value === "string" && /[#;]/.test(value)) { + return ` ${name} = "${value}"`; + } + return ` ${name} = ${value}`; + } + if (subsection != null) { + return `[${section} "${subsection}"]`; + } + return `[${section}]`; + }).join("\n"); + } +}; +var GitConfigManager = class { + static async get({ fs, gitdir }) { + const text2 = await fs.read(`${gitdir}/config`, { encoding: "utf8" }); + return GitConfig.from(text2); + } + static async save({ fs, gitdir, config }) { + await fs.write(`${gitdir}/config`, config.toString(), { + encoding: "utf8" + }); + } +}; +var refpaths = (ref) => [ + `${ref}`, + `refs/${ref}`, + `refs/tags/${ref}`, + `refs/heads/${ref}`, + `refs/remotes/${ref}`, + `refs/remotes/${ref}/HEAD` +]; +var GIT_FILES = ["config", "description", "index", "shallow", "commondir"]; +var GitRefManager = class _GitRefManager { + static async updateRemoteRefs({ + fs, + gitdir, + remote, + refs, + symrefs, + tags, + refspecs = void 0, + prune = false, + pruneTags = false + }) { + for (const value of refs.values()) { + if (!value.match(/[0-9a-f]{40}/)) { + throw new InvalidOidError(value); + } + } + const config = await GitConfigManager.get({ fs, gitdir }); + if (!refspecs) { + refspecs = await config.getall(`remote.${remote}.fetch`); + if (refspecs.length === 0) { + throw new NoRefspecError(remote); + } + refspecs.unshift(`+HEAD:refs/remotes/${remote}/HEAD`); + } + const refspec = GitRefSpecSet.from(refspecs); + const actualRefsToWrite = /* @__PURE__ */ new Map(); + if (pruneTags) { + const tags2 = await _GitRefManager.listRefs({ + fs, + gitdir, + filepath: "refs/tags" + }); + await _GitRefManager.deleteRefs({ + fs, + gitdir, + refs: tags2.map((tag2) => `refs/tags/${tag2}`) + }); + } + if (tags) { + for (const serverRef of refs.keys()) { + if (serverRef.startsWith("refs/tags") && !serverRef.endsWith("^{}")) { + if (!await _GitRefManager.exists({ fs, gitdir, ref: serverRef })) { + const oid = refs.get(serverRef); + actualRefsToWrite.set(serverRef, oid); + } + } + } + } + const refTranslations = refspec.translate([...refs.keys()]); + for (const [serverRef, translatedRef] of refTranslations) { + const value = refs.get(serverRef); + actualRefsToWrite.set(translatedRef, value); + } + const symrefTranslations = refspec.translate([...symrefs.keys()]); + for (const [serverRef, translatedRef] of symrefTranslations) { + const value = symrefs.get(serverRef); + const symtarget = refspec.translateOne(value); + if (symtarget) { + actualRefsToWrite.set(translatedRef, `ref: ${symtarget}`); + } + } + const pruned = []; + if (prune) { + for (const filepath of refspec.localNamespaces()) { + const refs2 = (await _GitRefManager.listRefs({ + fs, + gitdir, + filepath + })).map((file) => `${filepath}/${file}`); + for (const ref of refs2) { + if (!actualRefsToWrite.has(ref)) { + pruned.push(ref); + } + } + } + if (pruned.length > 0) { + await _GitRefManager.deleteRefs({ fs, gitdir, refs: pruned }); + } + } + for (const [key2, value] of actualRefsToWrite) { + await fs.write(join(gitdir, key2), `${value.trim()} +`, "utf8"); + } + return { pruned }; + } + // TODO: make this less crude? + static async writeRef({ fs, gitdir, ref, value }) { + if (!value.match(/[0-9a-f]{40}/)) { + throw new InvalidOidError(value); + } + await fs.write(join(gitdir, ref), `${value.trim()} +`, "utf8"); + } + static async writeSymbolicRef({ fs, gitdir, ref, value }) { + await fs.write(join(gitdir, ref), `ref: ${value.trim()} +`, "utf8"); + } + static async deleteRef({ fs, gitdir, ref }) { + return _GitRefManager.deleteRefs({ fs, gitdir, refs: [ref] }); + } + static async deleteRefs({ fs, gitdir, refs }) { + await Promise.all(refs.map((ref) => fs.rm(join(gitdir, ref)))); + let text2 = await fs.read(`${gitdir}/packed-refs`, { encoding: "utf8" }); + const packed = GitPackedRefs.from(text2); + const beforeSize = packed.refs.size; + for (const ref of refs) { + if (packed.refs.has(ref)) { + packed.delete(ref); + } + } + if (packed.refs.size < beforeSize) { + text2 = packed.toString(); + await fs.write(`${gitdir}/packed-refs`, text2, { encoding: "utf8" }); + } + } + /** + * @param {object} args + * @param {import('../models/FileSystem.js').FileSystem} args.fs + * @param {string} args.gitdir + * @param {string} args.ref + * @param {number} [args.depth] + * @returns {Promise} + */ + static async resolve({ fs, gitdir, ref, depth = void 0 }) { + if (depth !== void 0) { + depth--; + if (depth === -1) { + return ref; + } + } + let sha; + if (ref.startsWith("ref: ")) { + ref = ref.slice("ref: ".length); + return _GitRefManager.resolve({ fs, gitdir, ref, depth }); + } + if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { + return ref; + } + const packedMap = await _GitRefManager.packedRefs({ fs, gitdir }); + const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p)); + for (const ref2 of allpaths) { + sha = await fs.read(`${gitdir}/${ref2}`, { encoding: "utf8" }) || packedMap.get(ref2); + if (sha) { + return _GitRefManager.resolve({ fs, gitdir, ref: sha.trim(), depth }); + } + } + throw new NotFoundError(ref); + } + static async exists({ fs, gitdir, ref }) { + try { + await _GitRefManager.expand({ fs, gitdir, ref }); + return true; + } catch (err) { + return false; + } + } + static async expand({ fs, gitdir, ref }) { + if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { + return ref; + } + const packedMap = await _GitRefManager.packedRefs({ fs, gitdir }); + const allpaths = refpaths(ref); + for (const ref2 of allpaths) { + if (await fs.exists(`${gitdir}/${ref2}`)) + return ref2; + if (packedMap.has(ref2)) + return ref2; + } + throw new NotFoundError(ref); + } + static async expandAgainstMap({ ref, map }) { + const allpaths = refpaths(ref); + for (const ref2 of allpaths) { + if (await map.has(ref2)) + return ref2; + } + throw new NotFoundError(ref); + } + static resolveAgainstMap({ ref, fullref = ref, depth = void 0, map }) { + if (depth !== void 0) { + depth--; + if (depth === -1) { + return { fullref, oid: ref }; + } + } + if (ref.startsWith("ref: ")) { + ref = ref.slice("ref: ".length); + return _GitRefManager.resolveAgainstMap({ ref, fullref, depth, map }); + } + if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { + return { fullref, oid: ref }; + } + const allpaths = refpaths(ref); + for (const ref2 of allpaths) { + const sha = map.get(ref2); + if (sha) { + return _GitRefManager.resolveAgainstMap({ + ref: sha.trim(), + fullref: ref2, + depth, + map + }); + } + } + throw new NotFoundError(ref); + } + static async packedRefs({ fs, gitdir }) { + const text2 = await fs.read(`${gitdir}/packed-refs`, { encoding: "utf8" }); + const packed = GitPackedRefs.from(text2); + return packed.refs; + } + // List all the refs that match the `filepath` prefix + static async listRefs({ fs, gitdir, filepath }) { + const packedMap = _GitRefManager.packedRefs({ fs, gitdir }); + let files = null; + try { + files = await fs.readdirDeep(`${gitdir}/${filepath}`); + files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, "")); + } catch (err) { + files = []; + } + for (let key2 of (await packedMap).keys()) { + if (key2.startsWith(filepath)) { + key2 = key2.replace(filepath + "/", ""); + if (!files.includes(key2)) { + files.push(key2); + } + } + } + files.sort(compareRefNames); + return files; + } + static async listBranches({ fs, gitdir, remote }) { + if (remote) { + return _GitRefManager.listRefs({ + fs, + gitdir, + filepath: `refs/remotes/${remote}` + }); + } else { + return _GitRefManager.listRefs({ fs, gitdir, filepath: `refs/heads` }); + } + } + static async listTags({ fs, gitdir }) { + const tags = await _GitRefManager.listRefs({ + fs, + gitdir, + filepath: `refs/tags` + }); + return tags.filter((x) => !x.endsWith("^{}")); + } +}; +function compareTreeEntryPath(a, b) { + return compareStrings(appendSlashIfDir(a), appendSlashIfDir(b)); +} +function appendSlashIfDir(entry) { + return entry.mode === "040000" ? entry.path + "/" : entry.path; +} +function mode2type$1(mode) { + switch (mode) { + case "040000": + return "tree"; + case "100644": + return "blob"; + case "100755": + return "blob"; + case "120000": + return "blob"; + case "160000": + return "commit"; + } + throw new InternalError(`Unexpected GitTree entry mode: ${mode}`); +} +function parseBuffer(buffer2) { + const _entries = []; + let cursor = 0; + while (cursor < buffer2.length) { + const space2 = buffer2.indexOf(32, cursor); + if (space2 === -1) { + throw new InternalError( + `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.` + ); + } + const nullchar = buffer2.indexOf(0, cursor); + if (nullchar === -1) { + throw new InternalError( + `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.` + ); + } + let mode = buffer2.slice(cursor, space2).toString("utf8"); + if (mode === "40000") + mode = "040000"; + const type = mode2type$1(mode); + const path2 = buffer2.slice(space2 + 1, nullchar).toString("utf8"); + if (path2.includes("\\") || path2.includes("/")) { + throw new UnsafeFilepathError(path2); + } + const oid = buffer2.slice(nullchar + 1, nullchar + 21).toString("hex"); + cursor = nullchar + 21; + _entries.push({ mode, path: path2, oid, type }); + } + return _entries; +} +function limitModeToAllowed(mode) { + if (typeof mode === "number") { + mode = mode.toString(8); + } + if (mode.match(/^0?4.*/)) + return "040000"; + if (mode.match(/^1006.*/)) + return "100644"; + if (mode.match(/^1007.*/)) + return "100755"; + if (mode.match(/^120.*/)) + return "120000"; + if (mode.match(/^160.*/)) + return "160000"; + throw new InternalError(`Could not understand file mode: ${mode}`); +} +function nudgeIntoShape(entry) { + if (!entry.oid && entry.sha) { + entry.oid = entry.sha; + } + entry.mode = limitModeToAllowed(entry.mode); + if (!entry.type) { + entry.type = mode2type$1(entry.mode); + } + return entry; +} +var GitTree = class _GitTree { + constructor(entries) { + if (Buffer.isBuffer(entries)) { + this._entries = parseBuffer(entries); + } else if (Array.isArray(entries)) { + this._entries = entries.map(nudgeIntoShape); + } else { + throw new InternalError("invalid type passed to GitTree constructor"); + } + this._entries.sort(comparePath); + } + static from(tree) { + return new _GitTree(tree); + } + render() { + return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid} ${entry.path}`).join("\n"); + } + toObject() { + const entries = [...this._entries]; + entries.sort(compareTreeEntryPath); + return Buffer.concat( + entries.map((entry) => { + const mode = Buffer.from(entry.mode.replace(/^0/, "")); + const space2 = Buffer.from(" "); + const path2 = Buffer.from(entry.path, "utf8"); + const nullchar = Buffer.from([0]); + const oid = Buffer.from(entry.oid, "hex"); + return Buffer.concat([mode, space2, path2, nullchar, oid]); + }) + ); + } + /** + * @returns {TreeEntry[]} + */ + entries() { + return this._entries; + } + *[Symbol.iterator]() { + for (const entry of this._entries) { + yield entry; + } + } +}; +var GitObject = class { + static wrap({ type, object }) { + return Buffer.concat([ + Buffer.from(`${type} ${object.byteLength.toString()}\0`), + Buffer.from(object) + ]); + } + static unwrap(buffer2) { + const s = buffer2.indexOf(32); + const i = buffer2.indexOf(0); + const type = buffer2.slice(0, s).toString("utf8"); + const length = buffer2.slice(s + 1, i).toString("utf8"); + const actualLength = buffer2.length - (i + 1); + if (parseInt(length) !== actualLength) { + throw new InternalError( + `Length mismatch: expected ${length} bytes but got ${actualLength} instead.` + ); + } + return { + type, + object: Buffer.from(buffer2.slice(i + 1)) + }; + } +}; +async function readObjectLoose({ fs, gitdir, oid }) { + const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`; + const file = await fs.read(`${gitdir}/${source}`); + if (!file) { + return null; + } + return { object: file, format: "deflated", source }; +} +function applyDelta(delta, source) { + const reader = new BufferCursor(delta); + const sourceSize = readVarIntLE(reader); + if (sourceSize !== source.byteLength) { + throw new InternalError( + `applyDelta expected source buffer to be ${sourceSize} bytes but the provided buffer was ${source.length} bytes` + ); + } + const targetSize = readVarIntLE(reader); + let target; + const firstOp = readOp(reader, source); + if (firstOp.byteLength === targetSize) { + target = firstOp; + } else { + target = Buffer.alloc(targetSize); + const writer = new BufferCursor(target); + writer.copy(firstOp); + while (!reader.eof()) { + writer.copy(readOp(reader, source)); + } + const tell = writer.tell(); + if (targetSize !== tell) { + throw new InternalError( + `applyDelta expected target buffer to be ${targetSize} bytes but the resulting buffer was ${tell} bytes` + ); + } + } + return target; +} +function readVarIntLE(reader) { + let result = 0; + let shift = 0; + let byte = null; + do { + byte = reader.readUInt8(); + result |= (byte & 127) << shift; + shift += 7; + } while (byte & 128); + return result; +} +function readCompactLE(reader, flags, size) { + let result = 0; + let shift = 0; + while (size--) { + if (flags & 1) { + result |= reader.readUInt8() << shift; + } + flags >>= 1; + shift += 8; + } + return result; +} +function readOp(reader, source) { + const byte = reader.readUInt8(); + const COPY = 128; + const OFFS = 15; + const SIZE = 112; + if (byte & COPY) { + const offset = readCompactLE(reader, byte & OFFS, 4); + let size = readCompactLE(reader, (byte & SIZE) >> 4, 3); + if (size === 0) + size = 65536; + return source.slice(offset, offset + size); + } else { + return reader.slice(byte); + } +} +function fromValue(value) { + let queue = [value]; + return { + next() { + return Promise.resolve({ done: queue.length === 0, value: queue.pop() }); + }, + return() { + queue = []; + return {}; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +function getIterator(iterable) { + if (iterable[Symbol.asyncIterator]) { + return iterable[Symbol.asyncIterator](); + } + if (iterable[Symbol.iterator]) { + return iterable[Symbol.iterator](); + } + if (iterable.next) { + return iterable; + } + return fromValue(iterable); +} +var StreamReader = class { + constructor(stream) { + this.stream = getIterator(stream); + this.buffer = null; + this.cursor = 0; + this.undoCursor = 0; + this.started = false; + this._ended = false; + this._discardedBytes = 0; + } + eof() { + return this._ended && this.cursor === this.buffer.length; + } + tell() { + return this._discardedBytes + this.cursor; + } + async byte() { + if (this.eof()) + return; + if (!this.started) + await this._init(); + if (this.cursor === this.buffer.length) { + await this._loadnext(); + if (this._ended) + return; + } + this._moveCursor(1); + return this.buffer[this.undoCursor]; + } + async chunk() { + if (this.eof()) + return; + if (!this.started) + await this._init(); + if (this.cursor === this.buffer.length) { + await this._loadnext(); + if (this._ended) + return; + } + this._moveCursor(this.buffer.length); + return this.buffer.slice(this.undoCursor, this.cursor); + } + async read(n) { + if (this.eof()) + return; + if (!this.started) + await this._init(); + if (this.cursor + n > this.buffer.length) { + this._trim(); + await this._accumulate(n); + } + this._moveCursor(n); + return this.buffer.slice(this.undoCursor, this.cursor); + } + async skip(n) { + if (this.eof()) + return; + if (!this.started) + await this._init(); + if (this.cursor + n > this.buffer.length) { + this._trim(); + await this._accumulate(n); + } + this._moveCursor(n); + } + async undo() { + this.cursor = this.undoCursor; + } + async _next() { + this.started = true; + let { done, value } = await this.stream.next(); + if (done) { + this._ended = true; + if (!value) + return Buffer.alloc(0); + } + if (value) { + value = Buffer.from(value); + } + return value; + } + _trim() { + this.buffer = this.buffer.slice(this.undoCursor); + this.cursor -= this.undoCursor; + this._discardedBytes += this.undoCursor; + this.undoCursor = 0; + } + _moveCursor(n) { + this.undoCursor = this.cursor; + this.cursor += n; + if (this.cursor > this.buffer.length) { + this.cursor = this.buffer.length; + } + } + async _accumulate(n) { + if (this._ended) + return; + const buffers = [this.buffer]; + while (this.cursor + n > lengthBuffers(buffers)) { + const nextbuffer = await this._next(); + if (this._ended) + break; + buffers.push(nextbuffer); + } + this.buffer = Buffer.concat(buffers); + } + async _loadnext() { + this._discardedBytes += this.buffer.length; + this.undoCursor = 0; + this.cursor = 0; + this.buffer = await this._next(); + } + async _init() { + this.buffer = await this._next(); + } +}; +function lengthBuffers(buffers) { + return buffers.reduce((acc, buffer2) => acc + buffer2.length, 0); +} +async function listpack(stream, onData) { + const reader = new StreamReader(stream); + let PACK = await reader.read(4); + PACK = PACK.toString("utf8"); + if (PACK !== "PACK") { + throw new InternalError(`Invalid PACK header '${PACK}'`); + } + let version2 = await reader.read(4); + version2 = version2.readUInt32BE(0); + if (version2 !== 2) { + throw new InternalError(`Invalid packfile version: ${version2}`); + } + let numObjects = await reader.read(4); + numObjects = numObjects.readUInt32BE(0); + if (numObjects < 1) + return; + while (!reader.eof() && numObjects--) { + const offset = reader.tell(); + const { type, length, ofs, reference } = await parseHeader(reader); + const inflator = new import_pako.default.Inflate(); + while (!inflator.result) { + const chunk = await reader.chunk(); + if (!chunk) + break; + inflator.push(chunk, false); + if (inflator.err) { + throw new InternalError(`Pako error: ${inflator.msg}`); + } + if (inflator.result) { + if (inflator.result.length !== length) { + throw new InternalError( + `Inflated object size is different from that stated in packfile.` + ); + } + await reader.undo(); + await reader.read(chunk.length - inflator.strm.avail_in); + const end = reader.tell(); + await onData({ + data: inflator.result, + type, + num: numObjects, + offset, + end, + reference, + ofs + }); + } + } + } +} +async function parseHeader(reader) { + let byte = await reader.byte(); + const type = byte >> 4 & 7; + let length = byte & 15; + if (byte & 128) { + let shift = 4; + do { + byte = await reader.byte(); + length |= (byte & 127) << shift; + shift += 7; + } while (byte & 128); + } + let ofs; + let reference; + if (type === 6) { + let shift = 0; + ofs = 0; + const bytes = []; + do { + byte = await reader.byte(); + ofs |= (byte & 127) << shift; + shift += 7; + bytes.push(byte); + } while (byte & 128); + reference = Buffer.from(bytes); + } + if (type === 7) { + const buf = await reader.read(20); + reference = buf; + } + return { type, length, ofs, reference }; +} +var supportsDecompressionStream = false; +async function inflate(buffer2) { + if (supportsDecompressionStream === null) { + supportsDecompressionStream = testDecompressionStream(); + } + return supportsDecompressionStream ? browserInflate(buffer2) : import_pako.default.inflate(buffer2); +} +async function browserInflate(buffer2) { + const ds = new DecompressionStream("deflate"); + const d = new Blob([buffer2]).stream().pipeThrough(ds); + return new Uint8Array(await new Response(d).arrayBuffer()); +} +function testDecompressionStream() { + try { + const ds = new DecompressionStream("deflate"); + if (ds) + return true; + } catch (_) { + } + return false; +} +function decodeVarInt(reader) { + const bytes = []; + let byte = 0; + let multibyte = 0; + do { + byte = reader.readUInt8(); + const lastSeven = byte & 127; + bytes.push(lastSeven); + multibyte = byte & 128; + } while (multibyte); + return bytes.reduce((a, b) => a + 1 << 7 | b, -1); +} +function otherVarIntDecode(reader, startWith) { + let result = startWith; + let shift = 4; + let byte = null; + do { + byte = reader.readUInt8(); + result |= (byte & 127) << shift; + shift += 7; + } while (byte & 128); + return result; +} +var GitPackIndex = class _GitPackIndex { + constructor(stuff) { + Object.assign(this, stuff); + this.offsetCache = {}; + } + static async fromIdx({ idx, getExternalRefDelta }) { + const reader = new BufferCursor(idx); + const magic = reader.slice(4).toString("hex"); + if (magic !== "ff744f63") { + return; + } + const version2 = reader.readUInt32BE(); + if (version2 !== 2) { + throw new InternalError( + `Unable to read version ${version2} packfile IDX. (Only version 2 supported)` + ); + } + if (idx.byteLength > 2048 * 1024 * 1024) { + throw new InternalError( + `To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.` + ); + } + reader.seek(reader.tell() + 4 * 255); + const size = reader.readUInt32BE(); + const hashes = []; + for (let i = 0; i < size; i++) { + const hash2 = reader.slice(20).toString("hex"); + hashes[i] = hash2; + } + reader.seek(reader.tell() + 4 * size); + const offsets = /* @__PURE__ */ new Map(); + for (let i = 0; i < size; i++) { + offsets.set(hashes[i], reader.readUInt32BE()); + } + const packfileSha = reader.slice(20).toString("hex"); + return new _GitPackIndex({ + hashes, + crcs: {}, + offsets, + packfileSha, + getExternalRefDelta + }); + } + static async fromPack({ pack, getExternalRefDelta, onProgress }) { + const listpackTypes = { + 1: "commit", + 2: "tree", + 3: "blob", + 4: "tag", + 6: "ofs-delta", + 7: "ref-delta" + }; + const offsetToObject = {}; + const packfileSha = pack.slice(-20).toString("hex"); + const hashes = []; + const crcs = {}; + const offsets = /* @__PURE__ */ new Map(); + let totalObjectCount = null; + let lastPercent = null; + await listpack([pack], async ({ data, type, reference, offset, num: num2 }) => { + if (totalObjectCount === null) + totalObjectCount = num2; + const percent = Math.floor( + (totalObjectCount - num2) * 100 / totalObjectCount + ); + if (percent !== lastPercent) { + if (onProgress) { + await onProgress({ + phase: "Receiving objects", + loaded: totalObjectCount - num2, + total: totalObjectCount + }); + } + } + lastPercent = percent; + type = listpackTypes[type]; + if (["commit", "tree", "blob", "tag"].includes(type)) { + offsetToObject[offset] = { + type, + offset + }; + } else if (type === "ofs-delta") { + offsetToObject[offset] = { + type, + offset + }; + } else if (type === "ref-delta") { + offsetToObject[offset] = { + type, + offset + }; + } + }); + const offsetArray = Object.keys(offsetToObject).map(Number); + for (const [i, start] of offsetArray.entries()) { + const end = i + 1 === offsetArray.length ? pack.byteLength - 20 : offsetArray[i + 1]; + const o = offsetToObject[start]; + const crc = import_crc_32.default.buf(pack.slice(start, end)) >>> 0; + o.end = end; + o.crc = crc; + } + const p = new _GitPackIndex({ + pack: Promise.resolve(pack), + packfileSha, + crcs, + hashes, + offsets, + getExternalRefDelta + }); + lastPercent = null; + let count = 0; + const objectsByDepth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (let offset in offsetToObject) { + offset = Number(offset); + const percent = Math.floor(count * 100 / totalObjectCount); + if (percent !== lastPercent) { + if (onProgress) { + await onProgress({ + phase: "Resolving deltas", + loaded: count, + total: totalObjectCount + }); + } + } + count++; + lastPercent = percent; + const o = offsetToObject[offset]; + if (o.oid) + continue; + try { + p.readDepth = 0; + p.externalReadDepth = 0; + const { type, object } = await p.readSlice({ start: offset }); + objectsByDepth[p.readDepth] += 1; + const oid = await shasum(GitObject.wrap({ type, object })); + o.oid = oid; + hashes.push(oid); + offsets.set(oid, offset); + crcs[oid] = o.crc; + } catch (err) { + continue; + } + } + hashes.sort(); + return p; + } + async toBuffer() { + const buffers = []; + const write = (str, encoding) => { + buffers.push(Buffer.from(str, encoding)); + }; + write("ff744f63", "hex"); + write("00000002", "hex"); + const fanoutBuffer = new BufferCursor(Buffer.alloc(256 * 4)); + for (let i = 0; i < 256; i++) { + let count = 0; + for (const hash2 of this.hashes) { + if (parseInt(hash2.slice(0, 2), 16) <= i) + count++; + } + fanoutBuffer.writeUInt32BE(count); + } + buffers.push(fanoutBuffer.buffer); + for (const hash2 of this.hashes) { + write(hash2, "hex"); + } + const crcsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4)); + for (const hash2 of this.hashes) { + crcsBuffer.writeUInt32BE(this.crcs[hash2]); + } + buffers.push(crcsBuffer.buffer); + const offsetsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4)); + for (const hash2 of this.hashes) { + offsetsBuffer.writeUInt32BE(this.offsets.get(hash2)); + } + buffers.push(offsetsBuffer.buffer); + write(this.packfileSha, "hex"); + const totalBuffer = Buffer.concat(buffers); + const sha = await shasum(totalBuffer); + const shaBuffer = Buffer.alloc(20); + shaBuffer.write(sha, "hex"); + return Buffer.concat([totalBuffer, shaBuffer]); + } + async load({ pack }) { + this.pack = pack; + } + async unload() { + this.pack = null; + } + async read({ oid }) { + if (!this.offsets.get(oid)) { + if (this.getExternalRefDelta) { + this.externalReadDepth++; + return this.getExternalRefDelta(oid); + } else { + throw new InternalError(`Could not read object ${oid} from packfile`); + } + } + const start = this.offsets.get(oid); + return this.readSlice({ start }); + } + async readSlice({ start }) { + if (this.offsetCache[start]) { + return Object.assign({}, this.offsetCache[start]); + } + this.readDepth++; + const types2 = { + 16: "commit", + 32: "tree", + 48: "blob", + 64: "tag", + 96: "ofs_delta", + 112: "ref_delta" + }; + if (!this.pack) { + throw new InternalError( + "Tried to read from a GitPackIndex with no packfile loaded into memory" + ); + } + const raw = (await this.pack).slice(start); + const reader = new BufferCursor(raw); + const byte = reader.readUInt8(); + const btype = byte & 112; + let type = types2[btype]; + if (type === void 0) { + throw new InternalError("Unrecognized type: 0b" + btype.toString(2)); + } + const lastFour = byte & 15; + let length = lastFour; + const multibyte = byte & 128; + if (multibyte) { + length = otherVarIntDecode(reader, lastFour); + } + let base = null; + let object = null; + if (type === "ofs_delta") { + const offset = decodeVarInt(reader); + const baseOffset = start - offset; + ({ object: base, type } = await this.readSlice({ start: baseOffset })); + } + if (type === "ref_delta") { + const oid = reader.slice(20).toString("hex"); + ({ object: base, type } = await this.read({ oid })); + } + const buffer2 = raw.slice(reader.tell()); + object = Buffer.from(await inflate(buffer2)); + if (object.byteLength !== length) { + throw new InternalError( + `Packfile told us object would have length ${length} but it had length ${object.byteLength}` + ); + } + if (base) { + object = Buffer.from(applyDelta(object, base)); + } + if (this.readDepth > 3) { + this.offsetCache[start] = { type, object }; + } + return { type, format: "content", object }; + } +}; +var PackfileCache = Symbol("PackfileCache"); +async function loadPackIndex({ + fs, + filename, + getExternalRefDelta, + emitter, + emitterPrefix +}) { + const idx = await fs.read(filename); + return GitPackIndex.fromIdx({ idx, getExternalRefDelta }); +} +function readPackIndex({ + fs, + cache, + filename, + getExternalRefDelta, + emitter, + emitterPrefix +}) { + if (!cache[PackfileCache]) + cache[PackfileCache] = /* @__PURE__ */ new Map(); + let p = cache[PackfileCache].get(filename); + if (!p) { + p = loadPackIndex({ + fs, + filename, + getExternalRefDelta, + emitter, + emitterPrefix + }); + cache[PackfileCache].set(filename, p); + } + return p; +} +async function readObjectPacked({ + fs, + cache, + gitdir, + oid, + format = "content", + getExternalRefDelta +}) { + let list = await fs.readdir(join(gitdir, "objects/pack")); + list = list.filter((x) => x.endsWith(".idx")); + for (const filename of list) { + const indexFile = `${gitdir}/objects/pack/${filename}`; + const p = await readPackIndex({ + fs, + cache, + filename: indexFile, + getExternalRefDelta + }); + if (p.error) + throw new InternalError(p.error); + if (p.offsets.has(oid)) { + if (!p.pack) { + const packFile = indexFile.replace(/idx$/, "pack"); + p.pack = fs.read(packFile); + } + const result = await p.read({ oid, getExternalRefDelta }); + result.format = "content"; + result.source = `objects/pack/${filename.replace(/idx$/, "pack")}`; + return result; + } + } + return null; +} +async function _readObject({ + fs, + cache, + gitdir, + oid, + format = "content" +}) { + const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 }); + let result; + if (oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904") { + result = { format: "wrapped", object: Buffer.from(`tree 0\0`) }; + } + if (!result) { + result = await readObjectLoose({ fs, gitdir, oid }); + } + if (!result) { + result = await readObjectPacked({ + fs, + cache, + gitdir, + oid, + getExternalRefDelta + }); + } + if (!result) { + throw new NotFoundError(oid); + } + if (format === "deflated") { + return result; + } + if (result.format === "deflated") { + result.object = Buffer.from(await inflate(result.object)); + result.format = "wrapped"; + } + if (result.format === "wrapped") { + if (format === "wrapped" && result.format === "wrapped") { + return result; + } + const sha = await shasum(result.object); + if (sha !== oid) { + throw new InternalError( + `SHA check failed! Expected ${oid}, computed ${sha}` + ); + } + const { object, type } = GitObject.unwrap(result.object); + result.type = type; + result.object = object; + result.format = "content"; + } + if (result.format === "content") { + if (format === "content") + return result; + return; + } + throw new InternalError(`invalid format "${result.format}"`); +} +var AlreadyExistsError = class _AlreadyExistsError extends BaseError { + /** + * @param {'note'|'remote'|'tag'|'branch'} noun + * @param {string} where + * @param {boolean} canForce + */ + constructor(noun, where, canForce = true) { + super( + `Failed to create ${noun} at ${where} because it already exists.${canForce ? ` (Hint: use 'force: true' parameter to overwrite existing ${noun}.)` : ""}` + ); + this.code = this.name = _AlreadyExistsError.code; + this.data = { noun, where, canForce }; + } +}; +AlreadyExistsError.code = "AlreadyExistsError"; +var AmbiguousError = class _AmbiguousError extends BaseError { + /** + * @param {'oids'|'refs'} nouns + * @param {string} short + * @param {string[]} matches + */ + constructor(nouns, short, matches) { + super( + `Found multiple ${nouns} matching "${short}" (${matches.join( + ", " + )}). Use a longer abbreviation length to disambiguate them.` + ); + this.code = this.name = _AmbiguousError.code; + this.data = { nouns, short, matches }; + } +}; +AmbiguousError.code = "AmbiguousError"; +var CheckoutConflictError = class _CheckoutConflictError extends BaseError { + /** + * @param {string[]} filepaths + */ + constructor(filepaths) { + super( + `Your local changes to the following files would be overwritten by checkout: ${filepaths.join( + ", " + )}` + ); + this.code = this.name = _CheckoutConflictError.code; + this.data = { filepaths }; + } +}; +CheckoutConflictError.code = "CheckoutConflictError"; +var CommitNotFetchedError = class _CommitNotFetchedError extends BaseError { + /** + * @param {string} ref + * @param {string} oid + */ + constructor(ref, oid) { + super( + `Failed to checkout "${ref}" because commit ${oid} is not available locally. Do a git fetch to make the branch available locally.` + ); + this.code = this.name = _CommitNotFetchedError.code; + this.data = { ref, oid }; + } +}; +CommitNotFetchedError.code = "CommitNotFetchedError"; +var EmptyServerResponseError = class _EmptyServerResponseError extends BaseError { + constructor() { + super(`Empty response from git server.`); + this.code = this.name = _EmptyServerResponseError.code; + this.data = {}; + } +}; +EmptyServerResponseError.code = "EmptyServerResponseError"; +var FastForwardError = class _FastForwardError extends BaseError { + constructor() { + super(`A simple fast-forward merge was not possible.`); + this.code = this.name = _FastForwardError.code; + this.data = {}; + } +}; +FastForwardError.code = "FastForwardError"; +var GitPushError = class _GitPushError extends BaseError { + /** + * @param {string} prettyDetails + * @param {PushResult} result + */ + constructor(prettyDetails, result) { + super(`One or more branches were not updated: ${prettyDetails}`); + this.code = this.name = _GitPushError.code; + this.data = { prettyDetails, result }; + } +}; +GitPushError.code = "GitPushError"; +var HttpError = class _HttpError extends BaseError { + /** + * @param {number} statusCode + * @param {string} statusMessage + * @param {string} response + */ + constructor(statusCode, statusMessage, response) { + super(`HTTP Error: ${statusCode} ${statusMessage}`); + this.code = this.name = _HttpError.code; + this.data = { statusCode, statusMessage, response }; + } +}; +HttpError.code = "HttpError"; +var InvalidFilepathError = class _InvalidFilepathError extends BaseError { + /** + * @param {'leading-slash'|'trailing-slash'|'directory'} [reason] + */ + constructor(reason) { + let message = "invalid filepath"; + if (reason === "leading-slash" || reason === "trailing-slash") { + message = `"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.`; + } else if (reason === "directory") { + message = `"filepath" should not be a directory.`; + } + super(message); + this.code = this.name = _InvalidFilepathError.code; + this.data = { reason }; + } +}; +InvalidFilepathError.code = "InvalidFilepathError"; +var InvalidRefNameError = class _InvalidRefNameError extends BaseError { + /** + * @param {string} ref + * @param {string} suggestion + * @param {boolean} canForce + */ + constructor(ref, suggestion) { + super( + `"${ref}" would be an invalid git reference. (Hint: a valid alternative would be "${suggestion}".)` + ); + this.code = this.name = _InvalidRefNameError.code; + this.data = { ref, suggestion }; + } +}; +InvalidRefNameError.code = "InvalidRefNameError"; +var MaxDepthError = class _MaxDepthError extends BaseError { + /** + * @param {number} depth + */ + constructor(depth) { + super(`Maximum search depth of ${depth} exceeded.`); + this.code = this.name = _MaxDepthError.code; + this.data = { depth }; + } +}; +MaxDepthError.code = "MaxDepthError"; +var MergeNotSupportedError = class _MergeNotSupportedError extends BaseError { + constructor() { + super(`Merges with conflicts are not supported yet.`); + this.code = this.name = _MergeNotSupportedError.code; + this.data = {}; + } +}; +MergeNotSupportedError.code = "MergeNotSupportedError"; +var MergeConflictError = class _MergeConflictError extends BaseError { + /** + * @param {Array} filepaths + * @param {Array} bothModified + * @param {Array} deleteByUs + * @param {Array} deleteByTheirs + */ + constructor(filepaths, bothModified, deleteByUs, deleteByTheirs) { + super( + `Automatic merge failed with one or more merge conflicts in the following files: ${filepaths.toString()}. Fix conflicts then commit the result.` + ); + this.code = this.name = _MergeConflictError.code; + this.data = { filepaths, bothModified, deleteByUs, deleteByTheirs }; + } +}; +MergeConflictError.code = "MergeConflictError"; +var MissingNameError = class _MissingNameError extends BaseError { + /** + * @param {'author'|'committer'|'tagger'} role + */ + constructor(role) { + super( + `No name was provided for ${role} in the argument or in the .git/config file.` + ); + this.code = this.name = _MissingNameError.code; + this.data = { role }; + } +}; +MissingNameError.code = "MissingNameError"; +var MissingParameterError = class _MissingParameterError extends BaseError { + /** + * @param {string} parameter + */ + constructor(parameter) { + super( + `The function requires a "${parameter}" parameter but none was provided.` + ); + this.code = this.name = _MissingParameterError.code; + this.data = { parameter }; + } +}; +MissingParameterError.code = "MissingParameterError"; +var MultipleGitError = class _MultipleGitError extends BaseError { + /** + * @param {Error[]} errors + * @param {string} message + */ + constructor(errors) { + super( + `There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more` + ); + this.code = this.name = _MultipleGitError.code; + this.data = { errors }; + this.errors = errors; + } +}; +MultipleGitError.code = "MultipleGitError"; +var ParseError = class _ParseError extends BaseError { + /** + * @param {string} expected + * @param {string} actual + */ + constructor(expected, actual) { + super(`Expected "${expected}" but received "${actual}".`); + this.code = this.name = _ParseError.code; + this.data = { expected, actual }; + } +}; +ParseError.code = "ParseError"; +var PushRejectedError = class _PushRejectedError extends BaseError { + /** + * @param {'not-fast-forward'|'tag-exists'} reason + */ + constructor(reason) { + let message = ""; + if (reason === "not-fast-forward") { + message = " because it was not a simple fast-forward"; + } else if (reason === "tag-exists") { + message = " because tag already exists"; + } + super(`Push rejected${message}. Use "force: true" to override.`); + this.code = this.name = _PushRejectedError.code; + this.data = { reason }; + } +}; +PushRejectedError.code = "PushRejectedError"; +var RemoteCapabilityError = class _RemoteCapabilityError extends BaseError { + /** + * @param {'shallow'|'deepen-since'|'deepen-not'|'deepen-relative'} capability + * @param {'depth'|'since'|'exclude'|'relative'} parameter + */ + constructor(capability, parameter) { + super( + `Remote does not support the "${capability}" so the "${parameter}" parameter cannot be used.` + ); + this.code = this.name = _RemoteCapabilityError.code; + this.data = { capability, parameter }; + } +}; +RemoteCapabilityError.code = "RemoteCapabilityError"; +var SmartHttpError = class _SmartHttpError extends BaseError { + /** + * @param {string} preview + * @param {string} response + */ + constructor(preview, response) { + super( + `Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${preview}` + ); + this.code = this.name = _SmartHttpError.code; + this.data = { preview, response }; + } +}; +SmartHttpError.code = "SmartHttpError"; +var UnknownTransportError = class _UnknownTransportError extends BaseError { + /** + * @param {string} url + * @param {string} transport + * @param {string} [suggestion] + */ + constructor(url, transport, suggestion) { + super( + `Git remote "${url}" uses an unrecognized transport protocol: "${transport}"` + ); + this.code = this.name = _UnknownTransportError.code; + this.data = { url, transport, suggestion }; + } +}; +UnknownTransportError.code = "UnknownTransportError"; +var UrlParseError = class _UrlParseError extends BaseError { + /** + * @param {string} url + */ + constructor(url) { + super(`Cannot parse remote URL: "${url}"`); + this.code = this.name = _UrlParseError.code; + this.data = { url }; + } +}; +UrlParseError.code = "UrlParseError"; +var UserCanceledError = class _UserCanceledError extends BaseError { + constructor() { + super(`The operation was canceled.`); + this.code = this.name = _UserCanceledError.code; + this.data = {}; + } +}; +UserCanceledError.code = "UserCanceledError"; +var IndexResetError = class _IndexResetError extends BaseError { + /** + * @param {Array} filepaths + */ + constructor(filepath) { + super( + `Could not merge index: Entry for '${filepath}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged chages.` + ); + this.code = this.name = _IndexResetError.code; + this.data = { filepath }; + } +}; +IndexResetError.code = "IndexResetError"; +var Errors = /* @__PURE__ */ Object.freeze({ + __proto__: null, + AlreadyExistsError, + AmbiguousError, + CheckoutConflictError, + CommitNotFetchedError, + EmptyServerResponseError, + FastForwardError, + GitPushError, + HttpError, + InternalError, + InvalidFilepathError, + InvalidOidError, + InvalidRefNameError, + MaxDepthError, + MergeNotSupportedError, + MergeConflictError, + MissingNameError, + MissingParameterError, + MultipleGitError, + NoRefspecError, + NotFoundError, + ObjectTypeError, + ParseError, + PushRejectedError, + RemoteCapabilityError, + SmartHttpError, + UnknownTransportError, + UnsafeFilepathError, + UrlParseError, + UserCanceledError, + UnmergedPathsError, + IndexResetError +}); +function formatAuthor({ name, email, timestamp, timezoneOffset }) { + timezoneOffset = formatTimezoneOffset(timezoneOffset); + return `${name} <${email}> ${timestamp} ${timezoneOffset}`; +} +function formatTimezoneOffset(minutes) { + const sign = simpleSign(negateExceptForZero(minutes)); + minutes = Math.abs(minutes); + const hours = Math.floor(minutes / 60); + minutes -= hours * 60; + let strHours = String(hours); + let strMinutes = String(minutes); + if (strHours.length < 2) + strHours = "0" + strHours; + if (strMinutes.length < 2) + strMinutes = "0" + strMinutes; + return (sign === -1 ? "-" : "+") + strHours + strMinutes; +} +function simpleSign(n) { + return Math.sign(n) || (Object.is(n, -0) ? -1 : 1); +} +function negateExceptForZero(n) { + return n === 0 ? n : -n; +} +function normalizeNewlines(str) { + str = str.replace(/\r/g, ""); + str = str.replace(/^\n+/, ""); + str = str.replace(/\n+$/, "") + "\n"; + return str; +} +function parseAuthor(author) { + const [, name, email, timestamp, offset] = author.match( + /^(.*) <(.*)> (.*) (.*)$/ + ); + return { + name, + email, + timestamp: Number(timestamp), + timezoneOffset: parseTimezoneOffset(offset) + }; +} +function parseTimezoneOffset(offset) { + let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/); + minutes = (sign === "+" ? 1 : -1) * (Number(hours) * 60 + Number(minutes)); + return negateExceptForZero$1(minutes); +} +function negateExceptForZero$1(n) { + return n === 0 ? n : -n; +} +var GitAnnotatedTag = class _GitAnnotatedTag { + constructor(tag2) { + if (typeof tag2 === "string") { + this._tag = tag2; + } else if (Buffer.isBuffer(tag2)) { + this._tag = tag2.toString("utf8"); + } else if (typeof tag2 === "object") { + this._tag = _GitAnnotatedTag.render(tag2); + } else { + throw new InternalError( + "invalid type passed to GitAnnotatedTag constructor" + ); + } + } + static from(tag2) { + return new _GitAnnotatedTag(tag2); + } + static render(obj) { + return `object ${obj.object} +type ${obj.type} +tag ${obj.tag} +tagger ${formatAuthor(obj.tagger)} + +${obj.message} +${obj.gpgsig ? obj.gpgsig : ""}`; + } + justHeaders() { + return this._tag.slice(0, this._tag.indexOf("\n\n")); + } + message() { + const tag2 = this.withoutSignature(); + return tag2.slice(tag2.indexOf("\n\n") + 2); + } + parse() { + return Object.assign(this.headers(), { + message: this.message(), + gpgsig: this.gpgsig() + }); + } + render() { + return this._tag; + } + headers() { + const headers = this.justHeaders().split("\n"); + const hs = []; + for (const h of headers) { + if (h[0] === " ") { + hs[hs.length - 1] += "\n" + h.slice(1); + } else { + hs.push(h); + } + } + const obj = {}; + for (const h of hs) { + const key2 = h.slice(0, h.indexOf(" ")); + const value = h.slice(h.indexOf(" ") + 1); + if (Array.isArray(obj[key2])) { + obj[key2].push(value); + } else { + obj[key2] = value; + } + } + if (obj.tagger) { + obj.tagger = parseAuthor(obj.tagger); + } + if (obj.committer) { + obj.committer = parseAuthor(obj.committer); + } + return obj; + } + withoutSignature() { + const tag2 = normalizeNewlines(this._tag); + if (tag2.indexOf("\n-----BEGIN PGP SIGNATURE-----") === -1) + return tag2; + return tag2.slice(0, tag2.lastIndexOf("\n-----BEGIN PGP SIGNATURE-----")); + } + gpgsig() { + if (this._tag.indexOf("\n-----BEGIN PGP SIGNATURE-----") === -1) + return; + const signature = this._tag.slice( + this._tag.indexOf("-----BEGIN PGP SIGNATURE-----"), + this._tag.indexOf("-----END PGP SIGNATURE-----") + "-----END PGP SIGNATURE-----".length + ); + return normalizeNewlines(signature); + } + payload() { + return this.withoutSignature() + "\n"; + } + toObject() { + return Buffer.from(this._tag, "utf8"); + } + static async sign(tag2, sign, secretKey) { + const payload = tag2.payload(); + let { signature } = await sign({ payload, secretKey }); + signature = normalizeNewlines(signature); + const signedTag = payload + signature; + return _GitAnnotatedTag.from(signedTag); + } +}; +function indent(str) { + return str.trim().split("\n").map((x) => " " + x).join("\n") + "\n"; +} +function outdent(str) { + return str.split("\n").map((x) => x.replace(/^ /, "")).join("\n"); +} +var GitCommit = class _GitCommit { + constructor(commit2) { + if (typeof commit2 === "string") { + this._commit = commit2; + } else if (Buffer.isBuffer(commit2)) { + this._commit = commit2.toString("utf8"); + } else if (typeof commit2 === "object") { + this._commit = _GitCommit.render(commit2); + } else { + throw new InternalError("invalid type passed to GitCommit constructor"); + } + } + static fromPayloadSignature({ payload, signature }) { + const headers = _GitCommit.justHeaders(payload); + const message = _GitCommit.justMessage(payload); + const commit2 = normalizeNewlines( + headers + "\ngpgsig" + indent(signature) + "\n" + message + ); + return new _GitCommit(commit2); + } + static from(commit2) { + return new _GitCommit(commit2); + } + toObject() { + return Buffer.from(this._commit, "utf8"); + } + // Todo: allow setting the headers and message + headers() { + return this.parseHeaders(); + } + // Todo: allow setting the headers and message + message() { + return _GitCommit.justMessage(this._commit); + } + parse() { + return Object.assign({ message: this.message() }, this.headers()); + } + static justMessage(commit2) { + return normalizeNewlines(commit2.slice(commit2.indexOf("\n\n") + 2)); + } + static justHeaders(commit2) { + return commit2.slice(0, commit2.indexOf("\n\n")); + } + parseHeaders() { + const headers = _GitCommit.justHeaders(this._commit).split("\n"); + const hs = []; + for (const h of headers) { + if (h[0] === " ") { + hs[hs.length - 1] += "\n" + h.slice(1); + } else { + hs.push(h); + } + } + const obj = { + parent: [] + }; + for (const h of hs) { + const key2 = h.slice(0, h.indexOf(" ")); + const value = h.slice(h.indexOf(" ") + 1); + if (Array.isArray(obj[key2])) { + obj[key2].push(value); + } else { + obj[key2] = value; + } + } + if (obj.author) { + obj.author = parseAuthor(obj.author); + } + if (obj.committer) { + obj.committer = parseAuthor(obj.committer); + } + return obj; + } + static renderHeaders(obj) { + let headers = ""; + if (obj.tree) { + headers += `tree ${obj.tree} +`; + } else { + headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 +`; + } + if (obj.parent) { + if (obj.parent.length === void 0) { + throw new InternalError(`commit 'parent' property should be an array`); + } + for (const p of obj.parent) { + headers += `parent ${p} +`; + } + } + const author = obj.author; + headers += `author ${formatAuthor(author)} +`; + const committer = obj.committer || obj.author; + headers += `committer ${formatAuthor(committer)} +`; + if (obj.gpgsig) { + headers += "gpgsig" + indent(obj.gpgsig); + } + return headers; + } + static render(obj) { + return _GitCommit.renderHeaders(obj) + "\n" + normalizeNewlines(obj.message); + } + render() { + return this._commit; + } + withoutSignature() { + const commit2 = normalizeNewlines(this._commit); + if (commit2.indexOf("\ngpgsig") === -1) + return commit2; + const headers = commit2.slice(0, commit2.indexOf("\ngpgsig")); + const message = commit2.slice( + commit2.indexOf("-----END PGP SIGNATURE-----\n") + "-----END PGP SIGNATURE-----\n".length + ); + return normalizeNewlines(headers + "\n" + message); + } + isolateSignature() { + const signature = this._commit.slice( + this._commit.indexOf("-----BEGIN PGP SIGNATURE-----"), + this._commit.indexOf("-----END PGP SIGNATURE-----") + "-----END PGP SIGNATURE-----".length + ); + return outdent(signature); + } + static async sign(commit2, sign, secretKey) { + const payload = commit2.withoutSignature(); + const message = _GitCommit.justMessage(commit2._commit); + let { signature } = await sign({ payload, secretKey }); + signature = normalizeNewlines(signature); + const headers = _GitCommit.justHeaders(commit2._commit); + const signedCommit = headers + "\ngpgsig" + indent(signature) + "\n" + message; + return _GitCommit.from(signedCommit); + } +}; +async function resolveTree({ fs, cache, gitdir, oid }) { + if (oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904") { + return { tree: GitTree.from([]), oid }; + } + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type === "tag") { + oid = GitAnnotatedTag.from(object).parse().object; + return resolveTree({ fs, cache, gitdir, oid }); + } + if (type === "commit") { + oid = GitCommit.from(object).parse().tree; + return resolveTree({ fs, cache, gitdir, oid }); + } + if (type !== "tree") { + throw new ObjectTypeError(oid, type, "tree"); + } + return { tree: GitTree.from(object), oid }; +} +var GitWalkerRepo = class { + constructor({ fs, gitdir, ref, cache }) { + this.fs = fs; + this.cache = cache; + this.gitdir = gitdir; + this.mapPromise = (async () => { + const map = /* @__PURE__ */ new Map(); + let oid; + try { + oid = await GitRefManager.resolve({ fs, gitdir, ref }); + } catch (e) { + if (e instanceof NotFoundError) { + oid = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; + } + } + const tree = await resolveTree({ fs, cache: this.cache, gitdir, oid }); + tree.type = "tree"; + tree.mode = "40000"; + map.set(".", tree); + return map; + })(); + const walker = this; + this.ConstructEntry = class TreeEntry { + constructor(fullpath) { + this._fullpath = fullpath; + this._type = false; + this._mode = false; + this._stat = false; + this._content = false; + this._oid = false; + } + async type() { + return walker.type(this); + } + async mode() { + return walker.mode(this); + } + async stat() { + return walker.stat(this); + } + async content() { + return walker.content(this); + } + async oid() { + return walker.oid(this); + } + }; + } + async readdir(entry) { + const filepath = entry._fullpath; + const { fs, cache, gitdir } = this; + const map = await this.mapPromise; + const obj = map.get(filepath); + if (!obj) + throw new Error(`No obj for ${filepath}`); + const oid = obj.oid; + if (!oid) + throw new Error(`No oid for obj ${JSON.stringify(obj)}`); + if (obj.type !== "tree") { + return null; + } + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type !== obj.type) { + throw new ObjectTypeError(oid, type, obj.type); + } + const tree = GitTree.from(object); + for (const entry2 of tree) { + map.set(join(filepath, entry2.path), entry2); + } + return tree.entries().map((entry2) => join(filepath, entry2.path)); + } + async type(entry) { + if (entry._type === false) { + const map = await this.mapPromise; + const { type } = map.get(entry._fullpath); + entry._type = type; + } + return entry._type; + } + async mode(entry) { + if (entry._mode === false) { + const map = await this.mapPromise; + const { mode } = map.get(entry._fullpath); + entry._mode = normalizeMode(parseInt(mode, 8)); + } + return entry._mode; + } + async stat(_entry) { + } + async content(entry) { + if (entry._content === false) { + const map = await this.mapPromise; + const { fs, cache, gitdir } = this; + const obj = map.get(entry._fullpath); + const oid = obj.oid; + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type !== "blob") { + entry._content = void 0; + } else { + entry._content = new Uint8Array(object); + } + } + return entry._content; + } + async oid(entry) { + if (entry._oid === false) { + const map = await this.mapPromise; + const obj = map.get(entry._fullpath); + entry._oid = obj.oid; + } + return entry._oid; + } +}; +function TREE({ ref = "HEAD" } = {}) { + const o = /* @__PURE__ */ Object.create(null); + Object.defineProperty(o, GitWalkSymbol, { + value: function({ fs, gitdir, cache }) { + return new GitWalkerRepo({ fs, gitdir, ref, cache }); + } + }); + Object.freeze(o); + return o; +} +var GitWalkerFs = class { + constructor({ fs, dir, gitdir, cache }) { + this.fs = fs; + this.cache = cache; + this.dir = dir; + this.gitdir = gitdir; + const walker = this; + this.ConstructEntry = class WorkdirEntry { + constructor(fullpath) { + this._fullpath = fullpath; + this._type = false; + this._mode = false; + this._stat = false; + this._content = false; + this._oid = false; + } + async type() { + return walker.type(this); + } + async mode() { + return walker.mode(this); + } + async stat() { + return walker.stat(this); + } + async content() { + return walker.content(this); + } + async oid() { + return walker.oid(this); + } + }; + } + async readdir(entry) { + const filepath = entry._fullpath; + const { fs, dir } = this; + const names = await fs.readdir(join(dir, filepath)); + if (names === null) + return null; + return names.map((name) => join(filepath, name)); + } + async type(entry) { + if (entry._type === false) { + await entry.stat(); + } + return entry._type; + } + async mode(entry) { + if (entry._mode === false) { + await entry.stat(); + } + return entry._mode; + } + async stat(entry) { + if (entry._stat === false) { + const { fs, dir } = this; + let stat = await fs.lstat(`${dir}/${entry._fullpath}`); + if (!stat) { + throw new Error( + `ENOENT: no such file or directory, lstat '${entry._fullpath}'` + ); + } + let type = stat.isDirectory() ? "tree" : "blob"; + if (type === "blob" && !stat.isFile() && !stat.isSymbolicLink()) { + type = "special"; + } + entry._type = type; + stat = normalizeStats(stat); + entry._mode = stat.mode; + if (stat.size === -1 && entry._actualSize) { + stat.size = entry._actualSize; + } + entry._stat = stat; + } + return entry._stat; + } + async content(entry) { + if (entry._content === false) { + const { fs, dir } = this; + if (await entry.type() === "tree") { + entry._content = void 0; + } else { + const content = await fs.read(`${dir}/${entry._fullpath}`); + entry._actualSize = content.length; + if (entry._stat && entry._stat.size === -1) { + entry._stat.size = entry._actualSize; + } + entry._content = new Uint8Array(content); + } + } + return entry._content; + } + async oid(entry) { + if (entry._oid === false) { + const { fs, gitdir, cache } = this; + let oid; + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + const stage = index2.entriesMap.get(entry._fullpath); + const stats = await entry.stat(); + if (!stage || compareStats(stats, stage)) { + const content = await entry.content(); + if (content === void 0) { + oid = void 0; + } else { + oid = await shasum( + GitObject.wrap({ type: "blob", object: await entry.content() }) + ); + if (stage && oid === stage.oid && stats.mode === stage.mode && compareStats(stats, stage)) { + index2.insert({ + filepath: entry._fullpath, + stats, + oid + }); + } + } + } else { + oid = stage.oid; + } + }); + entry._oid = oid; + } + return entry._oid; + } +}; +function WORKDIR() { + const o = /* @__PURE__ */ Object.create(null); + Object.defineProperty(o, GitWalkSymbol, { + value: function({ fs, dir, gitdir, cache }) { + return new GitWalkerFs({ fs, dir, gitdir, cache }); + } + }); + Object.freeze(o); + return o; +} +function arrayRange(start, end) { + const length = end - start; + return Array.from({ length }, (_, i) => start + i); +} +var flat = typeof Array.prototype.flat === "undefined" ? (entries) => entries.reduce((acc, x) => acc.concat(x), []) : (entries) => entries.flat(); +var RunningMinimum = class { + constructor() { + this.value = null; + } + consider(value) { + if (value === null || value === void 0) + return; + if (this.value === null) { + this.value = value; + } else if (value < this.value) { + this.value = value; + } + } + reset() { + this.value = null; + } +}; +function* unionOfIterators(sets) { + const min = new RunningMinimum(); + let minimum; + const heads = []; + const numsets = sets.length; + for (let i = 0; i < numsets; i++) { + heads[i] = sets[i].next().value; + if (heads[i] !== void 0) { + min.consider(heads[i]); + } + } + if (min.value === null) + return; + while (true) { + const result = []; + minimum = min.value; + min.reset(); + for (let i = 0; i < numsets; i++) { + if (heads[i] !== void 0 && heads[i] === minimum) { + result[i] = heads[i]; + heads[i] = sets[i].next().value; + } else { + result[i] = null; + } + if (heads[i] !== void 0) { + min.consider(heads[i]); + } + } + yield result; + if (min.value === null) + return; + } +} +async function _walk({ + fs, + cache, + dir, + gitdir, + trees, + // @ts-ignore + map = async (_, entry) => entry, + // The default reducer is a flatmap that filters out undefineds. + reduce = async (parent, children2) => { + const flatten = flat(children2); + if (parent !== void 0) + flatten.unshift(parent); + return flatten; + }, + // The default iterate function walks all children concurrently + iterate = (walk2, children2) => Promise.all([...children2].map(walk2)) +}) { + const walkers = trees.map( + (proxy) => proxy[GitWalkSymbol]({ fs, dir, gitdir, cache }) + ); + const root2 = new Array(walkers.length).fill("."); + const range = arrayRange(0, walkers.length); + const unionWalkerFromReaddir = async (entries) => { + range.map((i) => { + entries[i] = entries[i] && new walkers[i].ConstructEntry(entries[i]); + }); + const subdirs = await Promise.all( + range.map((i) => entries[i] ? walkers[i].readdir(entries[i]) : []) + ); + const iterators = subdirs.map((array) => array === null ? [] : array).map((array) => array[Symbol.iterator]()); + return { + entries, + children: unionOfIterators(iterators) + }; + }; + const walk2 = async (root3) => { + const { entries, children: children2 } = await unionWalkerFromReaddir(root3); + const fullpath = entries.find((entry) => entry && entry._fullpath)._fullpath; + const parent = await map(fullpath, entries); + if (parent !== null) { + let walkedChildren = await iterate(walk2, children2); + walkedChildren = walkedChildren.filter((x) => x !== void 0); + return reduce(parent, walkedChildren); + } + }; + return walk2(root2); +} +async function rmRecursive(fs, filepath) { + const entries = await fs.readdir(filepath); + if (entries == null) { + await fs.rm(filepath); + } else if (entries.length) { + await Promise.all( + entries.map((entry) => { + const subpath = join(filepath, entry); + return fs.lstat(subpath).then((stat) => { + if (!stat) + return; + return stat.isDirectory() ? rmRecursive(fs, subpath) : fs.rm(subpath); + }); + }) + ).then(() => fs.rmdir(filepath)); + } else { + await fs.rmdir(filepath); + } +} +function isPromiseLike(obj) { + return isObject(obj) && isFunction(obj.then) && isFunction(obj.catch); +} +function isObject(obj) { + return obj && typeof obj === "object"; +} +function isFunction(obj) { + return typeof obj === "function"; +} +function isPromiseFs(fs) { + const test = (targetFs) => { + try { + return targetFs.readFile().catch((e) => e); + } catch (e) { + return e; + } + }; + return isPromiseLike(test(fs)); +} +var commands = [ + "readFile", + "writeFile", + "mkdir", + "rmdir", + "unlink", + "stat", + "lstat", + "readdir", + "readlink", + "symlink" +]; +function bindFs(target, fs) { + if (isPromiseFs(fs)) { + for (const command of commands) { + target[`_${command}`] = fs[command].bind(fs); + } + } else { + for (const command of commands) { + target[`_${command}`] = (0, import_pify.default)(fs[command].bind(fs)); + } + } + if (isPromiseFs(fs)) { + if (fs.rm) + target._rm = fs.rm.bind(fs); + else if (fs.rmdir.length > 1) + target._rm = fs.rmdir.bind(fs); + else + target._rm = rmRecursive.bind(null, target); + } else { + if (fs.rm) + target._rm = (0, import_pify.default)(fs.rm.bind(fs)); + else if (fs.rmdir.length > 2) + target._rm = (0, import_pify.default)(fs.rmdir.bind(fs)); + else + target._rm = rmRecursive.bind(null, target); + } +} +var FileSystem = class { + constructor(fs) { + if (typeof fs._original_unwrapped_fs !== "undefined") + return fs; + const promises = Object.getOwnPropertyDescriptor(fs, "promises"); + if (promises && promises.enumerable) { + bindFs(this, fs.promises); + } else { + bindFs(this, fs); + } + this._original_unwrapped_fs = fs; + } + /** + * Return true if a file exists, false if it doesn't exist. + * Rethrows errors that aren't related to file existance. + */ + async exists(filepath, options = {}) { + try { + await this._stat(filepath); + return true; + } catch (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return false; + } else { + console.log('Unhandled error in "FileSystem.exists()" function', err); + throw err; + } + } + } + /** + * Return the contents of a file if it exists, otherwise returns null. + * + * @param {string} filepath + * @param {object} [options] + * + * @returns {Promise} + */ + async read(filepath, options = {}) { + try { + let buffer2 = await this._readFile(filepath, options); + if (typeof buffer2 !== "string") { + buffer2 = Buffer.from(buffer2); + } + return buffer2; + } catch (err) { + return null; + } + } + /** + * Write a file (creating missing directories if need be) without throwing errors. + * + * @param {string} filepath + * @param {Buffer|Uint8Array|string} contents + * @param {object|string} [options] + */ + async write(filepath, contents, options = {}) { + try { + await this._writeFile(filepath, contents, options); + return; + } catch (err) { + await this.mkdir(dirname(filepath)); + await this._writeFile(filepath, contents, options); + } + } + /** + * Make a directory (or series of nested directories) without throwing an error if it already exists. + */ + async mkdir(filepath, _selfCall = false) { + try { + await this._mkdir(filepath); + return; + } catch (err) { + if (err === null) + return; + if (err.code === "EEXIST") + return; + if (_selfCall) + throw err; + if (err.code === "ENOENT") { + const parent = dirname(filepath); + if (parent === "." || parent === "/" || parent === filepath) + throw err; + await this.mkdir(parent); + await this.mkdir(filepath, true); + } + } + } + /** + * Delete a file without throwing an error if it is already deleted. + */ + async rm(filepath) { + try { + await this._unlink(filepath); + } catch (err) { + if (err.code !== "ENOENT") + throw err; + } + } + /** + * Delete a directory without throwing an error if it is already deleted. + */ + async rmdir(filepath, opts) { + try { + if (opts && opts.recursive) { + await this._rm(filepath, opts); + } else { + await this._rmdir(filepath); + } + } catch (err) { + if (err.code !== "ENOENT") + throw err; + } + } + /** + * Read a directory without throwing an error is the directory doesn't exist + */ + async readdir(filepath) { + try { + const names = await this._readdir(filepath); + names.sort(compareStrings); + return names; + } catch (err) { + if (err.code === "ENOTDIR") + return null; + return []; + } + } + /** + * Return a flast list of all the files nested inside a directory + * + * Based on an elegant concurrent recursive solution from SO + * https://stackoverflow.com/a/45130990/2168416 + */ + async readdirDeep(dir) { + const subdirs = await this._readdir(dir); + const files = await Promise.all( + subdirs.map(async (subdir) => { + const res = dir + "/" + subdir; + return (await this._stat(res)).isDirectory() ? this.readdirDeep(res) : res; + }) + ); + return files.reduce((a, f) => a.concat(f), []); + } + /** + * Return the Stats of a file/symlink if it exists, otherwise returns null. + * Rethrows errors that aren't related to file existance. + */ + async lstat(filename) { + try { + const stats = await this._lstat(filename); + return stats; + } catch (err) { + if (err.code === "ENOENT") { + return null; + } + throw err; + } + } + /** + * Reads the contents of a symlink if it exists, otherwise returns null. + * Rethrows errors that aren't related to file existance. + */ + async readlink(filename, opts = { encoding: "buffer" }) { + try { + const link = await this._readlink(filename, opts); + return Buffer.isBuffer(link) ? link : Buffer.from(link); + } catch (err) { + if (err.code === "ENOENT") { + return null; + } + throw err; + } + } + /** + * Write the contents of buffer to a symlink. + */ + async writelink(filename, buffer2) { + return this._symlink(buffer2.toString("utf8"), filename); + } +}; +function assertParameter(name, value) { + if (value === void 0) { + throw new MissingParameterError(name); + } +} +async function modified(entry, base) { + if (!entry && !base) + return false; + if (entry && !base) + return true; + if (!entry && base) + return true; + if (await entry.type() === "tree" && await base.type() === "tree") { + return false; + } + if (await entry.type() === await base.type() && await entry.mode() === await base.mode() && await entry.oid() === await base.oid()) { + return false; + } + return true; +} +async function abortMerge({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + commit: commit2 = "HEAD", + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("dir", dir); + assertParameter("gitdir", gitdir); + const fs = new FileSystem(_fs); + const trees = [TREE({ ref: commit2 }), WORKDIR(), STAGE()]; + let unmergedPaths = []; + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + unmergedPaths = index2.unmergedPaths; + }); + const results = await _walk({ + fs, + cache, + dir, + gitdir, + trees, + map: async function(path2, [head, workdir, index2]) { + const staged = !await modified(workdir, index2); + const unmerged = unmergedPaths.includes(path2); + const unmodified = !await modified(index2, head); + if (staged || unmerged) { + return head ? { + path: path2, + mode: await head.mode(), + oid: await head.oid(), + type: await head.type(), + content: await head.content() + } : void 0; + } + if (unmodified) + return false; + else + throw new IndexResetError(path2); + } + }); + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + for (const entry of results) { + if (entry === false) + continue; + if (!entry) { + await fs.rmdir(`${dir}/${entry.path}`, { recursive: true }); + index2.delete({ filepath: entry.path }); + continue; + } + if (entry.type === "blob") { + const content = new TextDecoder().decode(entry.content); + await fs.write(`${dir}/${entry.path}`, content, { mode: entry.mode }); + index2.insert({ + filepath: entry.path, + oid: entry.oid, + stage: 0 + }); + } + } + }); + } catch (err) { + err.caller = "git.abortMerge"; + throw err; + } +} +var GitIgnoreManager = class { + static async isIgnored({ fs, dir, gitdir = join(dir, ".git"), filepath }) { + if (basename(filepath) === ".git") + return true; + if (filepath === ".") + return false; + let excludes = ""; + const excludesFile = join(gitdir, "info", "exclude"); + if (await fs.exists(excludesFile)) { + excludes = await fs.read(excludesFile, "utf8"); + } + const pairs = [ + { + gitignore: join(dir, ".gitignore"), + filepath + } + ]; + const pieces = filepath.split("/").filter(Boolean); + for (let i = 1; i < pieces.length; i++) { + const folder = pieces.slice(0, i).join("/"); + const file = pieces.slice(i).join("/"); + pairs.push({ + gitignore: join(dir, folder, ".gitignore"), + filepath: file + }); + } + let ignoredStatus = false; + for (const p of pairs) { + let file; + try { + file = await fs.read(p.gitignore, "utf8"); + } catch (err) { + if (err.code === "NOENT") + continue; + } + const ign = (0, import_ignore.default)().add(excludes); + ign.add(file); + const parentdir = dirname(p.filepath); + if (parentdir !== "." && ign.ignores(parentdir)) + return true; + if (ignoredStatus) { + ignoredStatus = !ign.test(p.filepath).unignored; + } else { + ignoredStatus = ign.test(p.filepath).ignored; + } + } + return ignoredStatus; + } +}; +async function writeObjectLoose({ fs, gitdir, object, format, oid }) { + if (format !== "deflated") { + throw new InternalError( + "GitObjectStoreLoose expects objects to write to be in deflated format" + ); + } + const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`; + const filepath = `${gitdir}/${source}`; + if (!await fs.exists(filepath)) + await fs.write(filepath, object); +} +var supportsCompressionStream = null; +async function deflate(buffer2) { + if (supportsCompressionStream === null) { + supportsCompressionStream = testCompressionStream(); + } + return supportsCompressionStream ? browserDeflate(buffer2) : import_pako.default.deflate(buffer2); +} +async function browserDeflate(buffer2) { + const cs = new CompressionStream("deflate"); + const c = new Blob([buffer2]).stream().pipeThrough(cs); + return new Uint8Array(await new Response(c).arrayBuffer()); +} +function testCompressionStream() { + try { + const cs = new CompressionStream("deflate"); + new Blob([]).stream(); + if (cs) + return true; + } catch (_) { + } + return false; +} +async function _writeObject({ + fs, + gitdir, + type, + object, + format = "content", + oid = void 0, + dryRun = false +}) { + if (format !== "deflated") { + if (format !== "wrapped") { + object = GitObject.wrap({ type, object }); + } + oid = await shasum(object); + object = Buffer.from(await deflate(object)); + } + if (!dryRun) { + await writeObjectLoose({ fs, gitdir, object, format: "deflated", oid }); + } + return oid; +} +function posixifyPathBuffer(buffer2) { + let idx; + while (~(idx = buffer2.indexOf(92))) + buffer2[idx] = 47; + return buffer2; +} +async function add({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + filepath, + cache = {}, + force = false, + parallel = true +}) { + try { + assertParameter("fs", _fs); + assertParameter("dir", dir); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + const fs = new FileSystem(_fs); + await GitIndexManager.acquire({ fs, gitdir, cache }, async (index2) => { + return addToIndex({ + dir, + gitdir, + fs, + filepath, + index: index2, + force, + parallel + }); + }); + } catch (err) { + err.caller = "git.add"; + throw err; + } +} +async function addToIndex({ + dir, + gitdir, + fs, + filepath, + index: index2, + force, + parallel +}) { + filepath = Array.isArray(filepath) ? filepath : [filepath]; + const promises = filepath.map(async (currentFilepath) => { + if (!force) { + const ignored = await GitIgnoreManager.isIgnored({ + fs, + dir, + gitdir, + filepath: currentFilepath + }); + if (ignored) + return; + } + const stats = await fs.lstat(join(dir, currentFilepath)); + if (!stats) + throw new NotFoundError(currentFilepath); + if (stats.isDirectory()) { + const children2 = await fs.readdir(join(dir, currentFilepath)); + if (parallel) { + const promises2 = children2.map( + (child) => addToIndex({ + dir, + gitdir, + fs, + filepath: [join(currentFilepath, child)], + index: index2, + force, + parallel + }) + ); + await Promise.all(promises2); + } else { + for (const child of children2) { + await addToIndex({ + dir, + gitdir, + fs, + filepath: [join(currentFilepath, child)], + index: index2, + force, + parallel + }); + } + } + } else { + const object = stats.isSymbolicLink() ? await fs.readlink(join(dir, currentFilepath)).then(posixifyPathBuffer) : await fs.read(join(dir, currentFilepath)); + if (object === null) + throw new NotFoundError(currentFilepath); + const oid = await _writeObject({ fs, gitdir, type: "blob", object }); + index2.insert({ filepath: currentFilepath, stats, oid }); + } + }); + const settledPromises = await Promise.allSettled(promises); + const rejectedPromises = settledPromises.filter((settle) => settle.status === "rejected").map((settle) => settle.reason); + if (rejectedPromises.length > 1) { + throw new MultipleGitError(rejectedPromises); + } + if (rejectedPromises.length === 1) { + throw rejectedPromises[0]; + } + const fulfilledPromises = settledPromises.filter((settle) => settle.status === "fulfilled" && settle.value).map((settle) => settle.value); + return fulfilledPromises; +} +async function _commit({ + fs, + cache, + onSign, + gitdir, + message, + author, + committer, + signingKey, + dryRun = false, + noUpdateBranch = false, + ref, + parent, + tree +}) { + if (!ref) { + ref = await GitRefManager.resolve({ + fs, + gitdir, + ref: "HEAD", + depth: 2 + }); + } + return GitIndexManager.acquire( + { fs, gitdir, cache, allowUnmerged: false }, + async function(index2) { + const inodes = flatFileListToDirectoryStructure(index2.entries); + const inode = inodes.get("."); + if (!tree) { + tree = await constructTree({ fs, gitdir, inode, dryRun }); + } + if (!parent) { + try { + parent = [ + await GitRefManager.resolve({ + fs, + gitdir, + ref + }) + ]; + } catch (err) { + parent = []; + } + } else { + parent = await Promise.all( + parent.map((p) => { + return GitRefManager.resolve({ fs, gitdir, ref: p }); + }) + ); + } + let comm = GitCommit.from({ + tree, + parent, + author, + committer, + message + }); + if (signingKey) { + comm = await GitCommit.sign(comm, onSign, signingKey); + } + const oid = await _writeObject({ + fs, + gitdir, + type: "commit", + object: comm.toObject(), + dryRun + }); + if (!noUpdateBranch && !dryRun) { + await GitRefManager.writeRef({ + fs, + gitdir, + ref, + value: oid + }); + } + return oid; + } + ); +} +async function constructTree({ fs, gitdir, inode, dryRun }) { + const children2 = inode.children; + for (const inode2 of children2) { + if (inode2.type === "tree") { + inode2.metadata.mode = "040000"; + inode2.metadata.oid = await constructTree({ fs, gitdir, inode: inode2, dryRun }); + } + } + const entries = children2.map((inode2) => ({ + mode: inode2.metadata.mode, + path: inode2.basename, + oid: inode2.metadata.oid, + type: inode2.type + })); + const tree = GitTree.from(entries); + const oid = await _writeObject({ + fs, + gitdir, + type: "tree", + object: tree.toObject(), + dryRun + }); + return oid; +} +async function resolveFilepath({ fs, cache, gitdir, oid, filepath }) { + if (filepath.startsWith("/")) { + throw new InvalidFilepathError("leading-slash"); + } else if (filepath.endsWith("/")) { + throw new InvalidFilepathError("trailing-slash"); + } + const _oid = oid; + const result = await resolveTree({ fs, cache, gitdir, oid }); + const tree = result.tree; + if (filepath === "") { + oid = result.oid; + } else { + const pathArray = filepath.split("/"); + oid = await _resolveFilepath({ + fs, + cache, + gitdir, + tree, + pathArray, + oid: _oid, + filepath + }); + } + return oid; +} +async function _resolveFilepath({ + fs, + cache, + gitdir, + tree, + pathArray, + oid, + filepath +}) { + const name = pathArray.shift(); + for (const entry of tree) { + if (entry.path === name) { + if (pathArray.length === 0) { + return entry.oid; + } else { + const { type, object } = await _readObject({ + fs, + cache, + gitdir, + oid: entry.oid + }); + if (type !== "tree") { + throw new ObjectTypeError(oid, type, "tree", filepath); + } + tree = GitTree.from(object); + return _resolveFilepath({ + fs, + cache, + gitdir, + tree, + pathArray, + oid, + filepath + }); + } + } + } + throw new NotFoundError(`file or directory found at "${oid}:${filepath}"`); +} +async function _readTree({ + fs, + cache, + gitdir, + oid, + filepath = void 0 +}) { + if (filepath !== void 0) { + oid = await resolveFilepath({ fs, cache, gitdir, oid, filepath }); + } + const { tree, oid: treeOid } = await resolveTree({ fs, cache, gitdir, oid }); + const result = { + oid: treeOid, + tree: tree.entries() + }; + return result; +} +async function _writeTree({ fs, gitdir, tree }) { + const object = GitTree.from(tree).toObject(); + const oid = await _writeObject({ + fs, + gitdir, + type: "tree", + object, + format: "content" + }); + return oid; +} +async function _addNote({ + fs, + cache, + onSign, + gitdir, + ref, + oid, + note, + force, + author, + committer, + signingKey +}) { + let parent; + try { + parent = await GitRefManager.resolve({ gitdir, fs, ref }); + } catch (err) { + if (!(err instanceof NotFoundError)) { + throw err; + } + } + const result = await _readTree({ + fs, + cache, + gitdir, + oid: parent || "4b825dc642cb6eb9a060e54bf8d69288fbee4904" + }); + let tree = result.tree; + if (force) { + tree = tree.filter((entry) => entry.path !== oid); + } else { + for (const entry of tree) { + if (entry.path === oid) { + throw new AlreadyExistsError("note", oid); + } + } + } + if (typeof note === "string") { + note = Buffer.from(note, "utf8"); + } + const noteOid = await _writeObject({ + fs, + gitdir, + type: "blob", + object: note, + format: "content" + }); + tree.push({ mode: "100644", path: oid, oid: noteOid, type: "blob" }); + const treeOid = await _writeTree({ + fs, + gitdir, + tree + }); + const commitOid = await _commit({ + fs, + cache, + onSign, + gitdir, + ref, + tree: treeOid, + parent: parent && [parent], + message: `Note added by 'isomorphic-git addNote' +`, + author, + committer, + signingKey + }); + return commitOid; +} +async function _getConfig({ fs, gitdir, path: path2 }) { + const config = await GitConfigManager.get({ fs, gitdir }); + return config.get(path2); +} +async function normalizeAuthorObject({ fs, gitdir, author = {} }) { + let { name, email, timestamp, timezoneOffset } = author; + name = name || await _getConfig({ fs, gitdir, path: "user.name" }); + email = email || await _getConfig({ fs, gitdir, path: "user.email" }) || ""; + if (name === void 0) { + return void 0; + } + timestamp = timestamp != null ? timestamp : Math.floor(Date.now() / 1e3); + timezoneOffset = timezoneOffset != null ? timezoneOffset : new Date(timestamp * 1e3).getTimezoneOffset(); + return { name, email, timestamp, timezoneOffset }; +} +async function normalizeCommitterObject({ + fs, + gitdir, + author, + committer +}) { + committer = Object.assign({}, committer || author); + if (author) { + committer.timestamp = committer.timestamp || author.timestamp; + committer.timezoneOffset = committer.timezoneOffset || author.timezoneOffset; + } + committer = await normalizeAuthorObject({ fs, gitdir, author: committer }); + return committer; +} +async function addNote({ + fs: _fs, + onSign, + dir, + gitdir = join(dir, ".git"), + ref = "refs/notes/commits", + oid, + note, + force, + author: _author, + committer: _committer, + signingKey, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + assertParameter("note", note); + if (signingKey) { + assertParameter("onSign", onSign); + } + const fs = new FileSystem(_fs); + const author = await normalizeAuthorObject({ fs, gitdir, author: _author }); + if (!author) + throw new MissingNameError("author"); + const committer = await normalizeCommitterObject({ + fs, + gitdir, + author, + committer: _committer + }); + if (!committer) + throw new MissingNameError("committer"); + return await _addNote({ + fs: new FileSystem(fs), + cache, + onSign, + gitdir, + ref, + oid, + note, + force, + author, + committer, + signingKey + }); + } catch (err) { + err.caller = "git.addNote"; + throw err; + } +} +async function _addRemote({ fs, gitdir, remote, url, force }) { + if (remote !== import_clean_git_ref.default.clean(remote)) { + throw new InvalidRefNameError(remote, import_clean_git_ref.default.clean(remote)); + } + const config = await GitConfigManager.get({ fs, gitdir }); + if (!force) { + const remoteNames = await config.getSubsections("remote"); + if (remoteNames.includes(remote)) { + if (url !== await config.get(`remote.${remote}.url`)) { + throw new AlreadyExistsError("remote", remote); + } + } + } + await config.set(`remote.${remote}.url`, url); + await config.set( + `remote.${remote}.fetch`, + `+refs/heads/*:refs/remotes/${remote}/*` + ); + await GitConfigManager.save({ fs, gitdir, config }); +} +async function addRemote({ + fs, + dir, + gitdir = join(dir, ".git"), + remote, + url, + force = false +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("remote", remote); + assertParameter("url", url); + return await _addRemote({ + fs: new FileSystem(fs), + gitdir, + remote, + url, + force + }); + } catch (err) { + err.caller = "git.addRemote"; + throw err; + } +} +async function _annotatedTag({ + fs, + cache, + onSign, + gitdir, + ref, + tagger, + message = ref, + gpgsig, + object, + signingKey, + force = false +}) { + ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`; + if (!force && await GitRefManager.exists({ fs, gitdir, ref })) { + throw new AlreadyExistsError("tag", ref); + } + const oid = await GitRefManager.resolve({ + fs, + gitdir, + ref: object || "HEAD" + }); + const { type } = await _readObject({ fs, cache, gitdir, oid }); + let tagObject = GitAnnotatedTag.from({ + object: oid, + type, + tag: ref.replace("refs/tags/", ""), + tagger, + message, + gpgsig + }); + if (signingKey) { + tagObject = await GitAnnotatedTag.sign(tagObject, onSign, signingKey); + } + const value = await _writeObject({ + fs, + gitdir, + type: "tag", + object: tagObject.toObject() + }); + await GitRefManager.writeRef({ fs, gitdir, ref, value }); +} +async function annotatedTag({ + fs: _fs, + onSign, + dir, + gitdir = join(dir, ".git"), + ref, + tagger: _tagger, + message = ref, + gpgsig, + object, + signingKey, + force = false, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + if (signingKey) { + assertParameter("onSign", onSign); + } + const fs = new FileSystem(_fs); + const tagger = await normalizeAuthorObject({ fs, gitdir, author: _tagger }); + if (!tagger) + throw new MissingNameError("tagger"); + return await _annotatedTag({ + fs, + cache, + onSign, + gitdir, + ref, + tagger, + message, + gpgsig, + object, + signingKey, + force + }); + } catch (err) { + err.caller = "git.annotatedTag"; + throw err; + } +} +async function _branch({ + fs, + gitdir, + ref, + object, + checkout: checkout2 = false, + force = false +}) { + if (ref !== import_clean_git_ref.default.clean(ref)) { + throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref)); + } + const fullref = `refs/heads/${ref}`; + if (!force) { + const exist = await GitRefManager.exists({ fs, gitdir, ref: fullref }); + if (exist) { + throw new AlreadyExistsError("branch", ref, false); + } + } + let oid; + try { + oid = await GitRefManager.resolve({ fs, gitdir, ref: object || "HEAD" }); + } catch (e) { + } + if (oid) { + await GitRefManager.writeRef({ fs, gitdir, ref: fullref, value: oid }); + } + if (checkout2) { + await GitRefManager.writeSymbolicRef({ + fs, + gitdir, + ref: "HEAD", + value: fullref + }); + } +} +async function branch({ + fs, + dir, + gitdir = join(dir, ".git"), + ref, + object, + checkout: checkout2 = false, + force = false +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + return await _branch({ + fs: new FileSystem(fs), + gitdir, + ref, + object, + checkout: checkout2, + force + }); + } catch (err) { + err.caller = "git.branch"; + throw err; + } +} +var worthWalking = (filepath, root2) => { + if (filepath === "." || root2 == null || root2.length === 0 || root2 === ".") { + return true; + } + if (root2.length >= filepath.length) { + return root2.startsWith(filepath); + } else { + return filepath.startsWith(root2); + } +}; +async function _checkout({ + fs, + cache, + onProgress, + dir, + gitdir, + remote, + ref, + filepaths, + noCheckout, + noUpdateHead, + dryRun, + force, + track = true +}) { + let oid; + try { + oid = await GitRefManager.resolve({ fs, gitdir, ref }); + } catch (err) { + if (ref === "HEAD") + throw err; + const remoteRef = `${remote}/${ref}`; + oid = await GitRefManager.resolve({ + fs, + gitdir, + ref: remoteRef + }); + if (track) { + const config = await GitConfigManager.get({ fs, gitdir }); + await config.set(`branch.${ref}.remote`, remote); + await config.set(`branch.${ref}.merge`, `refs/heads/${ref}`); + await GitConfigManager.save({ fs, gitdir, config }); + } + await GitRefManager.writeRef({ + fs, + gitdir, + ref: `refs/heads/${ref}`, + value: oid + }); + } + if (!noCheckout) { + let ops; + try { + ops = await analyze({ + fs, + cache, + onProgress, + dir, + gitdir, + ref, + force, + filepaths + }); + } catch (err) { + if (err instanceof NotFoundError && err.data.what === oid) { + throw new CommitNotFetchedError(ref, oid); + } else { + throw err; + } + } + const conflicts2 = ops.filter(([method2]) => method2 === "conflict").map(([method2, fullpath]) => fullpath); + if (conflicts2.length > 0) { + throw new CheckoutConflictError(conflicts2); + } + const errors = ops.filter(([method2]) => method2 === "error").map(([method2, fullpath]) => fullpath); + if (errors.length > 0) { + throw new InternalError(errors.join(", ")); + } + if (dryRun) { + return; + } + let count = 0; + const total = ops.length; + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + await Promise.all( + ops.filter( + ([method2]) => method2 === "delete" || method2 === "delete-index" + ).map(async function([method2, fullpath]) { + const filepath = `${dir}/${fullpath}`; + if (method2 === "delete") { + await fs.rm(filepath); + } + index2.delete({ filepath: fullpath }); + if (onProgress) { + await onProgress({ + phase: "Updating workdir", + loaded: ++count, + total + }); + } + }) + ); + }); + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + for (const [method2, fullpath] of ops) { + if (method2 === "rmdir" || method2 === "rmdir-index") { + const filepath = `${dir}/${fullpath}`; + try { + if (method2 === "rmdir-index") { + index2.delete({ filepath: fullpath }); + } + await fs.rmdir(filepath); + if (onProgress) { + await onProgress({ + phase: "Updating workdir", + loaded: ++count, + total + }); + } + } catch (e) { + if (e.code === "ENOTEMPTY") { + console.log( + `Did not delete ${fullpath} because directory is not empty` + ); + } else { + throw e; + } + } + } + } + }); + await Promise.all( + ops.filter(([method2]) => method2 === "mkdir" || method2 === "mkdir-index").map(async function([_, fullpath]) { + const filepath = `${dir}/${fullpath}`; + await fs.mkdir(filepath); + if (onProgress) { + await onProgress({ + phase: "Updating workdir", + loaded: ++count, + total + }); + } + }) + ); + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + await Promise.all( + ops.filter( + ([method2]) => method2 === "create" || method2 === "create-index" || method2 === "update" || method2 === "mkdir-index" + ).map(async function([method2, fullpath, oid2, mode, chmod]) { + const filepath = `${dir}/${fullpath}`; + try { + if (method2 !== "create-index" && method2 !== "mkdir-index") { + const { object } = await _readObject({ fs, cache, gitdir, oid: oid2 }); + if (chmod) { + await fs.rm(filepath); + } + if (mode === 33188) { + await fs.write(filepath, object); + } else if (mode === 33261) { + await fs.write(filepath, object, { mode: 511 }); + } else if (mode === 40960) { + await fs.writelink(filepath, object); + } else { + throw new InternalError( + `Invalid mode 0o${mode.toString(8)} detected in blob ${oid2}` + ); + } + } + const stats = await fs.lstat(filepath); + if (mode === 33261) { + stats.mode = 493; + } + if (method2 === "mkdir-index") { + stats.mode = 57344; + } + index2.insert({ + filepath: fullpath, + stats, + oid: oid2 + }); + if (onProgress) { + await onProgress({ + phase: "Updating workdir", + loaded: ++count, + total + }); + } + } catch (e) { + console.log(e); + } + }) + ); + }); + } + if (!noUpdateHead) { + const fullRef = await GitRefManager.expand({ fs, gitdir, ref }); + if (fullRef.startsWith("refs/heads")) { + await GitRefManager.writeSymbolicRef({ + fs, + gitdir, + ref: "HEAD", + value: fullRef + }); + } else { + await GitRefManager.writeRef({ fs, gitdir, ref: "HEAD", value: oid }); + } + } +} +async function analyze({ + fs, + cache, + onProgress, + dir, + gitdir, + ref, + force, + filepaths +}) { + let count = 0; + return _walk({ + fs, + cache, + dir, + gitdir, + trees: [TREE({ ref }), WORKDIR(), STAGE()], + map: async function(fullpath, [commit2, workdir, stage]) { + if (fullpath === ".") + return; + if (filepaths && !filepaths.some((base) => worthWalking(fullpath, base))) { + return null; + } + if (onProgress) { + await onProgress({ phase: "Analyzing workdir", loaded: ++count }); + } + const key2 = [!!stage, !!commit2, !!workdir].map(Number).join(""); + switch (key2) { + case "000": + return; + case "001": + if (force && filepaths && filepaths.includes(fullpath)) { + return ["delete", fullpath]; + } + return; + case "010": { + switch (await commit2.type()) { + case "tree": { + return ["mkdir", fullpath]; + } + case "blob": { + return [ + "create", + fullpath, + await commit2.oid(), + await commit2.mode() + ]; + } + case "commit": { + return [ + "mkdir-index", + fullpath, + await commit2.oid(), + await commit2.mode() + ]; + } + default: { + return [ + "error", + `new entry Unhandled type ${await commit2.type()}` + ]; + } + } + } + case "011": { + switch (`${await commit2.type()}-${await workdir.type()}`) { + case "tree-tree": { + return; + } + case "tree-blob": + case "blob-tree": { + return ["conflict", fullpath]; + } + case "blob-blob": { + if (await commit2.oid() !== await workdir.oid()) { + if (force) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + await commit2.mode() !== await workdir.mode() + ]; + } else { + return ["conflict", fullpath]; + } + } else { + if (await commit2.mode() !== await workdir.mode()) { + if (force) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + true + ]; + } else { + return ["conflict", fullpath]; + } + } else { + return [ + "create-index", + fullpath, + await commit2.oid(), + await commit2.mode() + ]; + } + } + } + case "commit-tree": { + return; + } + case "commit-blob": { + return ["conflict", fullpath]; + } + default: { + return ["error", `new entry Unhandled type ${commit2.type}`]; + } + } + } + case "100": { + return ["delete-index", fullpath]; + } + case "101": { + switch (await stage.type()) { + case "tree": { + return ["rmdir", fullpath]; + } + case "blob": { + if (await stage.oid() !== await workdir.oid()) { + if (force) { + return ["delete", fullpath]; + } else { + return ["conflict", fullpath]; + } + } else { + return ["delete", fullpath]; + } + } + case "commit": { + return ["rmdir-index", fullpath]; + } + default: { + return [ + "error", + `delete entry Unhandled type ${await stage.type()}` + ]; + } + } + } + case "110": + case "111": { + switch (`${await stage.type()}-${await commit2.type()}`) { + case "tree-tree": { + return; + } + case "blob-blob": { + if (await stage.oid() === await commit2.oid() && await stage.mode() === await commit2.mode() && !force) { + return; + } + if (workdir) { + if (await workdir.oid() !== await stage.oid() && await workdir.oid() !== await commit2.oid()) { + if (force) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + await commit2.mode() !== await workdir.mode() + ]; + } else { + return ["conflict", fullpath]; + } + } + } else if (force) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + await commit2.mode() !== await stage.mode() + ]; + } + if (await commit2.mode() !== await stage.mode()) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + true + ]; + } + if (await commit2.oid() !== await stage.oid()) { + return [ + "update", + fullpath, + await commit2.oid(), + await commit2.mode(), + false + ]; + } else { + return; + } + } + case "tree-blob": { + return ["update-dir-to-blob", fullpath, await commit2.oid()]; + } + case "blob-tree": { + return ["update-blob-to-tree", fullpath]; + } + case "commit-commit": { + return [ + "mkdir-index", + fullpath, + await commit2.oid(), + await commit2.mode() + ]; + } + default: { + return [ + "error", + `update entry Unhandled type ${await stage.type()}-${await commit2.type()}` + ]; + } + } + } + } + }, + // Modify the default flat mapping + reduce: async function(parent, children2) { + children2 = flat(children2); + if (!parent) { + return children2; + } else if (parent && parent[0] === "rmdir") { + children2.push(parent); + return children2; + } else { + children2.unshift(parent); + return children2; + } + } + }); +} +async function checkout({ + fs, + onProgress, + dir, + gitdir = join(dir, ".git"), + remote = "origin", + ref: _ref, + filepaths, + noCheckout = false, + noUpdateHead = _ref === void 0, + dryRun = false, + force = false, + track = true, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("dir", dir); + assertParameter("gitdir", gitdir); + const ref = _ref || "HEAD"; + return await _checkout({ + fs: new FileSystem(fs), + cache, + onProgress, + dir, + gitdir, + remote, + ref, + filepaths, + noCheckout, + noUpdateHead, + dryRun, + force, + track + }); + } catch (err) { + err.caller = "git.checkout"; + throw err; + } +} +var abbreviateRx = new RegExp("^refs/(heads/|tags/|remotes/)?(.*)"); +function abbreviateRef(ref) { + const match = abbreviateRx.exec(ref); + if (match) { + if (match[1] === "remotes/" && ref.endsWith("/HEAD")) { + return match[2].slice(0, -5); + } else { + return match[2]; + } + } + return ref; +} +async function _currentBranch({ + fs, + gitdir, + fullname = false, + test = false +}) { + const ref = await GitRefManager.resolve({ + fs, + gitdir, + ref: "HEAD", + depth: 2 + }); + if (test) { + try { + await GitRefManager.resolve({ fs, gitdir, ref }); + } catch (_) { + return; + } + } + if (!ref.startsWith("refs/")) + return; + return fullname ? ref : abbreviateRef(ref); +} +function translateSSHtoHTTP(url) { + url = url.replace(/^git@([^:]+):/, "https://$1/"); + url = url.replace(/^ssh:\/\//, "https://"); + return url; +} +function calculateBasicAuthHeader({ username = "", password = "" }) { + return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`; +} +async function forAwait(iterable, cb) { + const iter = getIterator(iterable); + while (true) { + const { value, done } = await iter.next(); + if (value) + await cb(value); + if (done) + break; + } + if (iter.return) + iter.return(); +} +async function collect(iterable) { + let size = 0; + const buffers = []; + await forAwait(iterable, (value) => { + buffers.push(value); + size += value.byteLength; + }); + const result = new Uint8Array(size); + let nextIndex = 0; + for (const buffer2 of buffers) { + result.set(buffer2, nextIndex); + nextIndex += buffer2.byteLength; + } + return result; +} +function extractAuthFromUrl(url) { + let userpass = url.match(/^https?:\/\/([^/]+)@/); + if (userpass == null) + return { url, auth: {} }; + userpass = userpass[1]; + const [username, password] = userpass.split(":"); + url = url.replace(`${userpass}@`, ""); + return { url, auth: { username, password } }; +} +function padHex(b, n) { + const s = n.toString(16); + return "0".repeat(b - s.length) + s; +} +var GitPktLine = class { + static flush() { + return Buffer.from("0000", "utf8"); + } + static delim() { + return Buffer.from("0001", "utf8"); + } + static encode(line) { + if (typeof line === "string") { + line = Buffer.from(line); + } + const length = line.length + 4; + const hexlength = padHex(4, length); + return Buffer.concat([Buffer.from(hexlength, "utf8"), line]); + } + static streamReader(stream) { + const reader = new StreamReader(stream); + return async function read() { + try { + let length = await reader.read(4); + if (length == null) + return true; + length = parseInt(length.toString("utf8"), 16); + if (length === 0) + return null; + if (length === 1) + return null; + const buffer2 = await reader.read(length - 4); + if (buffer2 == null) + return true; + return buffer2; + } catch (err) { + stream.error = err; + return true; + } + }; + } +}; +async function parseCapabilitiesV2(read) { + const capabilities2 = {}; + let line; + while (true) { + line = await read(); + if (line === true) + break; + if (line === null) + continue; + line = line.toString("utf8").replace(/\n$/, ""); + const i = line.indexOf("="); + if (i > -1) { + const key2 = line.slice(0, i); + const value = line.slice(i + 1); + capabilities2[key2] = value; + } else { + capabilities2[line] = true; + } + } + return { protocolVersion: 2, capabilities2 }; +} +async function parseRefsAdResponse(stream, { service }) { + const capabilities = /* @__PURE__ */ new Set(); + const refs = /* @__PURE__ */ new Map(); + const symrefs = /* @__PURE__ */ new Map(); + const read = GitPktLine.streamReader(stream); + let lineOne = await read(); + while (lineOne === null) + lineOne = await read(); + if (lineOne === true) + throw new EmptyServerResponseError(); + if (lineOne.includes("version 2")) { + return parseCapabilitiesV2(read); + } + if (lineOne.toString("utf8").replace(/\n$/, "") !== `# service=${service}`) { + throw new ParseError(`# service=${service}\\n`, lineOne.toString("utf8")); + } + let lineTwo = await read(); + while (lineTwo === null) + lineTwo = await read(); + if (lineTwo === true) + return { capabilities, refs, symrefs }; + lineTwo = lineTwo.toString("utf8"); + if (lineTwo.includes("version 2")) { + return parseCapabilitiesV2(read); + } + const [firstRef, capabilitiesLine] = splitAndAssert(lineTwo, "\0", "\\x00"); + capabilitiesLine.split(" ").map((x) => capabilities.add(x)); + const [ref, name] = splitAndAssert(firstRef, " ", " "); + refs.set(name, ref); + while (true) { + const line = await read(); + if (line === true) + break; + if (line !== null) { + const [ref2, name2] = splitAndAssert(line.toString("utf8"), " ", " "); + refs.set(name2, ref2); + } + } + for (const cap of capabilities) { + if (cap.startsWith("symref=")) { + const m = cap.match(/symref=([^:]+):(.*)/); + if (m.length === 3) { + symrefs.set(m[1], m[2]); + } + } + } + return { protocolVersion: 1, capabilities, refs, symrefs }; +} +function splitAndAssert(line, sep2, expected) { + const split = line.trim().split(sep2); + if (split.length !== 2) { + throw new ParseError( + `Two strings separated by '${expected}'`, + line.toString("utf8") + ); + } + return split; +} +var corsProxify = (corsProxy, url) => corsProxy.endsWith("?") ? `${corsProxy}${url}` : `${corsProxy}/${url.replace(/^https?:\/\//, "")}`; +var updateHeaders = (headers, auth) => { + if (auth.username || auth.password) { + headers.Authorization = calculateBasicAuthHeader(auth); + } + if (auth.headers) { + Object.assign(headers, auth.headers); + } +}; +var stringifyBody = async (res) => { + try { + const data = Buffer.from(await collect(res.body)); + const response = data.toString("utf8"); + const preview = response.length < 256 ? response : response.slice(0, 256) + "..."; + return { preview, response, data }; + } catch (e) { + return {}; + } +}; +var GitRemoteHTTP = class { + static async capabilities() { + return ["discover", "connect"]; + } + /** + * @param {Object} args + * @param {HttpClient} args.http + * @param {ProgressCallback} [args.onProgress] + * @param {AuthCallback} [args.onAuth] + * @param {AuthFailureCallback} [args.onAuthFailure] + * @param {AuthSuccessCallback} [args.onAuthSuccess] + * @param {string} [args.corsProxy] + * @param {string} args.service + * @param {string} args.url + * @param {Object} args.headers + * @param {1 | 2} args.protocolVersion - Git Protocol Version + */ + static async discover({ + http, + onProgress, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service, + url: _origUrl, + headers, + protocolVersion + }) { + let { url, auth } = extractAuthFromUrl(_origUrl); + const proxifiedURL = corsProxy ? corsProxify(corsProxy, url) : url; + if (auth.username || auth.password) { + headers.Authorization = calculateBasicAuthHeader(auth); + } + if (protocolVersion === 2) { + headers["Git-Protocol"] = "version=2"; + } + let res; + let tryAgain; + let providedAuthBefore = false; + do { + res = await http.request({ + onProgress, + method: "GET", + url: `${proxifiedURL}/info/refs?service=${service}`, + headers + }); + tryAgain = false; + if (res.statusCode === 401 || res.statusCode === 203) { + const getAuth = providedAuthBefore ? onAuthFailure : onAuth; + if (getAuth) { + auth = await getAuth(url, { + ...auth, + headers: { ...headers } + }); + if (auth && auth.cancel) { + throw new UserCanceledError(); + } else if (auth) { + updateHeaders(headers, auth); + providedAuthBefore = true; + tryAgain = true; + } + } + } else if (res.statusCode === 200 && providedAuthBefore && onAuthSuccess) { + await onAuthSuccess(url, auth); + } + } while (tryAgain); + if (res.statusCode !== 200) { + const { response } = await stringifyBody(res); + throw new HttpError(res.statusCode, res.statusMessage, response); + } + if (res.headers["content-type"] === `application/x-${service}-advertisement`) { + const remoteHTTP = await parseRefsAdResponse(res.body, { service }); + remoteHTTP.auth = auth; + return remoteHTTP; + } else { + const { preview, response, data } = await stringifyBody(res); + try { + const remoteHTTP = await parseRefsAdResponse([data], { service }); + remoteHTTP.auth = auth; + return remoteHTTP; + } catch (e) { + throw new SmartHttpError(preview, response); + } + } + } + /** + * @param {Object} args + * @param {HttpClient} args.http + * @param {ProgressCallback} [args.onProgress] + * @param {string} [args.corsProxy] + * @param {string} args.service + * @param {string} args.url + * @param {Object} [args.headers] + * @param {any} args.body + * @param {any} args.auth + */ + static async connect({ + http, + onProgress, + corsProxy, + service, + url, + auth, + body, + headers + }) { + const urlAuth = extractAuthFromUrl(url); + if (urlAuth) + url = urlAuth.url; + if (corsProxy) + url = corsProxify(corsProxy, url); + headers["content-type"] = `application/x-${service}-request`; + headers.accept = `application/x-${service}-result`; + updateHeaders(headers, auth); + const res = await http.request({ + onProgress, + method: "POST", + url: `${url}/${service}`, + body, + headers + }); + if (res.statusCode !== 200) { + const { response } = stringifyBody(res); + throw new HttpError(res.statusCode, res.statusMessage, response); + } + return res; + } +}; +function parseRemoteUrl({ url }) { + if (url.startsWith("git@")) { + return { + transport: "ssh", + address: url + }; + } + const matches = url.match(/(\w+)(:\/\/|::)(.*)/); + if (matches === null) + return; + if (matches[2] === "://") { + return { + transport: matches[1], + address: matches[0] + }; + } + if (matches[2] === "::") { + return { + transport: matches[1], + address: matches[3] + }; + } +} +var GitRemoteManager = class { + static getRemoteHelperFor({ url }) { + const remoteHelpers = /* @__PURE__ */ new Map(); + remoteHelpers.set("http", GitRemoteHTTP); + remoteHelpers.set("https", GitRemoteHTTP); + const parts = parseRemoteUrl({ url }); + if (!parts) { + throw new UrlParseError(url); + } + if (remoteHelpers.has(parts.transport)) { + return remoteHelpers.get(parts.transport); + } + throw new UnknownTransportError( + url, + parts.transport, + parts.transport === "ssh" ? translateSSHtoHTTP(url) : void 0 + ); + } +}; +var lock$1 = null; +var GitShallowManager = class { + static async read({ fs, gitdir }) { + if (lock$1 === null) + lock$1 = new import_async_lock.default(); + const filepath = join(gitdir, "shallow"); + const oids = /* @__PURE__ */ new Set(); + await lock$1.acquire(filepath, async function() { + const text2 = await fs.read(filepath, { encoding: "utf8" }); + if (text2 === null) + return oids; + if (text2.trim() === "") + return oids; + text2.trim().split("\n").map((oid) => oids.add(oid)); + }); + return oids; + } + static async write({ fs, gitdir, oids }) { + if (lock$1 === null) + lock$1 = new import_async_lock.default(); + const filepath = join(gitdir, "shallow"); + if (oids.size > 0) { + const text2 = [...oids].join("\n") + "\n"; + await lock$1.acquire(filepath, async function() { + await fs.write(filepath, text2, { + encoding: "utf8" + }); + }); + } else { + await lock$1.acquire(filepath, async function() { + await fs.rm(filepath); + }); + } + } +}; +async function hasObjectLoose({ fs, gitdir, oid }) { + const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`; + return fs.exists(`${gitdir}/${source}`); +} +async function hasObjectPacked({ + fs, + cache, + gitdir, + oid, + getExternalRefDelta +}) { + let list = await fs.readdir(join(gitdir, "objects/pack")); + list = list.filter((x) => x.endsWith(".idx")); + for (const filename of list) { + const indexFile = `${gitdir}/objects/pack/${filename}`; + const p = await readPackIndex({ + fs, + cache, + filename: indexFile, + getExternalRefDelta + }); + if (p.error) + throw new InternalError(p.error); + if (p.offsets.has(oid)) { + return true; + } + } + return false; +} +async function hasObject({ + fs, + cache, + gitdir, + oid, + format = "content" +}) { + const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 }); + let result = await hasObjectLoose({ fs, gitdir, oid }); + if (!result) { + result = await hasObjectPacked({ + fs, + cache, + gitdir, + oid, + getExternalRefDelta + }); + } + return result; +} +function emptyPackfile(pack) { + const pheader = "5041434b"; + const version2 = "00000002"; + const obCount = "00000000"; + const header = pheader + version2 + obCount; + return pack.slice(0, 12).toString("hex") === header; +} +function filterCapabilities(server, client) { + const serverNames = server.map((cap) => cap.split("=", 1)[0]); + return client.filter((cap) => { + const name = cap.split("=", 1)[0]; + return serverNames.includes(name); + }); +} +var pkg = { + name: "isomorphic-git", + version: "1.25.3", + agent: "git/isomorphic-git@1.25.3" +}; +var FIFO = class { + constructor() { + this._queue = []; + } + write(chunk) { + if (this._ended) { + throw Error("You cannot write to a FIFO that has already been ended!"); + } + if (this._waiting) { + const resolve = this._waiting; + this._waiting = null; + resolve({ value: chunk }); + } else { + this._queue.push(chunk); + } + } + end() { + this._ended = true; + if (this._waiting) { + const resolve = this._waiting; + this._waiting = null; + resolve({ done: true }); + } + } + destroy(err) { + this.error = err; + this.end(); + } + async next() { + if (this._queue.length > 0) { + return { value: this._queue.shift() }; + } + if (this._ended) { + return { done: true }; + } + if (this._waiting) { + throw Error( + "You cannot call read until the previous call to read has returned!" + ); + } + return new Promise((resolve) => { + this._waiting = resolve; + }); + } +}; +function findSplit(str) { + const r = str.indexOf("\r"); + const n = str.indexOf("\n"); + if (r === -1 && n === -1) + return -1; + if (r === -1) + return n + 1; + if (n === -1) + return r + 1; + if (n === r + 1) + return n + 1; + return Math.min(r, n) + 1; +} +function splitLines(input) { + const output = new FIFO(); + let tmp = ""; + (async () => { + await forAwait(input, (chunk) => { + chunk = chunk.toString("utf8"); + tmp += chunk; + while (true) { + const i = findSplit(tmp); + if (i === -1) + break; + output.write(tmp.slice(0, i)); + tmp = tmp.slice(i); + } + }); + if (tmp.length > 0) { + output.write(tmp); + } + output.end(); + })(); + return output; +} +var GitSideBand = class { + static demux(input) { + const read = GitPktLine.streamReader(input); + const packetlines = new FIFO(); + const packfile = new FIFO(); + const progress = new FIFO(); + const nextBit = async function() { + const line = await read(); + if (line === null) + return nextBit(); + if (line === true) { + packetlines.end(); + progress.end(); + input.error ? packfile.destroy(input.error) : packfile.end(); + return; + } + switch (line[0]) { + case 1: { + packfile.write(line.slice(1)); + break; + } + case 2: { + progress.write(line.slice(1)); + break; + } + case 3: { + const error = line.slice(1); + progress.write(error); + packetlines.end(); + progress.end(); + packfile.destroy(new Error(error.toString("utf8"))); + return; + } + default: { + packetlines.write(line); + } + } + nextBit(); + }; + nextBit(); + return { + packetlines, + packfile, + progress + }; + } + // static mux ({ + // protocol, // 'side-band' or 'side-band-64k' + // packetlines, + // packfile, + // progress, + // error + // }) { + // const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519 + // let output = new PassThrough() + // packetlines.on('data', data => { + // if (data === null) { + // output.write(GitPktLine.flush()) + // } else { + // output.write(GitPktLine.encode(data)) + // } + // }) + // let packfileWasEmpty = true + // let packfileEnded = false + // let progressEnded = false + // let errorEnded = false + // let goodbye = Buffer.concat([ + // GitPktLine.encode(Buffer.from('010A', 'hex')), + // GitPktLine.flush() + // ]) + // packfile + // .on('data', data => { + // packfileWasEmpty = false + // const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + // for (const buffer of buffers) { + // output.write( + // GitPktLine.encode(Buffer.concat([Buffer.from('01', 'hex'), buffer])) + // ) + // } + // }) + // .on('end', () => { + // packfileEnded = true + // if (!packfileWasEmpty) output.write(goodbye) + // if (progressEnded && errorEnded) output.end() + // }) + // progress + // .on('data', data => { + // const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + // for (const buffer of buffers) { + // output.write( + // GitPktLine.encode(Buffer.concat([Buffer.from('02', 'hex'), buffer])) + // ) + // } + // }) + // .on('end', () => { + // progressEnded = true + // if (packfileEnded && errorEnded) output.end() + // }) + // error + // .on('data', data => { + // const buffers = splitBuffer(data, MAX_PACKET_LENGTH) + // for (const buffer of buffers) { + // output.write( + // GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer])) + // ) + // } + // }) + // .on('end', () => { + // errorEnded = true + // if (progressEnded && packfileEnded) output.end() + // }) + // return output + // } +}; +async function parseUploadPackResponse(stream) { + const { packetlines, packfile, progress } = GitSideBand.demux(stream); + const shallows = []; + const unshallows = []; + const acks = []; + let nak = false; + let done = false; + return new Promise((resolve, reject) => { + forAwait(packetlines, (data) => { + const line = data.toString("utf8").trim(); + if (line.startsWith("shallow")) { + const oid = line.slice(-41).trim(); + if (oid.length !== 40) { + reject(new InvalidOidError(oid)); + } + shallows.push(oid); + } else if (line.startsWith("unshallow")) { + const oid = line.slice(-41).trim(); + if (oid.length !== 40) { + reject(new InvalidOidError(oid)); + } + unshallows.push(oid); + } else if (line.startsWith("ACK")) { + const [, oid, status2] = line.split(" "); + acks.push({ oid, status: status2 }); + if (!status2) + done = true; + } else if (line.startsWith("NAK")) { + nak = true; + done = true; + } else { + done = true; + nak = true; + } + if (done) { + stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress }); + } + }).finally(() => { + if (!done) { + stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress }); + } + }); + }); +} +function writeUploadPackRequest({ + capabilities = [], + wants = [], + haves = [], + shallows = [], + depth = null, + since = null, + exclude = [] +}) { + const packstream = []; + wants = [...new Set(wants)]; + let firstLineCapabilities = ` ${capabilities.join(" ")}`; + for (const oid of wants) { + packstream.push(GitPktLine.encode(`want ${oid}${firstLineCapabilities} +`)); + firstLineCapabilities = ""; + } + for (const oid of shallows) { + packstream.push(GitPktLine.encode(`shallow ${oid} +`)); + } + if (depth !== null) { + packstream.push(GitPktLine.encode(`deepen ${depth} +`)); + } + if (since !== null) { + packstream.push( + GitPktLine.encode(`deepen-since ${Math.floor(since.valueOf() / 1e3)} +`) + ); + } + for (const oid of exclude) { + packstream.push(GitPktLine.encode(`deepen-not ${oid} +`)); + } + packstream.push(GitPktLine.flush()); + for (const oid of haves) { + packstream.push(GitPktLine.encode(`have ${oid} +`)); + } + packstream.push(GitPktLine.encode(`done +`)); + return packstream; +} +async function _fetch({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + ref: _ref, + remoteRef: _remoteRef, + remote: _remote, + url: _url, + corsProxy, + depth = null, + since = null, + exclude = [], + relative: relative2 = false, + tags = false, + singleBranch = false, + headers = {}, + prune = false, + pruneTags = false +}) { + const ref = _ref || await _currentBranch({ fs, gitdir, test: true }); + const config = await GitConfigManager.get({ fs, gitdir }); + const remote = _remote || ref && await config.get(`branch.${ref}.remote`) || "origin"; + const url = _url || await config.get(`remote.${remote}.url`); + if (typeof url === "undefined") { + throw new MissingParameterError("remote OR url"); + } + const remoteRef = _remoteRef || ref && await config.get(`branch.${ref}.merge`) || _ref || "HEAD"; + if (corsProxy === void 0) { + corsProxy = await config.get("http.corsProxy"); + } + const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url }); + const remoteHTTP = await GitRemoteHTTP2.discover({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service: "git-upload-pack", + url, + headers, + protocolVersion: 1 + }); + const auth = remoteHTTP.auth; + const remoteRefs = remoteHTTP.refs; + if (remoteRefs.size === 0) { + return { + defaultBranch: null, + fetchHead: null, + fetchHeadDescription: null + }; + } + if (depth !== null && !remoteHTTP.capabilities.has("shallow")) { + throw new RemoteCapabilityError("shallow", "depth"); + } + if (since !== null && !remoteHTTP.capabilities.has("deepen-since")) { + throw new RemoteCapabilityError("deepen-since", "since"); + } + if (exclude.length > 0 && !remoteHTTP.capabilities.has("deepen-not")) { + throw new RemoteCapabilityError("deepen-not", "exclude"); + } + if (relative2 === true && !remoteHTTP.capabilities.has("deepen-relative")) { + throw new RemoteCapabilityError("deepen-relative", "relative"); + } + const { oid, fullref } = GitRefManager.resolveAgainstMap({ + ref: remoteRef, + map: remoteRefs + }); + for (const remoteRef2 of remoteRefs.keys()) { + if (remoteRef2 === fullref || remoteRef2 === "HEAD" || remoteRef2.startsWith("refs/heads/") || tags && remoteRef2.startsWith("refs/tags/")) { + continue; + } + remoteRefs.delete(remoteRef2); + } + const capabilities = filterCapabilities( + [...remoteHTTP.capabilities], + [ + "multi_ack_detailed", + "no-done", + "side-band-64k", + // Note: I removed 'thin-pack' option since our code doesn't "fatten" packfiles, + // which is necessary for compatibility with git. It was the cause of mysterious + // 'fatal: pack has [x] unresolved deltas' errors that plagued us for some time. + // isomorphic-git is perfectly happy with thin packfiles in .git/objects/pack but + // canonical git it turns out is NOT. + "ofs-delta", + `agent=${pkg.agent}` + ] + ); + if (relative2) + capabilities.push("deepen-relative"); + const wants = singleBranch ? [oid] : remoteRefs.values(); + const haveRefs = singleBranch ? [ref] : await GitRefManager.listRefs({ + fs, + gitdir, + filepath: `refs` + }); + let haves = []; + for (let ref2 of haveRefs) { + try { + ref2 = await GitRefManager.expand({ fs, gitdir, ref: ref2 }); + const oid2 = await GitRefManager.resolve({ fs, gitdir, ref: ref2 }); + if (await hasObject({ fs, cache, gitdir, oid: oid2 })) { + haves.push(oid2); + } + } catch (err) { + } + } + haves = [...new Set(haves)]; + const oids = await GitShallowManager.read({ fs, gitdir }); + const shallows = remoteHTTP.capabilities.has("shallow") ? [...oids] : []; + const packstream = writeUploadPackRequest({ + capabilities, + wants, + haves, + shallows, + depth, + since, + exclude + }); + const packbuffer = Buffer.from(await collect(packstream)); + const raw = await GitRemoteHTTP2.connect({ + http, + onProgress, + corsProxy, + service: "git-upload-pack", + url, + auth, + body: [packbuffer], + headers + }); + const response = await parseUploadPackResponse(raw.body); + if (raw.headers) { + response.headers = raw.headers; + } + for (const oid2 of response.shallows) { + if (!oids.has(oid2)) { + try { + const { object } = await _readObject({ fs, cache, gitdir, oid: oid2 }); + const commit2 = new GitCommit(object); + const hasParents = await Promise.all( + commit2.headers().parent.map((oid3) => hasObject({ fs, cache, gitdir, oid: oid3 })) + ); + const haveAllParents = hasParents.length === 0 || hasParents.every((has) => has); + if (!haveAllParents) { + oids.add(oid2); + } + } catch (err) { + oids.add(oid2); + } + } + } + for (const oid2 of response.unshallows) { + oids.delete(oid2); + } + await GitShallowManager.write({ fs, gitdir, oids }); + if (singleBranch) { + const refs = /* @__PURE__ */ new Map([[fullref, oid]]); + const symrefs = /* @__PURE__ */ new Map(); + let bail = 10; + let key2 = fullref; + while (bail--) { + const value = remoteHTTP.symrefs.get(key2); + if (value === void 0) + break; + symrefs.set(key2, value); + key2 = value; + } + const realRef = remoteRefs.get(key2); + if (realRef) { + refs.set(key2, realRef); + } + const { pruned } = await GitRefManager.updateRemoteRefs({ + fs, + gitdir, + remote, + refs, + symrefs, + tags, + prune + }); + if (prune) { + response.pruned = pruned; + } + } else { + const { pruned } = await GitRefManager.updateRemoteRefs({ + fs, + gitdir, + remote, + refs: remoteRefs, + symrefs: remoteHTTP.symrefs, + tags, + prune, + pruneTags + }); + if (prune) { + response.pruned = pruned; + } + } + response.HEAD = remoteHTTP.symrefs.get("HEAD"); + if (response.HEAD === void 0) { + const { oid: oid2 } = GitRefManager.resolveAgainstMap({ + ref: "HEAD", + map: remoteRefs + }); + for (const [key2, value] of remoteRefs.entries()) { + if (key2 !== "HEAD" && value === oid2) { + response.HEAD = key2; + break; + } + } + } + const noun = fullref.startsWith("refs/tags") ? "tag" : "branch"; + response.FETCH_HEAD = { + oid, + description: `${noun} '${abbreviateRef(fullref)}' of ${url}` + }; + if (onProgress || onMessage) { + const lines = splitLines(response.progress); + forAwait(lines, async (line) => { + if (onMessage) + await onMessage(line); + if (onProgress) { + const matches = line.match(/([^:]*).*\((\d+?)\/(\d+?)\)/); + if (matches) { + await onProgress({ + phase: matches[1].trim(), + loaded: parseInt(matches[2], 10), + total: parseInt(matches[3], 10) + }); + } + } + }); + } + const packfile = Buffer.from(await collect(response.packfile)); + if (raw.body.error) + throw raw.body.error; + const packfileSha = packfile.slice(-20).toString("hex"); + const res = { + defaultBranch: response.HEAD, + fetchHead: response.FETCH_HEAD.oid, + fetchHeadDescription: response.FETCH_HEAD.description + }; + if (response.headers) { + res.headers = response.headers; + } + if (prune) { + res.pruned = response.pruned; + } + if (packfileSha !== "" && !emptyPackfile(packfile)) { + res.packfile = `objects/pack/pack-${packfileSha}.pack`; + const fullpath = join(gitdir, res.packfile); + await fs.write(fullpath, packfile); + const getExternalRefDelta = (oid2) => _readObject({ fs, cache, gitdir, oid: oid2 }); + const idx = await GitPackIndex.fromPack({ + pack: packfile, + getExternalRefDelta, + onProgress + }); + await fs.write(fullpath.replace(/\.pack$/, ".idx"), await idx.toBuffer()); + } + return res; +} +async function _init({ + fs, + bare = false, + dir, + gitdir = bare ? dir : join(dir, ".git"), + defaultBranch = "master" +}) { + if (await fs.exists(gitdir + "/config")) + return; + let folders = [ + "hooks", + "info", + "objects/info", + "objects/pack", + "refs/heads", + "refs/tags" + ]; + folders = folders.map((dir2) => gitdir + "/" + dir2); + for (const folder of folders) { + await fs.mkdir(folder); + } + await fs.write( + gitdir + "/config", + `[core] + repositoryformatversion = 0 + filemode = false + bare = ${bare} +` + (bare ? "" : " logallrefupdates = true\n") + " symlinks = false\n ignorecase = true\n" + ); + await fs.write(gitdir + "/HEAD", `ref: refs/heads/${defaultBranch} +`); +} +async function _clone({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir, + url, + corsProxy, + ref, + remote, + depth, + since, + exclude, + relative: relative2, + singleBranch, + noCheckout, + noTags, + headers +}) { + try { + await _init({ fs, gitdir }); + await _addRemote({ fs, gitdir, remote, url, force: false }); + if (corsProxy) { + const config = await GitConfigManager.get({ fs, gitdir }); + await config.set(`http.corsProxy`, corsProxy); + await GitConfigManager.save({ fs, gitdir, config }); + } + const { defaultBranch, fetchHead } = await _fetch({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + ref, + remote, + corsProxy, + depth, + since, + exclude, + relative: relative2, + singleBranch, + headers, + tags: !noTags + }); + if (fetchHead === null) + return; + ref = ref || defaultBranch; + ref = ref.replace("refs/heads/", ""); + await _checkout({ + fs, + cache, + onProgress, + dir, + gitdir, + ref, + remote, + noCheckout + }); + } catch (err) { + await fs.rmdir(gitdir, { recursive: true, maxRetries: 10 }).catch(() => void 0); + throw err; + } +} +async function clone({ + fs, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir = join(dir, ".git"), + url, + corsProxy = void 0, + ref = void 0, + remote = "origin", + depth = void 0, + since = void 0, + exclude = [], + relative: relative2 = false, + singleBranch = false, + noCheckout = false, + noTags = false, + headers = {}, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("http", http); + assertParameter("gitdir", gitdir); + if (!noCheckout) { + assertParameter("dir", dir); + } + assertParameter("url", url); + return await _clone({ + fs: new FileSystem(fs), + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir, + url, + corsProxy, + ref, + remote, + depth, + since, + exclude, + relative: relative2, + singleBranch, + noCheckout, + noTags, + headers + }); + } catch (err) { + err.caller = "git.clone"; + throw err; + } +} +async function commit({ + fs: _fs, + onSign, + dir, + gitdir = join(dir, ".git"), + message, + author: _author, + committer: _committer, + signingKey, + dryRun = false, + noUpdateBranch = false, + ref, + parent, + tree, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("message", message); + if (signingKey) { + assertParameter("onSign", onSign); + } + const fs = new FileSystem(_fs); + const author = await normalizeAuthorObject({ fs, gitdir, author: _author }); + if (!author) + throw new MissingNameError("author"); + const committer = await normalizeCommitterObject({ + fs, + gitdir, + author, + committer: _committer + }); + if (!committer) + throw new MissingNameError("committer"); + return await _commit({ + fs, + cache, + onSign, + gitdir, + message, + author, + committer, + signingKey, + dryRun, + noUpdateBranch, + ref, + parent, + tree + }); + } catch (err) { + err.caller = "git.commit"; + throw err; + } +} +async function currentBranch({ + fs, + dir, + gitdir = join(dir, ".git"), + fullname = false, + test = false +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + return await _currentBranch({ + fs: new FileSystem(fs), + gitdir, + fullname, + test + }); + } catch (err) { + err.caller = "git.currentBranch"; + throw err; + } +} +async function _deleteBranch({ fs, gitdir, ref }) { + ref = ref.startsWith("refs/heads/") ? ref : `refs/heads/${ref}`; + const exist = await GitRefManager.exists({ fs, gitdir, ref }); + if (!exist) { + throw new NotFoundError(ref); + } + const fullRef = await GitRefManager.expand({ fs, gitdir, ref }); + const currentRef = await _currentBranch({ fs, gitdir, fullname: true }); + if (fullRef === currentRef) { + const value = await GitRefManager.resolve({ fs, gitdir, ref: fullRef }); + await GitRefManager.writeRef({ fs, gitdir, ref: "HEAD", value }); + } + await GitRefManager.deleteRef({ fs, gitdir, ref: fullRef }); +} +async function deleteBranch({ + fs, + dir, + gitdir = join(dir, ".git"), + ref +}) { + try { + assertParameter("fs", fs); + assertParameter("ref", ref); + return await _deleteBranch({ + fs: new FileSystem(fs), + gitdir, + ref + }); + } catch (err) { + err.caller = "git.deleteBranch"; + throw err; + } +} +async function deleteRef({ fs, dir, gitdir = join(dir, ".git"), ref }) { + try { + assertParameter("fs", fs); + assertParameter("ref", ref); + await GitRefManager.deleteRef({ fs: new FileSystem(fs), gitdir, ref }); + } catch (err) { + err.caller = "git.deleteRef"; + throw err; + } +} +async function _deleteRemote({ fs, gitdir, remote }) { + const config = await GitConfigManager.get({ fs, gitdir }); + await config.deleteSection("remote", remote); + await GitConfigManager.save({ fs, gitdir, config }); +} +async function deleteRemote({ + fs, + dir, + gitdir = join(dir, ".git"), + remote +}) { + try { + assertParameter("fs", fs); + assertParameter("remote", remote); + return await _deleteRemote({ + fs: new FileSystem(fs), + gitdir, + remote + }); + } catch (err) { + err.caller = "git.deleteRemote"; + throw err; + } +} +async function _deleteTag({ fs, gitdir, ref }) { + ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`; + await GitRefManager.deleteRef({ fs, gitdir, ref }); +} +async function deleteTag({ fs, dir, gitdir = join(dir, ".git"), ref }) { + try { + assertParameter("fs", fs); + assertParameter("ref", ref); + return await _deleteTag({ + fs: new FileSystem(fs), + gitdir, + ref + }); + } catch (err) { + err.caller = "git.deleteTag"; + throw err; + } +} +async function expandOidLoose({ fs, gitdir, oid: short }) { + const prefix = short.slice(0, 2); + const objectsSuffixes = await fs.readdir(`${gitdir}/objects/${prefix}`); + return objectsSuffixes.map((suffix) => `${prefix}${suffix}`).filter((_oid) => _oid.startsWith(short)); +} +async function expandOidPacked({ + fs, + cache, + gitdir, + oid: short, + getExternalRefDelta +}) { + const results = []; + let list = await fs.readdir(join(gitdir, "objects/pack")); + list = list.filter((x) => x.endsWith(".idx")); + for (const filename of list) { + const indexFile = `${gitdir}/objects/pack/${filename}`; + const p = await readPackIndex({ + fs, + cache, + filename: indexFile, + getExternalRefDelta + }); + if (p.error) + throw new InternalError(p.error); + for (const oid of p.offsets.keys()) { + if (oid.startsWith(short)) + results.push(oid); + } + } + return results; +} +async function _expandOid({ fs, cache, gitdir, oid: short }) { + const getExternalRefDelta = (oid) => _readObject({ fs, cache, gitdir, oid }); + const results = await expandOidLoose({ fs, gitdir, oid: short }); + const packedOids = await expandOidPacked({ + fs, + cache, + gitdir, + oid: short, + getExternalRefDelta + }); + for (const packedOid of packedOids) { + if (results.indexOf(packedOid) === -1) { + results.push(packedOid); + } + } + if (results.length === 1) { + return results[0]; + } + if (results.length > 1) { + throw new AmbiguousError("oids", short, results); + } + throw new NotFoundError(`an object matching "${short}"`); +} +async function expandOid({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + return await _expandOid({ + fs: new FileSystem(fs), + cache, + gitdir, + oid + }); + } catch (err) { + err.caller = "git.expandOid"; + throw err; + } +} +async function expandRef({ fs, dir, gitdir = join(dir, ".git"), ref }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + return await GitRefManager.expand({ + fs: new FileSystem(fs), + gitdir, + ref + }); + } catch (err) { + err.caller = "git.expandRef"; + throw err; + } +} +async function _findMergeBase({ fs, cache, gitdir, oids }) { + const visits = {}; + const passes = oids.length; + let heads = oids.map((oid, index2) => ({ index: index2, oid })); + while (heads.length) { + const result = /* @__PURE__ */ new Set(); + for (const { oid, index: index2 } of heads) { + if (!visits[oid]) + visits[oid] = /* @__PURE__ */ new Set(); + visits[oid].add(index2); + if (visits[oid].size === passes) { + result.add(oid); + } + } + if (result.size > 0) { + return [...result]; + } + const newheads = /* @__PURE__ */ new Map(); + for (const { oid, index: index2 } of heads) { + try { + const { object } = await _readObject({ fs, cache, gitdir, oid }); + const commit2 = GitCommit.from(object); + const { parent } = commit2.parseHeaders(); + for (const oid2 of parent) { + if (!visits[oid2] || !visits[oid2].has(index2)) { + newheads.set(oid2 + ":" + index2, { oid: oid2, index: index2 }); + } + } + } catch (err) { + } + } + heads = Array.from(newheads.values()); + } + return []; +} +var LINEBREAKS = /^.*(\r?\n|$)/gm; +function mergeFile({ branches, contents }) { + const ourName = branches[1]; + const theirName = branches[2]; + const baseContent = contents[0]; + const ourContent = contents[1]; + const theirContent = contents[2]; + const ours = ourContent.match(LINEBREAKS); + const base = baseContent.match(LINEBREAKS); + const theirs = theirContent.match(LINEBREAKS); + const result = (0, import_diff3.default)(ours, base, theirs); + const markerSize = 7; + let mergedText = ""; + let cleanMerge = true; + for (const item of result) { + if (item.ok) { + mergedText += item.ok.join(""); + } + if (item.conflict) { + cleanMerge = false; + mergedText += `${"<".repeat(markerSize)} ${ourName} +`; + mergedText += item.conflict.a.join(""); + mergedText += `${"=".repeat(markerSize)} +`; + mergedText += item.conflict.b.join(""); + mergedText += `${">".repeat(markerSize)} ${theirName} +`; + } + } + return { cleanMerge, mergedText }; +} +async function mergeTree({ + fs, + cache, + dir, + gitdir = join(dir, ".git"), + index: index2, + ourOid, + baseOid, + theirOid, + ourName = "ours", + baseName = "base", + theirName = "theirs", + dryRun = false, + abortOnConflict = true, + mergeDriver +}) { + const ourTree = TREE({ ref: ourOid }); + const baseTree = TREE({ ref: baseOid }); + const theirTree = TREE({ ref: theirOid }); + const unmergedFiles = []; + const bothModified = []; + const deleteByUs = []; + const deleteByTheirs = []; + const results = await _walk({ + fs, + cache, + dir, + gitdir, + trees: [ourTree, baseTree, theirTree], + map: async function(filepath, [ours, base, theirs]) { + const path2 = basename(filepath); + const ourChange = await modified(ours, base); + const theirChange = await modified(theirs, base); + switch (`${ourChange}-${theirChange}`) { + case "false-false": { + return { + mode: await base.mode(), + path: path2, + oid: await base.oid(), + type: await base.type() + }; + } + case "false-true": { + return theirs ? { + mode: await theirs.mode(), + path: path2, + oid: await theirs.oid(), + type: await theirs.type() + } : void 0; + } + case "true-false": { + return ours ? { + mode: await ours.mode(), + path: path2, + oid: await ours.oid(), + type: await ours.type() + } : void 0; + } + case "true-true": { + if (ours && base && theirs && await ours.type() === "blob" && await base.type() === "blob" && await theirs.type() === "blob") { + return mergeBlobs({ + fs, + gitdir, + path: path2, + ours, + base, + theirs, + ourName, + baseName, + theirName, + mergeDriver + }).then(async (r) => { + if (!r.cleanMerge) { + unmergedFiles.push(filepath); + bothModified.push(filepath); + if (!abortOnConflict) { + const baseOid2 = await base.oid(); + const ourOid2 = await ours.oid(); + const theirOid2 = await theirs.oid(); + index2.delete({ filepath }); + index2.insert({ filepath, oid: baseOid2, stage: 1 }); + index2.insert({ filepath, oid: ourOid2, stage: 2 }); + index2.insert({ filepath, oid: theirOid2, stage: 3 }); + } + } else if (!abortOnConflict) { + index2.insert({ filepath, oid: r.mergeResult.oid, stage: 0 }); + } + return r.mergeResult; + }); + } + if (base && !ours && theirs && await base.type() === "blob" && await theirs.type() === "blob") { + unmergedFiles.push(filepath); + deleteByUs.push(filepath); + if (!abortOnConflict) { + const baseOid2 = await base.oid(); + const theirOid2 = await theirs.oid(); + index2.delete({ filepath }); + index2.insert({ filepath, oid: baseOid2, stage: 1 }); + index2.insert({ filepath, oid: theirOid2, stage: 3 }); + } + return { + mode: await theirs.mode(), + oid: await theirs.oid(), + type: "blob", + path: path2 + }; + } + if (base && ours && !theirs && await base.type() === "blob" && await ours.type() === "blob") { + unmergedFiles.push(filepath); + deleteByTheirs.push(filepath); + if (!abortOnConflict) { + const baseOid2 = await base.oid(); + const ourOid2 = await ours.oid(); + index2.delete({ filepath }); + index2.insert({ filepath, oid: baseOid2, stage: 1 }); + index2.insert({ filepath, oid: ourOid2, stage: 2 }); + } + return { + mode: await ours.mode(), + oid: await ours.oid(), + type: "blob", + path: path2 + }; + } + if (base && !ours && !theirs && await base.type() === "blob") { + return void 0; + } + throw new MergeNotSupportedError(); + } + } + }, + /** + * @param {TreeEntry} [parent] + * @param {Array} children + */ + reduce: unmergedFiles.length !== 0 && (!dir || abortOnConflict) ? void 0 : async (parent, children2) => { + const entries = children2.filter(Boolean); + if (!parent) + return; + if (parent && parent.type === "tree" && entries.length === 0) + return; + if (entries.length > 0) { + const tree = new GitTree(entries); + const object = tree.toObject(); + const oid = await _writeObject({ + fs, + gitdir, + type: "tree", + object, + dryRun + }); + parent.oid = oid; + } + return parent; + } + }); + if (unmergedFiles.length !== 0) { + if (dir && !abortOnConflict) { + await _walk({ + fs, + cache, + dir, + gitdir, + trees: [TREE({ ref: results.oid })], + map: async function(filepath, [entry]) { + const path2 = `${dir}/${filepath}`; + if (await entry.type() === "blob") { + const mode = await entry.mode(); + const content = new TextDecoder().decode(await entry.content()); + await fs.write(path2, content, { mode }); + } + return true; + } + }); + } + return new MergeConflictError( + unmergedFiles, + bothModified, + deleteByUs, + deleteByTheirs + ); + } + return results.oid; +} +async function mergeBlobs({ + fs, + gitdir, + path: path2, + ours, + base, + theirs, + ourName, + theirName, + baseName, + dryRun, + mergeDriver = mergeFile +}) { + const type = "blob"; + const mode = await base.mode() === await ours.mode() ? await theirs.mode() : await ours.mode(); + if (await ours.oid() === await theirs.oid()) { + return { + cleanMerge: true, + mergeResult: { mode, path: path2, oid: await ours.oid(), type } + }; + } + if (await ours.oid() === await base.oid()) { + return { + cleanMerge: true, + mergeResult: { mode, path: path2, oid: await theirs.oid(), type } + }; + } + if (await theirs.oid() === await base.oid()) { + return { + cleanMerge: true, + mergeResult: { mode, path: path2, oid: await ours.oid(), type } + }; + } + const ourContent = Buffer.from(await ours.content()).toString("utf8"); + const baseContent = Buffer.from(await base.content()).toString("utf8"); + const theirContent = Buffer.from(await theirs.content()).toString("utf8"); + const { mergedText, cleanMerge } = await mergeDriver({ + branches: [baseName, ourName, theirName], + contents: [baseContent, ourContent, theirContent], + path: path2 + }); + const oid = await _writeObject({ + fs, + gitdir, + type: "blob", + object: Buffer.from(mergedText, "utf8"), + dryRun + }); + return { cleanMerge, mergeResult: { mode, path: path2, oid, type } }; +} +async function _merge({ + fs, + cache, + dir, + gitdir, + ours, + theirs, + fastForward: fastForward2 = true, + fastForwardOnly = false, + dryRun = false, + noUpdateBranch = false, + abortOnConflict = true, + message, + author, + committer, + signingKey, + onSign, + mergeDriver +}) { + if (ours === void 0) { + ours = await _currentBranch({ fs, gitdir, fullname: true }); + } + ours = await GitRefManager.expand({ + fs, + gitdir, + ref: ours + }); + theirs = await GitRefManager.expand({ + fs, + gitdir, + ref: theirs + }); + const ourOid = await GitRefManager.resolve({ + fs, + gitdir, + ref: ours + }); + const theirOid = await GitRefManager.resolve({ + fs, + gitdir, + ref: theirs + }); + const baseOids = await _findMergeBase({ + fs, + cache, + gitdir, + oids: [ourOid, theirOid] + }); + if (baseOids.length !== 1) { + throw new MergeNotSupportedError(); + } + const baseOid = baseOids[0]; + if (baseOid === theirOid) { + return { + oid: ourOid, + alreadyMerged: true + }; + } + if (fastForward2 && baseOid === ourOid) { + if (!dryRun && !noUpdateBranch) { + await GitRefManager.writeRef({ fs, gitdir, ref: ours, value: theirOid }); + } + return { + oid: theirOid, + fastForward: true + }; + } else { + if (fastForwardOnly) { + throw new FastForwardError(); + } + const tree = await GitIndexManager.acquire( + { fs, gitdir, cache, allowUnmerged: false }, + async (index2) => { + return mergeTree({ + fs, + cache, + dir, + gitdir, + index: index2, + ourOid, + theirOid, + baseOid, + ourName: abbreviateRef(ours), + baseName: "base", + theirName: abbreviateRef(theirs), + dryRun, + abortOnConflict, + mergeDriver + }); + } + ); + if (tree instanceof MergeConflictError) + throw tree; + if (!message) { + message = `Merge branch '${abbreviateRef(theirs)}' into ${abbreviateRef( + ours + )}`; + } + const oid = await _commit({ + fs, + cache, + gitdir, + message, + ref: ours, + tree, + parent: [ourOid, theirOid], + author, + committer, + signingKey, + onSign, + dryRun, + noUpdateBranch + }); + return { + oid, + tree, + mergeCommit: true + }; + } +} +async function _pull({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir, + ref, + url, + remote, + remoteRef, + prune, + pruneTags, + fastForward: fastForward2, + fastForwardOnly, + corsProxy, + singleBranch, + headers, + author, + committer, + signingKey +}) { + try { + if (!ref) { + const head = await _currentBranch({ fs, gitdir }); + if (!head) { + throw new MissingParameterError("ref"); + } + ref = head; + } + const { fetchHead, fetchHeadDescription } = await _fetch({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + corsProxy, + ref, + url, + remote, + remoteRef, + singleBranch, + headers, + prune, + pruneTags + }); + await _merge({ + fs, + cache, + gitdir, + ours: ref, + theirs: fetchHead, + fastForward: fastForward2, + fastForwardOnly, + message: `Merge ${fetchHeadDescription}`, + author, + committer, + signingKey, + dryRun: false, + noUpdateBranch: false + }); + await _checkout({ + fs, + cache, + onProgress, + dir, + gitdir, + ref, + remote, + noCheckout: false + }); + } catch (err) { + err.caller = "git.pull"; + throw err; + } +} +async function fastForward({ + fs, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir = join(dir, ".git"), + ref, + url, + remote, + remoteRef, + corsProxy, + singleBranch, + headers = {}, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("http", http); + assertParameter("gitdir", gitdir); + const thisWillNotBeUsed = { + name: "", + email: "", + timestamp: Date.now(), + timezoneOffset: 0 + }; + return await _pull({ + fs: new FileSystem(fs), + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir, + ref, + url, + remote, + remoteRef, + fastForwardOnly: true, + corsProxy, + singleBranch, + headers, + author: thisWillNotBeUsed, + committer: thisWillNotBeUsed + }); + } catch (err) { + err.caller = "git.fastForward"; + throw err; + } +} +async function fetch({ + fs, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir = join(dir, ".git"), + ref, + remote, + remoteRef, + url, + corsProxy, + depth = null, + since = null, + exclude = [], + relative: relative2 = false, + tags = false, + singleBranch = false, + headers = {}, + prune = false, + pruneTags = false, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("http", http); + assertParameter("gitdir", gitdir); + return await _fetch({ + fs: new FileSystem(fs), + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + ref, + remote, + remoteRef, + url, + corsProxy, + depth, + since, + exclude, + relative: relative2, + tags, + singleBranch, + headers, + prune, + pruneTags + }); + } catch (err) { + err.caller = "git.fetch"; + throw err; + } +} +async function findMergeBase({ + fs, + dir, + gitdir = join(dir, ".git"), + oids, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oids", oids); + return await _findMergeBase({ + fs: new FileSystem(fs), + cache, + gitdir, + oids + }); + } catch (err) { + err.caller = "git.findMergeBase"; + throw err; + } +} +async function _findRoot({ fs, filepath }) { + if (await fs.exists(join(filepath, ".git"))) { + return filepath; + } else { + const parent = dirname(filepath); + if (parent === filepath) { + throw new NotFoundError(`git root for ${filepath}`); + } + return _findRoot({ fs, filepath: parent }); + } +} +async function findRoot({ fs, filepath }) { + try { + assertParameter("fs", fs); + assertParameter("filepath", filepath); + return await _findRoot({ fs: new FileSystem(fs), filepath }); + } catch (err) { + err.caller = "git.findRoot"; + throw err; + } +} +async function getConfig({ fs, dir, gitdir = join(dir, ".git"), path: path2 }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("path", path2); + return await _getConfig({ + fs: new FileSystem(fs), + gitdir, + path: path2 + }); + } catch (err) { + err.caller = "git.getConfig"; + throw err; + } +} +async function _getConfigAll({ fs, gitdir, path: path2 }) { + const config = await GitConfigManager.get({ fs, gitdir }); + return config.getall(path2); +} +async function getConfigAll({ + fs, + dir, + gitdir = join(dir, ".git"), + path: path2 +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("path", path2); + return await _getConfigAll({ + fs: new FileSystem(fs), + gitdir, + path: path2 + }); + } catch (err) { + err.caller = "git.getConfigAll"; + throw err; + } +} +async function getRemoteInfo({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + url, + headers = {}, + forPush = false +}) { + try { + assertParameter("http", http); + assertParameter("url", url); + const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url }); + const remote = await GitRemoteHTTP2.discover({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service: forPush ? "git-receive-pack" : "git-upload-pack", + url, + headers, + protocolVersion: 1 + }); + const result = { + capabilities: [...remote.capabilities] + }; + for (const [ref, oid] of remote.refs) { + const parts = ref.split("/"); + const last2 = parts.pop(); + let o = result; + for (const part of parts) { + o[part] = o[part] || {}; + o = o[part]; + } + o[last2] = oid; + } + for (const [symref, ref] of remote.symrefs) { + const parts = symref.split("/"); + const last2 = parts.pop(); + let o = result; + for (const part of parts) { + o[part] = o[part] || {}; + o = o[part]; + } + o[last2] = ref; + } + return result; + } catch (err) { + err.caller = "git.getRemoteInfo"; + throw err; + } +} +function formatInfoRefs(remote, prefix, symrefs, peelTags) { + const refs = []; + for (const [key2, value] of remote.refs) { + if (prefix && !key2.startsWith(prefix)) + continue; + if (key2.endsWith("^{}")) { + if (peelTags) { + const _key = key2.replace("^{}", ""); + const last2 = refs[refs.length - 1]; + const r = last2.ref === _key ? last2 : refs.find((x) => x.ref === _key); + if (r === void 0) { + throw new Error("I did not expect this to happen"); + } + r.peeled = value; + } + continue; + } + const ref = { ref: key2, oid: value }; + if (symrefs) { + if (remote.symrefs.has(key2)) { + ref.target = remote.symrefs.get(key2); + } + } + refs.push(ref); + } + return refs; +} +async function getRemoteInfo2({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + url, + headers = {}, + forPush = false, + protocolVersion = 2 +}) { + try { + assertParameter("http", http); + assertParameter("url", url); + const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url }); + const remote = await GitRemoteHTTP2.discover({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service: forPush ? "git-receive-pack" : "git-upload-pack", + url, + headers, + protocolVersion + }); + if (remote.protocolVersion === 2) { + return { + protocolVersion: remote.protocolVersion, + capabilities: remote.capabilities2 + }; + } + const capabilities = {}; + for (const cap of remote.capabilities) { + const [key2, value] = cap.split("="); + if (value) { + capabilities[key2] = value; + } else { + capabilities[key2] = true; + } + } + return { + protocolVersion: 1, + capabilities, + refs: formatInfoRefs(remote, void 0, true, true) + }; + } catch (err) { + err.caller = "git.getRemoteInfo2"; + throw err; + } +} +async function hashObject({ + type, + object, + format = "content", + oid = void 0 +}) { + if (format !== "deflated") { + if (format !== "wrapped") { + object = GitObject.wrap({ type, object }); + } + oid = await shasum(object); + } + return { oid, object }; +} +async function hashBlob({ object }) { + try { + assertParameter("object", object); + if (typeof object === "string") { + object = Buffer.from(object, "utf8"); + } else { + object = Buffer.from(object); + } + const type = "blob"; + const { oid, object: _object } = await hashObject({ + type: "blob", + format: "content", + object + }); + return { oid, type, object: new Uint8Array(_object), format: "wrapped" }; + } catch (err) { + err.caller = "git.hashBlob"; + throw err; + } +} +async function _indexPack({ + fs, + cache, + onProgress, + dir, + gitdir, + filepath +}) { + try { + filepath = join(dir, filepath); + const pack = await fs.read(filepath); + const getExternalRefDelta = (oid) => _readObject({ fs, cache, gitdir, oid }); + const idx = await GitPackIndex.fromPack({ + pack, + getExternalRefDelta, + onProgress + }); + await fs.write(filepath.replace(/\.pack$/, ".idx"), await idx.toBuffer()); + return { + oids: [...idx.hashes] + }; + } catch (err) { + err.caller = "git.indexPack"; + throw err; + } +} +async function indexPack({ + fs, + onProgress, + dir, + gitdir = join(dir, ".git"), + filepath, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("dir", dir); + assertParameter("gitdir", dir); + assertParameter("filepath", filepath); + return await _indexPack({ + fs: new FileSystem(fs), + cache, + onProgress, + dir, + gitdir, + filepath + }); + } catch (err) { + err.caller = "git.indexPack"; + throw err; + } +} +async function init({ + fs, + bare = false, + dir, + gitdir = bare ? dir : join(dir, ".git"), + defaultBranch = "master" +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + if (!bare) { + assertParameter("dir", dir); + } + return await _init({ + fs: new FileSystem(fs), + bare, + dir, + gitdir, + defaultBranch + }); + } catch (err) { + err.caller = "git.init"; + throw err; + } +} +async function _isDescendent({ + fs, + cache, + gitdir, + oid, + ancestor, + depth +}) { + const shallows = await GitShallowManager.read({ fs, gitdir }); + if (!oid) { + throw new MissingParameterError("oid"); + } + if (!ancestor) { + throw new MissingParameterError("ancestor"); + } + if (oid === ancestor) + return false; + const queue = [oid]; + const visited = /* @__PURE__ */ new Set(); + let searchdepth = 0; + while (queue.length) { + if (searchdepth++ === depth) { + throw new MaxDepthError(depth); + } + const oid2 = queue.shift(); + const { type, object } = await _readObject({ + fs, + cache, + gitdir, + oid: oid2 + }); + if (type !== "commit") { + throw new ObjectTypeError(oid2, type, "commit"); + } + const commit2 = GitCommit.from(object).parse(); + for (const parent of commit2.parent) { + if (parent === ancestor) + return true; + } + if (!shallows.has(oid2)) { + for (const parent of commit2.parent) { + if (!visited.has(parent)) { + queue.push(parent); + visited.add(parent); + } + } + } + } + return false; +} +async function isDescendent({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + ancestor, + depth = -1, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + assertParameter("ancestor", ancestor); + return await _isDescendent({ + fs: new FileSystem(fs), + cache, + gitdir, + oid, + ancestor, + depth + }); + } catch (err) { + err.caller = "git.isDescendent"; + throw err; + } +} +async function isIgnored({ + fs, + dir, + gitdir = join(dir, ".git"), + filepath +}) { + try { + assertParameter("fs", fs); + assertParameter("dir", dir); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + return GitIgnoreManager.isIgnored({ + fs: new FileSystem(fs), + dir, + gitdir, + filepath + }); + } catch (err) { + err.caller = "git.isIgnored"; + throw err; + } +} +async function listBranches({ + fs, + dir, + gitdir = join(dir, ".git"), + remote +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + return GitRefManager.listBranches({ + fs: new FileSystem(fs), + gitdir, + remote + }); + } catch (err) { + err.caller = "git.listBranches"; + throw err; + } +} +async function _listFiles({ fs, gitdir, ref, cache }) { + if (ref) { + const oid = await GitRefManager.resolve({ gitdir, fs, ref }); + const filenames = []; + await accumulateFilesFromOid({ + fs, + cache, + gitdir, + oid, + filenames, + prefix: "" + }); + return filenames; + } else { + return GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + return index2.entries.map((x) => x.path); + }); + } +} +async function accumulateFilesFromOid({ + fs, + cache, + gitdir, + oid, + filenames, + prefix +}) { + const { tree } = await _readTree({ fs, cache, gitdir, oid }); + for (const entry of tree) { + if (entry.type === "tree") { + await accumulateFilesFromOid({ + fs, + cache, + gitdir, + oid: entry.oid, + filenames, + prefix: join(prefix, entry.path) + }); + } else { + filenames.push(join(prefix, entry.path)); + } + } +} +async function listFiles({ + fs, + dir, + gitdir = join(dir, ".git"), + ref, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + return await _listFiles({ + fs: new FileSystem(fs), + cache, + gitdir, + ref + }); + } catch (err) { + err.caller = "git.listFiles"; + throw err; + } +} +async function _listNotes({ fs, cache, gitdir, ref }) { + let parent; + try { + parent = await GitRefManager.resolve({ gitdir, fs, ref }); + } catch (err) { + if (err instanceof NotFoundError) { + return []; + } + } + const result = await _readTree({ + fs, + cache, + gitdir, + oid: parent + }); + const notes = result.tree.map((entry) => ({ + target: entry.path, + note: entry.oid + })); + return notes; +} +async function listNotes({ + fs, + dir, + gitdir = join(dir, ".git"), + ref = "refs/notes/commits", + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + return await _listNotes({ + fs: new FileSystem(fs), + cache, + gitdir, + ref + }); + } catch (err) { + err.caller = "git.listNotes"; + throw err; + } +} +async function _listRemotes({ fs, gitdir }) { + const config = await GitConfigManager.get({ fs, gitdir }); + const remoteNames = await config.getSubsections("remote"); + const remotes = Promise.all( + remoteNames.map(async (remote) => { + const url = await config.get(`remote.${remote}.url`); + return { remote, url }; + }) + ); + return remotes; +} +async function listRemotes({ fs, dir, gitdir = join(dir, ".git") }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + return await _listRemotes({ + fs: new FileSystem(fs), + gitdir + }); + } catch (err) { + err.caller = "git.listRemotes"; + throw err; + } +} +async function parseListRefsResponse(stream) { + const read = GitPktLine.streamReader(stream); + const refs = []; + let line; + while (true) { + line = await read(); + if (line === true) + break; + if (line === null) + continue; + line = line.toString("utf8").replace(/\n$/, ""); + const [oid, ref, ...attrs] = line.split(" "); + const r = { ref, oid }; + for (const attr2 of attrs) { + const [name, value] = attr2.split(":"); + if (name === "symref-target") { + r.target = value; + } else if (name === "peeled") { + r.peeled = value; + } + } + refs.push(r); + } + return refs; +} +async function writeListRefsRequest({ prefix, symrefs, peelTags }) { + const packstream = []; + packstream.push(GitPktLine.encode("command=ls-refs\n")); + packstream.push(GitPktLine.encode(`agent=${pkg.agent} +`)); + if (peelTags || symrefs || prefix) { + packstream.push(GitPktLine.delim()); + } + if (peelTags) + packstream.push(GitPktLine.encode("peel")); + if (symrefs) + packstream.push(GitPktLine.encode("symrefs")); + if (prefix) + packstream.push(GitPktLine.encode(`ref-prefix ${prefix}`)); + packstream.push(GitPktLine.flush()); + return packstream; +} +async function listServerRefs({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + url, + headers = {}, + forPush = false, + protocolVersion = 2, + prefix, + symrefs, + peelTags +}) { + try { + assertParameter("http", http); + assertParameter("url", url); + const remote = await GitRemoteHTTP.discover({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service: forPush ? "git-receive-pack" : "git-upload-pack", + url, + headers, + protocolVersion + }); + if (remote.protocolVersion === 1) { + return formatInfoRefs(remote, prefix, symrefs, peelTags); + } + const body = await writeListRefsRequest({ prefix, symrefs, peelTags }); + const res = await GitRemoteHTTP.connect({ + http, + auth: remote.auth, + headers, + corsProxy, + service: forPush ? "git-receive-pack" : "git-upload-pack", + url, + body + }); + return parseListRefsResponse(res.body); + } catch (err) { + err.caller = "git.listServerRefs"; + throw err; + } +} +async function listTags({ fs, dir, gitdir = join(dir, ".git") }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + return GitRefManager.listTags({ fs: new FileSystem(fs), gitdir }); + } catch (err) { + err.caller = "git.listTags"; + throw err; + } +} +async function resolveCommit({ fs, cache, gitdir, oid }) { + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type === "tag") { + oid = GitAnnotatedTag.from(object).parse().object; + return resolveCommit({ fs, cache, gitdir, oid }); + } + if (type !== "commit") { + throw new ObjectTypeError(oid, type, "commit"); + } + return { commit: GitCommit.from(object), oid }; +} +async function _readCommit({ fs, cache, gitdir, oid }) { + const { commit: commit2, oid: commitOid } = await resolveCommit({ + fs, + cache, + gitdir, + oid + }); + const result = { + oid: commitOid, + commit: commit2.parse(), + payload: commit2.withoutSignature() + }; + return result; +} +function compareAge(a, b) { + return a.committer.timestamp - b.committer.timestamp; +} +var EMPTY_OID = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"; +async function resolveFileIdInTree({ fs, cache, gitdir, oid, fileId }) { + if (fileId === EMPTY_OID) + return; + const _oid = oid; + let filepath; + const result = await resolveTree({ fs, cache, gitdir, oid }); + const tree = result.tree; + if (fileId === result.oid) { + filepath = result.path; + } else { + filepath = await _resolveFileId({ + fs, + cache, + gitdir, + tree, + fileId, + oid: _oid + }); + if (Array.isArray(filepath)) { + if (filepath.length === 0) + filepath = void 0; + else if (filepath.length === 1) + filepath = filepath[0]; + } + } + return filepath; +} +async function _resolveFileId({ + fs, + cache, + gitdir, + tree, + fileId, + oid, + filepaths = [], + parentPath = "" +}) { + const walks = tree.entries().map(function(entry) { + let result; + if (entry.oid === fileId) { + result = join(parentPath, entry.path); + filepaths.push(result); + } else if (entry.type === "tree") { + result = _readObject({ + fs, + cache, + gitdir, + oid: entry.oid + }).then(function({ object }) { + return _resolveFileId({ + fs, + cache, + gitdir, + tree: GitTree.from(object), + fileId, + oid, + filepaths, + parentPath: join(parentPath, entry.path) + }); + }); + } + return result; + }); + await Promise.all(walks); + return filepaths; +} +async function _log({ + fs, + cache, + gitdir, + filepath, + ref, + depth, + since, + force, + follow +}) { + const sinceTimestamp = typeof since === "undefined" ? void 0 : Math.floor(since.valueOf() / 1e3); + const commits = []; + const shallowCommits = await GitShallowManager.read({ fs, gitdir }); + const oid = await GitRefManager.resolve({ fs, gitdir, ref }); + const tips = [await _readCommit({ fs, cache, gitdir, oid })]; + let lastFileOid; + let lastCommit; + let isOk; + function endCommit(commit2) { + if (isOk && filepath) + commits.push(commit2); + } + while (tips.length > 0) { + const commit2 = tips.pop(); + if (sinceTimestamp !== void 0 && commit2.commit.committer.timestamp <= sinceTimestamp) { + break; + } + if (filepath) { + let vFileOid; + try { + vFileOid = await resolveFilepath({ + fs, + cache, + gitdir, + oid: commit2.commit.tree, + filepath + }); + if (lastCommit && lastFileOid !== vFileOid) { + commits.push(lastCommit); + } + lastFileOid = vFileOid; + lastCommit = commit2; + isOk = true; + } catch (e) { + if (e instanceof NotFoundError) { + let found = follow && lastFileOid; + if (found) { + found = await resolveFileIdInTree({ + fs, + cache, + gitdir, + oid: commit2.commit.tree, + fileId: lastFileOid + }); + if (found) { + if (Array.isArray(found)) { + if (lastCommit) { + const lastFound = await resolveFileIdInTree({ + fs, + cache, + gitdir, + oid: lastCommit.commit.tree, + fileId: lastFileOid + }); + if (Array.isArray(lastFound)) { + found = found.filter((p) => lastFound.indexOf(p) === -1); + if (found.length === 1) { + found = found[0]; + filepath = found; + if (lastCommit) + commits.push(lastCommit); + } else { + found = false; + if (lastCommit) + commits.push(lastCommit); + break; + } + } + } + } else { + filepath = found; + if (lastCommit) + commits.push(lastCommit); + } + } + } + if (!found) { + if (isOk && lastFileOid) { + commits.push(lastCommit); + if (!force) + break; + } + if (!force && !follow) + throw e; + } + lastCommit = commit2; + isOk = false; + } else + throw e; + } + } else { + commits.push(commit2); + } + if (depth !== void 0 && commits.length === depth) { + endCommit(commit2); + break; + } + if (!shallowCommits.has(commit2.oid)) { + for (const oid2 of commit2.commit.parent) { + const commit3 = await _readCommit({ fs, cache, gitdir, oid: oid2 }); + if (!tips.map((commit4) => commit4.oid).includes(commit3.oid)) { + tips.push(commit3); + } + } + } + if (tips.length === 0) { + endCommit(commit2); + } + tips.sort((a, b) => compareAge(a.commit, b.commit)); + } + return commits; +} +async function log({ + fs, + dir, + gitdir = join(dir, ".git"), + filepath, + ref = "HEAD", + depth, + since, + // Date + force, + follow, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + return await _log({ + fs: new FileSystem(fs), + cache, + gitdir, + filepath, + ref, + depth, + since, + force, + follow + }); + } catch (err) { + err.caller = "git.log"; + throw err; + } +} +async function merge({ + fs: _fs, + onSign, + dir, + gitdir = join(dir, ".git"), + ours, + theirs, + fastForward: fastForward2 = true, + fastForwardOnly = false, + dryRun = false, + noUpdateBranch = false, + abortOnConflict = true, + message, + author: _author, + committer: _committer, + signingKey, + cache = {}, + mergeDriver +}) { + try { + assertParameter("fs", _fs); + if (signingKey) { + assertParameter("onSign", onSign); + } + const fs = new FileSystem(_fs); + const author = await normalizeAuthorObject({ fs, gitdir, author: _author }); + if (!author && (!fastForwardOnly || !fastForward2)) { + throw new MissingNameError("author"); + } + const committer = await normalizeCommitterObject({ + fs, + gitdir, + author, + committer: _committer + }); + if (!committer && (!fastForwardOnly || !fastForward2)) { + throw new MissingNameError("committer"); + } + return await _merge({ + fs, + cache, + dir, + gitdir, + ours, + theirs, + fastForward: fastForward2, + fastForwardOnly, + dryRun, + noUpdateBranch, + abortOnConflict, + message, + author, + committer, + signingKey, + onSign, + mergeDriver + }); + } catch (err) { + err.caller = "git.merge"; + throw err; + } +} +var types = { + commit: 16, + tree: 32, + blob: 48, + tag: 64, + ofs_delta: 96, + ref_delta: 112 +}; +async function _pack({ + fs, + cache, + dir, + gitdir = join(dir, ".git"), + oids +}) { + const hash2 = new import_sha1.default(); + const outputStream = []; + function write(chunk, enc) { + const buff = Buffer.from(chunk, enc); + outputStream.push(buff); + hash2.update(buff); + } + async function writeObject2({ stype, object }) { + const type = types[stype]; + let length = object.length; + let multibyte = length > 15 ? 128 : 0; + const lastFour = length & 15; + length = length >>> 4; + let byte = (multibyte | type | lastFour).toString(16); + write(byte, "hex"); + while (multibyte) { + multibyte = length > 127 ? 128 : 0; + byte = multibyte | length & 127; + write(padHex(2, byte), "hex"); + length = length >>> 7; + } + write(Buffer.from(await deflate(object))); + } + write("PACK"); + write("00000002", "hex"); + write(padHex(8, oids.length), "hex"); + for (const oid of oids) { + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + await writeObject2({ write, object, stype: type }); + } + const digest = hash2.digest(); + outputStream.push(digest); + return outputStream; +} +async function _packObjects({ fs, cache, gitdir, oids, write }) { + const buffers = await _pack({ fs, cache, gitdir, oids }); + const packfile = Buffer.from(await collect(buffers)); + const packfileSha = packfile.slice(-20).toString("hex"); + const filename = `pack-${packfileSha}.pack`; + if (write) { + await fs.write(join(gitdir, `objects/pack/${filename}`), packfile); + return { filename }; + } + return { + filename, + packfile: new Uint8Array(packfile) + }; +} +async function packObjects({ + fs, + dir, + gitdir = join(dir, ".git"), + oids, + write = false, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oids", oids); + return await _packObjects({ + fs: new FileSystem(fs), + cache, + gitdir, + oids, + write + }); + } catch (err) { + err.caller = "git.packObjects"; + throw err; + } +} +async function pull({ + fs: _fs, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir = join(dir, ".git"), + ref, + url, + remote, + remoteRef, + prune = false, + pruneTags = false, + fastForward: fastForward2 = true, + fastForwardOnly = false, + corsProxy, + singleBranch, + headers = {}, + author: _author, + committer: _committer, + signingKey, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + const fs = new FileSystem(_fs); + const author = await normalizeAuthorObject({ fs, gitdir, author: _author }); + if (!author) + throw new MissingNameError("author"); + const committer = await normalizeCommitterObject({ + fs, + gitdir, + author, + committer: _committer + }); + if (!committer) + throw new MissingNameError("committer"); + return await _pull({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir, + ref, + url, + remote, + remoteRef, + fastForward: fastForward2, + fastForwardOnly, + corsProxy, + singleBranch, + headers, + author, + committer, + signingKey, + prune, + pruneTags + }); + } catch (err) { + err.caller = "git.pull"; + throw err; + } +} +async function listCommitsAndTags({ + fs, + cache, + dir, + gitdir = join(dir, ".git"), + start, + finish +}) { + const shallows = await GitShallowManager.read({ fs, gitdir }); + const startingSet = /* @__PURE__ */ new Set(); + const finishingSet = /* @__PURE__ */ new Set(); + for (const ref of start) { + startingSet.add(await GitRefManager.resolve({ fs, gitdir, ref })); + } + for (const ref of finish) { + try { + const oid = await GitRefManager.resolve({ fs, gitdir, ref }); + finishingSet.add(oid); + } catch (err) { + } + } + const visited = /* @__PURE__ */ new Set(); + async function walk2(oid) { + visited.add(oid); + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type === "tag") { + const tag2 = GitAnnotatedTag.from(object); + const commit2 = tag2.headers().object; + return walk2(commit2); + } + if (type !== "commit") { + throw new ObjectTypeError(oid, type, "commit"); + } + if (!shallows.has(oid)) { + const commit2 = GitCommit.from(object); + const parents = commit2.headers().parent; + for (oid of parents) { + if (!finishingSet.has(oid) && !visited.has(oid)) { + await walk2(oid); + } + } + } + } + for (const oid of startingSet) { + await walk2(oid); + } + return visited; +} +async function listObjects({ + fs, + cache, + dir, + gitdir = join(dir, ".git"), + oids +}) { + const visited = /* @__PURE__ */ new Set(); + async function walk2(oid) { + if (visited.has(oid)) + return; + visited.add(oid); + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type === "tag") { + const tag2 = GitAnnotatedTag.from(object); + const obj = tag2.headers().object; + await walk2(obj); + } else if (type === "commit") { + const commit2 = GitCommit.from(object); + const tree = commit2.headers().tree; + await walk2(tree); + } else if (type === "tree") { + const tree = GitTree.from(object); + for (const entry of tree) { + if (entry.type === "blob") { + visited.add(entry.oid); + } + if (entry.type === "tree") { + await walk2(entry.oid); + } + } + } + } + for (const oid of oids) { + await walk2(oid); + } + return visited; +} +async function parseReceivePackResponse(packfile) { + const result = {}; + let response = ""; + const read = GitPktLine.streamReader(packfile); + let line = await read(); + while (line !== true) { + if (line !== null) + response += line.toString("utf8") + "\n"; + line = await read(); + } + const lines = response.toString("utf8").split("\n"); + line = lines.shift(); + if (!line.startsWith("unpack ")) { + throw new ParseError('unpack ok" or "unpack [error message]', line); + } + result.ok = line === "unpack ok"; + if (!result.ok) { + result.error = line.slice("unpack ".length); + } + result.refs = {}; + for (const line2 of lines) { + if (line2.trim() === "") + continue; + const status2 = line2.slice(0, 2); + const refAndMessage = line2.slice(3); + let space2 = refAndMessage.indexOf(" "); + if (space2 === -1) + space2 = refAndMessage.length; + const ref = refAndMessage.slice(0, space2); + const error = refAndMessage.slice(space2 + 1); + result.refs[ref] = { + ok: status2 === "ok", + error + }; + } + return result; +} +async function writeReceivePackRequest({ + capabilities = [], + triplets = [] +}) { + const packstream = []; + let capsFirstLine = `\0 ${capabilities.join(" ")}`; + for (const trip of triplets) { + packstream.push( + GitPktLine.encode( + `${trip.oldoid} ${trip.oid} ${trip.fullRef}${capsFirstLine} +` + ) + ); + capsFirstLine = ""; + } + packstream.push(GitPktLine.flush()); + return packstream; +} +async function _push({ + fs, + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + ref: _ref, + remoteRef: _remoteRef, + remote, + url: _url, + force = false, + delete: _delete = false, + corsProxy, + headers = {} +}) { + const ref = _ref || await _currentBranch({ fs, gitdir }); + if (typeof ref === "undefined") { + throw new MissingParameterError("ref"); + } + const config = await GitConfigManager.get({ fs, gitdir }); + remote = remote || await config.get(`branch.${ref}.pushRemote`) || await config.get("remote.pushDefault") || await config.get(`branch.${ref}.remote`) || "origin"; + const url = _url || await config.get(`remote.${remote}.pushurl`) || await config.get(`remote.${remote}.url`); + if (typeof url === "undefined") { + throw new MissingParameterError("remote OR url"); + } + const remoteRef = _remoteRef || await config.get(`branch.${ref}.merge`); + if (typeof url === "undefined") { + throw new MissingParameterError("remoteRef"); + } + if (corsProxy === void 0) { + corsProxy = await config.get("http.corsProxy"); + } + const fullRef = await GitRefManager.expand({ fs, gitdir, ref }); + const oid = _delete ? "0000000000000000000000000000000000000000" : await GitRefManager.resolve({ fs, gitdir, ref: fullRef }); + const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url }); + const httpRemote = await GitRemoteHTTP2.discover({ + http, + onAuth, + onAuthSuccess, + onAuthFailure, + corsProxy, + service: "git-receive-pack", + url, + headers, + protocolVersion: 1 + }); + const auth = httpRemote.auth; + let fullRemoteRef; + if (!remoteRef) { + fullRemoteRef = fullRef; + } else { + try { + fullRemoteRef = await GitRefManager.expandAgainstMap({ + ref: remoteRef, + map: httpRemote.refs + }); + } catch (err) { + if (err instanceof NotFoundError) { + fullRemoteRef = remoteRef.startsWith("refs/") ? remoteRef : `refs/heads/${remoteRef}`; + } else { + throw err; + } + } + } + const oldoid = httpRemote.refs.get(fullRemoteRef) || "0000000000000000000000000000000000000000"; + const thinPack = !httpRemote.capabilities.has("no-thin"); + let objects = /* @__PURE__ */ new Set(); + if (!_delete) { + const finish = [...httpRemote.refs.values()]; + let skipObjects = /* @__PURE__ */ new Set(); + if (oldoid !== "0000000000000000000000000000000000000000") { + const mergebase = await _findMergeBase({ + fs, + cache, + gitdir, + oids: [oid, oldoid] + }); + for (const oid2 of mergebase) + finish.push(oid2); + if (thinPack) { + skipObjects = await listObjects({ fs, cache, gitdir, oids: mergebase }); + } + } + if (!finish.includes(oid)) { + const commits = await listCommitsAndTags({ + fs, + cache, + gitdir, + start: [oid], + finish + }); + objects = await listObjects({ fs, cache, gitdir, oids: commits }); + } + if (thinPack) { + try { + const ref2 = await GitRefManager.resolve({ + fs, + gitdir, + ref: `refs/remotes/${remote}/HEAD`, + depth: 2 + }); + const { oid: oid2 } = await GitRefManager.resolveAgainstMap({ + ref: ref2.replace(`refs/remotes/${remote}/`, ""), + fullref: ref2, + map: httpRemote.refs + }); + const oids = [oid2]; + for (const oid3 of await listObjects({ fs, cache, gitdir, oids })) { + skipObjects.add(oid3); + } + } catch (e) { + } + for (const oid2 of skipObjects) { + objects.delete(oid2); + } + } + if (oid === oldoid) + force = true; + if (!force) { + if (fullRef.startsWith("refs/tags") && oldoid !== "0000000000000000000000000000000000000000") { + throw new PushRejectedError("tag-exists"); + } + if (oid !== "0000000000000000000000000000000000000000" && oldoid !== "0000000000000000000000000000000000000000" && !await _isDescendent({ + fs, + cache, + gitdir, + oid, + ancestor: oldoid, + depth: -1 + })) { + throw new PushRejectedError("not-fast-forward"); + } + } + } + const capabilities = filterCapabilities( + [...httpRemote.capabilities], + ["report-status", "side-band-64k", `agent=${pkg.agent}`] + ); + const packstream1 = await writeReceivePackRequest({ + capabilities, + triplets: [{ oldoid, oid, fullRef: fullRemoteRef }] + }); + const packstream2 = _delete ? [] : await _pack({ + fs, + cache, + gitdir, + oids: [...objects] + }); + const res = await GitRemoteHTTP2.connect({ + http, + onProgress, + corsProxy, + service: "git-receive-pack", + url, + auth, + headers, + body: [...packstream1, ...packstream2] + }); + const { packfile, progress } = await GitSideBand.demux(res.body); + if (onMessage) { + const lines = splitLines(progress); + forAwait(lines, async (line) => { + await onMessage(line); + }); + } + const result = await parseReceivePackResponse(packfile); + if (res.headers) { + result.headers = res.headers; + } + if (remote && result.ok && result.refs[fullRemoteRef].ok) { + const ref2 = `refs/remotes/${remote}/${fullRemoteRef.replace( + "refs/heads", + "" + )}`; + if (_delete) { + await GitRefManager.deleteRef({ fs, gitdir, ref: ref2 }); + } else { + await GitRefManager.writeRef({ fs, gitdir, ref: ref2, value: oid }); + } + } + if (result.ok && Object.values(result.refs).every((result2) => result2.ok)) { + return result; + } else { + const prettyDetails = Object.entries(result.refs).filter(([k, v]) => !v.ok).map(([k, v]) => ` + - ${k}: ${v.error}`).join(""); + throw new GitPushError(prettyDetails, result); + } +} +async function push({ + fs, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + dir, + gitdir = join(dir, ".git"), + ref, + remoteRef, + remote = "origin", + url, + force = false, + delete: _delete = false, + corsProxy, + headers = {}, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("http", http); + assertParameter("gitdir", gitdir); + return await _push({ + fs: new FileSystem(fs), + cache, + http, + onProgress, + onMessage, + onAuth, + onAuthSuccess, + onAuthFailure, + gitdir, + ref, + remoteRef, + remote, + url, + force, + delete: _delete, + corsProxy, + headers + }); + } catch (err) { + err.caller = "git.push"; + throw err; + } +} +async function resolveBlob({ fs, cache, gitdir, oid }) { + const { type, object } = await _readObject({ fs, cache, gitdir, oid }); + if (type === "tag") { + oid = GitAnnotatedTag.from(object).parse().object; + return resolveBlob({ fs, cache, gitdir, oid }); + } + if (type !== "blob") { + throw new ObjectTypeError(oid, type, "blob"); + } + return { oid, blob: new Uint8Array(object) }; +} +async function _readBlob({ + fs, + cache, + gitdir, + oid, + filepath = void 0 +}) { + if (filepath !== void 0) { + oid = await resolveFilepath({ fs, cache, gitdir, oid, filepath }); + } + const blob = await resolveBlob({ + fs, + cache, + gitdir, + oid + }); + return blob; +} +async function readBlob({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + filepath, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + return await _readBlob({ + fs: new FileSystem(fs), + cache, + gitdir, + oid, + filepath + }); + } catch (err) { + err.caller = "git.readBlob"; + throw err; + } +} +async function readCommit({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + return await _readCommit({ + fs: new FileSystem(fs), + cache, + gitdir, + oid + }); + } catch (err) { + err.caller = "git.readCommit"; + throw err; + } +} +async function _readNote({ + fs, + cache, + gitdir, + ref = "refs/notes/commits", + oid +}) { + const parent = await GitRefManager.resolve({ gitdir, fs, ref }); + const { blob } = await _readBlob({ + fs, + cache, + gitdir, + oid: parent, + filepath: oid + }); + return blob; +} +async function readNote({ + fs, + dir, + gitdir = join(dir, ".git"), + ref = "refs/notes/commits", + oid, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + assertParameter("oid", oid); + return await _readNote({ + fs: new FileSystem(fs), + cache, + gitdir, + ref, + oid + }); + } catch (err) { + err.caller = "git.readNote"; + throw err; + } +} +async function readObject({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + oid, + format = "parsed", + filepath = void 0, + encoding = void 0, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + const fs = new FileSystem(_fs); + if (filepath !== void 0) { + oid = await resolveFilepath({ + fs, + cache, + gitdir, + oid, + filepath + }); + } + const _format = format === "parsed" ? "content" : format; + const result = await _readObject({ + fs, + cache, + gitdir, + oid, + format: _format + }); + result.oid = oid; + if (format === "parsed") { + result.format = "parsed"; + switch (result.type) { + case "commit": + result.object = GitCommit.from(result.object).parse(); + break; + case "tree": + result.object = GitTree.from(result.object).entries(); + break; + case "blob": + if (encoding) { + result.object = result.object.toString(encoding); + } else { + result.object = new Uint8Array(result.object); + result.format = "content"; + } + break; + case "tag": + result.object = GitAnnotatedTag.from(result.object).parse(); + break; + default: + throw new ObjectTypeError( + result.oid, + result.type, + "blob|commit|tag|tree" + ); + } + } else if (result.format === "deflated" || result.format === "wrapped") { + result.type = result.format; + } + return result; + } catch (err) { + err.caller = "git.readObject"; + throw err; + } +} +async function _readTag({ fs, cache, gitdir, oid }) { + const { type, object } = await _readObject({ + fs, + cache, + gitdir, + oid, + format: "content" + }); + if (type !== "tag") { + throw new ObjectTypeError(oid, type, "tag"); + } + const tag2 = GitAnnotatedTag.from(object); + const result = { + oid, + tag: tag2.parse(), + payload: tag2.payload() + }; + return result; +} +async function readTag({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + return await _readTag({ + fs: new FileSystem(fs), + cache, + gitdir, + oid + }); + } catch (err) { + err.caller = "git.readTag"; + throw err; + } +} +async function readTree({ + fs, + dir, + gitdir = join(dir, ".git"), + oid, + filepath = void 0, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + return await _readTree({ + fs: new FileSystem(fs), + cache, + gitdir, + oid, + filepath + }); + } catch (err) { + err.caller = "git.readTree"; + throw err; + } +} +async function remove({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + filepath, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + await GitIndexManager.acquire( + { fs: new FileSystem(_fs), gitdir, cache }, + async function(index2) { + index2.delete({ filepath }); + } + ); + } catch (err) { + err.caller = "git.remove"; + throw err; + } +} +async function _removeNote({ + fs, + cache, + onSign, + gitdir, + ref = "refs/notes/commits", + oid, + author, + committer, + signingKey +}) { + let parent; + try { + parent = await GitRefManager.resolve({ gitdir, fs, ref }); + } catch (err) { + if (!(err instanceof NotFoundError)) { + throw err; + } + } + const result = await _readTree({ + fs, + gitdir, + oid: parent || "4b825dc642cb6eb9a060e54bf8d69288fbee4904" + }); + let tree = result.tree; + tree = tree.filter((entry) => entry.path !== oid); + const treeOid = await _writeTree({ + fs, + gitdir, + tree + }); + const commitOid = await _commit({ + fs, + cache, + onSign, + gitdir, + ref, + tree: treeOid, + parent: parent && [parent], + message: `Note removed by 'isomorphic-git removeNote' +`, + author, + committer, + signingKey + }); + return commitOid; +} +async function removeNote({ + fs: _fs, + onSign, + dir, + gitdir = join(dir, ".git"), + ref = "refs/notes/commits", + oid, + author: _author, + committer: _committer, + signingKey, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("oid", oid); + const fs = new FileSystem(_fs); + const author = await normalizeAuthorObject({ fs, gitdir, author: _author }); + if (!author) + throw new MissingNameError("author"); + const committer = await normalizeCommitterObject({ + fs, + gitdir, + author, + committer: _committer + }); + if (!committer) + throw new MissingNameError("committer"); + return await _removeNote({ + fs, + cache, + onSign, + gitdir, + ref, + oid, + author, + committer, + signingKey + }); + } catch (err) { + err.caller = "git.removeNote"; + throw err; + } +} +async function _renameBranch({ + fs, + gitdir, + oldref, + ref, + checkout: checkout2 = false +}) { + if (ref !== import_clean_git_ref.default.clean(ref)) { + throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref)); + } + if (oldref !== import_clean_git_ref.default.clean(oldref)) { + throw new InvalidRefNameError(oldref, import_clean_git_ref.default.clean(oldref)); + } + const fulloldref = `refs/heads/${oldref}`; + const fullnewref = `refs/heads/${ref}`; + const newexist = await GitRefManager.exists({ fs, gitdir, ref: fullnewref }); + if (newexist) { + throw new AlreadyExistsError("branch", ref, false); + } + const value = await GitRefManager.resolve({ + fs, + gitdir, + ref: fulloldref, + depth: 1 + }); + await GitRefManager.writeRef({ fs, gitdir, ref: fullnewref, value }); + await GitRefManager.deleteRef({ fs, gitdir, ref: fulloldref }); + const fullCurrentBranchRef = await _currentBranch({ + fs, + gitdir, + fullname: true + }); + const isCurrentBranch = fullCurrentBranchRef === fulloldref; + if (checkout2 || isCurrentBranch) { + await GitRefManager.writeSymbolicRef({ + fs, + gitdir, + ref: "HEAD", + value: fullnewref + }); + } +} +async function renameBranch({ + fs, + dir, + gitdir = join(dir, ".git"), + ref, + oldref, + checkout: checkout2 = false +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + assertParameter("oldref", oldref); + return await _renameBranch({ + fs: new FileSystem(fs), + gitdir, + ref, + oldref, + checkout: checkout2 + }); + } catch (err) { + err.caller = "git.renameBranch"; + throw err; + } +} +async function hashObject$1({ gitdir, type, object }) { + return shasum(GitObject.wrap({ type, object })); +} +async function resetIndex({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + filepath, + ref, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + const fs = new FileSystem(_fs); + let oid; + let workdirOid; + try { + oid = await GitRefManager.resolve({ fs, gitdir, ref: ref || "HEAD" }); + } catch (e) { + if (ref) { + throw e; + } + } + if (oid) { + try { + oid = await resolveFilepath({ + fs, + cache, + gitdir, + oid, + filepath + }); + } catch (e) { + oid = null; + } + } + let stats = { + ctime: /* @__PURE__ */ new Date(0), + mtime: /* @__PURE__ */ new Date(0), + dev: 0, + ino: 0, + mode: 0, + uid: 0, + gid: 0, + size: 0 + }; + const object = dir && await fs.read(join(dir, filepath)); + if (object) { + workdirOid = await hashObject$1({ + gitdir, + type: "blob", + object + }); + if (oid === workdirOid) { + stats = await fs.lstat(join(dir, filepath)); + } + } + await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + index2.delete({ filepath }); + if (oid) { + index2.insert({ filepath, stats, oid }); + } + }); + } catch (err) { + err.caller = "git.reset"; + throw err; + } +} +async function resolveRef({ + fs, + dir, + gitdir = join(dir, ".git"), + ref, + depth +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + const oid = await GitRefManager.resolve({ + fs: new FileSystem(fs), + gitdir, + ref, + depth + }); + return oid; + } catch (err) { + err.caller = "git.resolveRef"; + throw err; + } +} +async function setConfig({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + path: path2, + value, + append: append3 = false +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("path", path2); + const fs = new FileSystem(_fs); + const config = await GitConfigManager.get({ fs, gitdir }); + if (append3) { + await config.append(path2, value); + } else { + await config.set(path2, value); + } + await GitConfigManager.save({ fs, gitdir, config }); + } catch (err) { + err.caller = "git.setConfig"; + throw err; + } +} +async function status({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + filepath, + cache = {} +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + const fs = new FileSystem(_fs); + const ignored = await GitIgnoreManager.isIgnored({ + fs, + gitdir, + dir, + filepath + }); + if (ignored) { + return "ignored"; + } + const headTree = await getHeadTree({ fs, cache, gitdir }); + const treeOid = await getOidAtPath({ + fs, + cache, + gitdir, + tree: headTree, + path: filepath + }); + const indexEntry = await GitIndexManager.acquire( + { fs, gitdir, cache }, + async function(index2) { + for (const entry of index2) { + if (entry.path === filepath) + return entry; + } + return null; + } + ); + const stats = await fs.lstat(join(dir, filepath)); + const H = treeOid !== null; + const I = indexEntry !== null; + const W = stats !== null; + const getWorkdirOid = async () => { + if (I && !compareStats(indexEntry, stats)) { + return indexEntry.oid; + } else { + const object = await fs.read(join(dir, filepath)); + const workdirOid = await hashObject$1({ + gitdir, + type: "blob", + object + }); + if (I && indexEntry.oid === workdirOid) { + if (stats.size !== -1) { + GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + index2.insert({ filepath, stats, oid: workdirOid }); + }); + } + } + return workdirOid; + } + }; + if (!H && !W && !I) + return "absent"; + if (!H && !W && I) + return "*absent"; + if (!H && W && !I) + return "*added"; + if (!H && W && I) { + const workdirOid = await getWorkdirOid(); + return workdirOid === indexEntry.oid ? "added" : "*added"; + } + if (H && !W && !I) + return "deleted"; + if (H && !W && I) { + return treeOid === indexEntry.oid ? "*deleted" : "*deleted"; + } + if (H && W && !I) { + const workdirOid = await getWorkdirOid(); + return workdirOid === treeOid ? "*undeleted" : "*undeletemodified"; + } + if (H && W && I) { + const workdirOid = await getWorkdirOid(); + if (workdirOid === treeOid) { + return workdirOid === indexEntry.oid ? "unmodified" : "*unmodified"; + } else { + return workdirOid === indexEntry.oid ? "modified" : "*modified"; + } + } + } catch (err) { + err.caller = "git.status"; + throw err; + } +} +async function getOidAtPath({ fs, cache, gitdir, tree, path: path2 }) { + if (typeof path2 === "string") + path2 = path2.split("/"); + const dirname3 = path2.shift(); + for (const entry of tree) { + if (entry.path === dirname3) { + if (path2.length === 0) { + return entry.oid; + } + const { type, object } = await _readObject({ + fs, + cache, + gitdir, + oid: entry.oid + }); + if (type === "tree") { + const tree2 = GitTree.from(object); + return getOidAtPath({ fs, cache, gitdir, tree: tree2, path: path2 }); + } + if (type === "blob") { + throw new ObjectTypeError(entry.oid, type, "blob", path2.join("/")); + } + } + } + return null; +} +async function getHeadTree({ fs, cache, gitdir }) { + let oid; + try { + oid = await GitRefManager.resolve({ fs, gitdir, ref: "HEAD" }); + } catch (e) { + if (e instanceof NotFoundError) { + return []; + } + } + const { tree } = await _readTree({ fs, cache, gitdir, oid }); + return tree; +} +async function statusMatrix({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + ref = "HEAD", + filepaths = ["."], + filter, + cache = {}, + ignored: shouldIgnore = false +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + const fs = new FileSystem(_fs); + return await _walk({ + fs, + cache, + dir, + gitdir, + trees: [TREE({ ref }), WORKDIR(), STAGE()], + map: async function(filepath, [head, workdir, stage]) { + if (!head && !stage && workdir) { + if (!shouldIgnore) { + const isIgnored2 = await GitIgnoreManager.isIgnored({ + fs, + dir, + filepath + }); + if (isIgnored2) { + return null; + } + } + } + if (!filepaths.some((base) => worthWalking(filepath, base))) { + return null; + } + if (filter) { + if (!filter(filepath)) + return; + } + const [headType, workdirType, stageType] = await Promise.all([ + head && head.type(), + workdir && workdir.type(), + stage && stage.type() + ]); + const isBlob = [headType, workdirType, stageType].includes("blob"); + if ((headType === "tree" || headType === "special") && !isBlob) + return; + if (headType === "commit") + return null; + if ((workdirType === "tree" || workdirType === "special") && !isBlob) + return; + if (stageType === "commit") + return null; + if ((stageType === "tree" || stageType === "special") && !isBlob) + return; + const headOid = headType === "blob" ? await head.oid() : void 0; + const stageOid = stageType === "blob" ? await stage.oid() : void 0; + let workdirOid; + if (headType !== "blob" && workdirType === "blob" && stageType !== "blob") { + workdirOid = "42"; + } else if (workdirType === "blob") { + workdirOid = await workdir.oid(); + } + const entry = [void 0, headOid, workdirOid, stageOid]; + const result = entry.map((value) => entry.indexOf(value)); + result.shift(); + return [filepath, ...result]; + } + }); + } catch (err) { + err.caller = "git.statusMatrix"; + throw err; + } +} +async function tag({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + ref, + object, + force = false +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + const fs = new FileSystem(_fs); + if (ref === void 0) { + throw new MissingParameterError("ref"); + } + ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`; + const value = await GitRefManager.resolve({ + fs, + gitdir, + ref: object || "HEAD" + }); + if (!force && await GitRefManager.exists({ fs, gitdir, ref })) { + throw new AlreadyExistsError("tag", ref); + } + await GitRefManager.writeRef({ fs, gitdir, ref, value }); + } catch (err) { + err.caller = "git.tag"; + throw err; + } +} +async function updateIndex({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + cache = {}, + filepath, + oid, + mode, + add: add2, + remove: remove3, + force +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("filepath", filepath); + const fs = new FileSystem(_fs); + if (remove3) { + return await GitIndexManager.acquire( + { fs, gitdir, cache }, + async function(index2) { + let fileStats2; + if (!force) { + fileStats2 = await fs.lstat(join(dir, filepath)); + if (fileStats2) { + if (fileStats2.isDirectory()) { + throw new InvalidFilepathError("directory"); + } + return; + } + } + if (index2.has({ filepath })) { + index2.delete({ + filepath + }); + } + } + ); + } + let fileStats; + if (!oid) { + fileStats = await fs.lstat(join(dir, filepath)); + if (!fileStats) { + throw new NotFoundError( + `file at "${filepath}" on disk and "remove" not set` + ); + } + if (fileStats.isDirectory()) { + throw new InvalidFilepathError("directory"); + } + } + return await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) { + if (!add2 && !index2.has({ filepath })) { + throw new NotFoundError( + `file at "${filepath}" in index and "add" not set` + ); + } + let stats = { + ctime: /* @__PURE__ */ new Date(0), + mtime: /* @__PURE__ */ new Date(0), + dev: 0, + ino: 0, + mode, + uid: 0, + gid: 0, + size: 0 + }; + if (!oid) { + stats = fileStats; + const object = stats.isSymbolicLink() ? await fs.readlink(join(dir, filepath)) : await fs.read(join(dir, filepath)); + oid = await _writeObject({ + fs, + gitdir, + type: "blob", + format: "content", + object + }); + } + index2.insert({ + filepath, + oid, + stats + }); + return oid; + }); + } catch (err) { + err.caller = "git.updateIndex"; + throw err; + } +} +function version() { + try { + return pkg.version; + } catch (err) { + err.caller = "git.version"; + throw err; + } +} +async function walk({ + fs, + dir, + gitdir = join(dir, ".git"), + trees, + map, + reduce, + iterate, + cache = {} +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("trees", trees); + return await _walk({ + fs: new FileSystem(fs), + cache, + dir, + gitdir, + trees, + map, + reduce, + iterate + }); + } catch (err) { + err.caller = "git.walk"; + throw err; + } +} +async function writeBlob({ fs, dir, gitdir = join(dir, ".git"), blob }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("blob", blob); + return await _writeObject({ + fs: new FileSystem(fs), + gitdir, + type: "blob", + object: blob, + format: "content" + }); + } catch (err) { + err.caller = "git.writeBlob"; + throw err; + } +} +async function _writeCommit({ fs, gitdir, commit: commit2 }) { + const object = GitCommit.from(commit2).toObject(); + const oid = await _writeObject({ + fs, + gitdir, + type: "commit", + object, + format: "content" + }); + return oid; +} +async function writeCommit({ + fs, + dir, + gitdir = join(dir, ".git"), + commit: commit2 +}) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("commit", commit2); + return await _writeCommit({ + fs: new FileSystem(fs), + gitdir, + commit: commit2 + }); + } catch (err) { + err.caller = "git.writeCommit"; + throw err; + } +} +async function writeObject({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + type, + object, + format = "parsed", + oid, + encoding = void 0 +}) { + try { + const fs = new FileSystem(_fs); + if (format === "parsed") { + switch (type) { + case "commit": + object = GitCommit.from(object).toObject(); + break; + case "tree": + object = GitTree.from(object).toObject(); + break; + case "blob": + object = Buffer.from(object, encoding); + break; + case "tag": + object = GitAnnotatedTag.from(object).toObject(); + break; + default: + throw new ObjectTypeError(oid || "", type, "blob|commit|tag|tree"); + } + format = "content"; + } + oid = await _writeObject({ + fs, + gitdir, + type, + object, + oid, + format + }); + return oid; + } catch (err) { + err.caller = "git.writeObject"; + throw err; + } +} +async function writeRef({ + fs: _fs, + dir, + gitdir = join(dir, ".git"), + ref, + value, + force = false, + symbolic = false +}) { + try { + assertParameter("fs", _fs); + assertParameter("gitdir", gitdir); + assertParameter("ref", ref); + assertParameter("value", value); + const fs = new FileSystem(_fs); + if (ref !== import_clean_git_ref.default.clean(ref)) { + throw new InvalidRefNameError(ref, import_clean_git_ref.default.clean(ref)); + } + if (!force && await GitRefManager.exists({ fs, gitdir, ref })) { + throw new AlreadyExistsError("ref", ref); + } + if (symbolic) { + await GitRefManager.writeSymbolicRef({ + fs, + gitdir, + ref, + value + }); + } else { + value = await GitRefManager.resolve({ + fs, + gitdir, + ref: value + }); + await GitRefManager.writeRef({ + fs, + gitdir, + ref, + value + }); + } + } catch (err) { + err.caller = "git.writeRef"; + throw err; + } +} +async function _writeTag({ fs, gitdir, tag: tag2 }) { + const object = GitAnnotatedTag.from(tag2).toObject(); + const oid = await _writeObject({ + fs, + gitdir, + type: "tag", + object, + format: "content" + }); + return oid; +} +async function writeTag({ fs, dir, gitdir = join(dir, ".git"), tag: tag2 }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("tag", tag2); + return await _writeTag({ + fs: new FileSystem(fs), + gitdir, + tag: tag2 + }); + } catch (err) { + err.caller = "git.writeTag"; + throw err; + } +} +async function writeTree({ fs, dir, gitdir = join(dir, ".git"), tree }) { + try { + assertParameter("fs", fs); + assertParameter("gitdir", gitdir); + assertParameter("tree", tree); + return await _writeTree({ + fs: new FileSystem(fs), + gitdir, + tree + }); + } catch (err) { + err.caller = "git.writeTree"; + throw err; + } +} +var index = { + Errors, + STAGE, + TREE, + WORKDIR, + add, + abortMerge, + addNote, + addRemote, + annotatedTag, + branch, + checkout, + clone, + commit, + getConfig, + getConfigAll, + setConfig, + currentBranch, + deleteBranch, + deleteRef, + deleteRemote, + deleteTag, + expandOid, + expandRef, + fastForward, + fetch, + findMergeBase, + findRoot, + getRemoteInfo, + getRemoteInfo2, + hashBlob, + indexPack, + init, + isDescendent, + isIgnored, + listBranches, + listFiles, + listNotes, + listRemotes, + listServerRefs, + listTags, + log, + merge, + packObjects, + pull, + push, + readBlob, + readCommit, + readNote, + readObject, + readTag, + readTree, + remove, + removeNote, + renameBranch, + resetIndex, + updateIndex, + resolveRef, + status, + statusMatrix, + tag, + version, + walk, + writeBlob, + writeCommit, + writeObject, + writeRef, + writeTag, + writeTree +}; +var isomorphic_git_default = index; + +// src/main.ts +var import_obsidian31 = require("obsidian"); + +// src/lineAuthor/lineAuthorIntegration.ts +init_polyfill_buffer(); +var import_obsidian12 = require("obsidian"); + +// src/gitManager/simpleGit.ts +init_polyfill_buffer(); +var import_child_process2 = require("child_process"); +var import_debug2 = __toESM(require_browser()); +var import_obsidian4 = require("obsidian"); +var path = __toESM(require("path")); +var import_path = require("path"); + +// node_modules/.pnpm/simple-git@https+++codeload.github.com+Vinzent03+git-js+tar.gz+6b9a2d899bc8256e38a1d6f0b8a881_rku6lxlylrt42756swupwur2wa/node_modules/simple-git/dist/esm/index.js +init_polyfill_buffer(); +var import_file_exists = __toESM(require_dist(), 1); +var import_debug = __toESM(require_browser(), 1); +var import_child_process = require("child_process"); +var import_promise_deferred = __toESM(require_dist2(), 1); +var import_promise_deferred2 = __toESM(require_dist2(), 1); +var __defProp2 = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames2 = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp2 = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp2 = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp2.call(b, prop)) + __defNormalProp2(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp2(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true }); +var __esm2 = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res; +}; +var __commonJS2 = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); +}; +var __reExport = (target, module2, copyDefault, desc) => { + if (module2 && typeof module2 === "object" || typeof module2 === "function") { + for (let key2 of __getOwnPropNames2(module2)) + if (!__hasOwnProp2.call(target, key2) && (copyDefault || key2 !== "default")) + __defProp2(target, key2, { get: () => module2[key2], enumerable: !(desc = __getOwnPropDesc2(module2, key2)) || desc.enumerable }); + } + return target; +}; +var __toCommonJS2 = /* @__PURE__ */ ((cache) => { + return (module2, temp) => { + return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp); + }; +})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +var GitError; +var init_git_error = __esm2({ + "src/lib/errors/git-error.ts"() { + GitError = class extends Error { + constructor(task, message) { + super(message); + this.task = task; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); +var GitResponseError; +var init_git_response_error = __esm2({ + "src/lib/errors/git-response-error.ts"() { + init_git_error(); + GitResponseError = class extends GitError { + constructor(git, message) { + super(void 0, message || String(git)); + this.git = git; + } + }; + } +}); +var TaskConfigurationError; +var init_task_configuration_error = __esm2({ + "src/lib/errors/task-configuration-error.ts"() { + init_git_error(); + TaskConfigurationError = class extends GitError { + constructor(message) { + super(void 0, message); + } + }; + } +}); +function asFunction(source) { + return typeof source === "function" ? source : NOOP; +} +function isUserFunction(source) { + return typeof source === "function" && source !== NOOP; +} +function splitOn(input, char) { + const index2 = input.indexOf(char); + if (index2 <= 0) { + return [input, ""]; + } + return [input.substr(0, index2), input.substr(index2 + 1)]; +} +function first(input, offset = 0) { + return isArrayLike(input) && input.length > offset ? input[offset] : void 0; +} +function last(input, offset = 0) { + if (isArrayLike(input) && input.length > offset) { + return input[input.length - 1 - offset]; + } +} +function isArrayLike(input) { + return !!(input && typeof input.length === "number"); +} +function toLinesWithContent(input = "", trimmed2 = true, separator2 = "\n") { + return input.split(separator2).reduce((output, line) => { + const lineContent = trimmed2 ? line.trim() : line; + if (lineContent) { + output.push(lineContent); + } + return output; + }, []); +} +function forEachLineWithContent(input, callback) { + return toLinesWithContent(input, true).map((line) => callback(line)); +} +function folderExists(path2) { + return (0, import_file_exists.exists)(path2, import_file_exists.FOLDER); +} +function append(target, item) { + if (Array.isArray(target)) { + if (!target.includes(item)) { + target.push(item); + } + } else { + target.add(item); + } + return item; +} +function including(target, item) { + if (Array.isArray(target) && !target.includes(item)) { + target.push(item); + } + return target; +} +function remove2(target, item) { + if (Array.isArray(target)) { + const index2 = target.indexOf(item); + if (index2 >= 0) { + target.splice(index2, 1); + } + } else { + target.delete(item); + } + return item; +} +function asArray(source) { + return Array.isArray(source) ? source : [source]; +} +function asStringArray(source) { + return asArray(source).map(String); +} +function asNumber(source, onNaN = 0) { + if (source == null) { + return onNaN; + } + const num2 = parseInt(source, 10); + return isNaN(num2) ? onNaN : num2; +} +function prefixedArray(input, prefix) { + const output = []; + for (let i = 0, max = input.length; i < max; i++) { + output.push(prefix, input[i]); + } + return output; +} +function bufferToString(input) { + return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8"); +} +function pick(source, properties) { + return Object.assign({}, ...properties.map((property) => property in source ? { [property]: source[property] } : {})); +} +function delay(duration = 0) { + return new Promise((done) => setTimeout(done, duration)); +} +var NULL; +var NOOP; +var objectToString; +var init_util = __esm2({ + "src/lib/utils/util.ts"() { + NULL = "\0"; + NOOP = () => { + }; + objectToString = Object.prototype.toString.call.bind(Object.prototype.toString); + } +}); +function filterType(input, filter, def) { + if (filter(input)) { + return input; + } + return arguments.length > 2 ? def : void 0; +} +function filterPrimitives(input, omit) { + return /number|string|boolean/.test(typeof input) && (!omit || !omit.includes(typeof input)); +} +function filterPlainObject(input) { + return !!input && objectToString(input) === "[object Object]"; +} +function filterFunction(input) { + return typeof input === "function"; +} +var filterArray; +var filterString; +var filterStringArray; +var filterStringOrStringArray; +var filterHasLength; +var init_argument_filters = __esm2({ + "src/lib/utils/argument-filters.ts"() { + init_util(); + filterArray = (input) => { + return Array.isArray(input); + }; + filterString = (input) => { + return typeof input === "string"; + }; + filterStringArray = (input) => { + return Array.isArray(input) && input.every(filterString); + }; + filterStringOrStringArray = (input) => { + return filterString(input) || Array.isArray(input) && input.every(filterString); + }; + filterHasLength = (input) => { + if (input == null || "number|boolean|function".includes(typeof input)) { + return false; + } + return Array.isArray(input) || typeof input === "string" || typeof input.length === "number"; + }; + } +}); +var ExitCodes; +var init_exit_codes = __esm2({ + "src/lib/utils/exit-codes.ts"() { + ExitCodes = /* @__PURE__ */ ((ExitCodes2) => { + ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS"; + ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR"; + ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND"; + ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN"; + return ExitCodes2; + })(ExitCodes || {}); + } +}); +var GitOutputStreams; +var init_git_output_streams = __esm2({ + "src/lib/utils/git-output-streams.ts"() { + GitOutputStreams = class { + constructor(stdOut, stdErr) { + this.stdOut = stdOut; + this.stdErr = stdErr; + } + asStrings() { + return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8")); + } + }; + } +}); +var LineParser; +var RemoteLineParser; +var init_line_parser = __esm2({ + "src/lib/utils/line-parser.ts"() { + LineParser = class { + constructor(regExp, useMatches) { + this.matches = []; + this.parse = (line, target) => { + this.resetMatches(); + if (!this._regExp.every((reg, index2) => this.addMatch(reg, index2, line(index2)))) { + return false; + } + return this.useMatches(target, this.prepareMatches()) !== false; + }; + this._regExp = Array.isArray(regExp) ? regExp : [regExp]; + if (useMatches) { + this.useMatches = useMatches; + } + } + useMatches(target, match) { + throw new Error(`LineParser:useMatches not implemented`); + } + resetMatches() { + this.matches.length = 0; + } + prepareMatches() { + return this.matches; + } + addMatch(reg, index2, line) { + const matched = line && reg.exec(line); + if (matched) { + this.pushMatch(index2, matched); + } + return !!matched; + } + pushMatch(_index, matched) { + this.matches.push(...matched.slice(1)); + } + }; + RemoteLineParser = class extends LineParser { + addMatch(reg, index2, line) { + return /^remote:\s/.test(String(line)) && super.addMatch(reg, index2, line); + } + pushMatch(index2, matched) { + if (index2 > 0 || matched.length > 1) { + super.pushMatch(index2, matched); + } + } + }; + } +}); +function createInstanceConfig(...options) { + const baseDir = process.cwd(); + const config = Object.assign(__spreadValues({ baseDir }, defaultOptions), ...options.filter((o) => typeof o === "object" && o)); + config.baseDir = config.baseDir || baseDir; + config.trimmed = config.trimmed === true; + return config; +} +var defaultOptions; +var init_simple_git_options = __esm2({ + "src/lib/utils/simple-git-options.ts"() { + defaultOptions = { + binary: "git", + maxConcurrentProcesses: 5, + config: [], + trimmed: false + }; + } +}); +function appendTaskOptions(options, commands2 = []) { + if (!filterPlainObject(options)) { + return commands2; + } + return Object.keys(options).reduce((commands22, key2) => { + const value = options[key2]; + if (filterPrimitives(value, ["boolean"])) { + commands22.push(key2 + "=" + value); + } else { + commands22.push(key2); + } + return commands22; + }, commands2); +} +function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) { + const command = []; + for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) { + if ("string|number".includes(typeof args[i])) { + command.push(String(args[i])); + } + } + appendTaskOptions(trailingOptionsArgument(args), command); + if (!objectOnly) { + command.push(...trailingArrayArgument(args)); + } + return command; +} +function trailingArrayArgument(args) { + const hasTrailingCallback = typeof last(args) === "function"; + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []); +} +function trailingOptionsArgument(args) { + const hasTrailingCallback = filterFunction(last(args)); + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject); +} +function trailingFunctionArgument(args, includeNoop = true) { + const callback = asFunction(last(args)); + return includeNoop || isUserFunction(callback) ? callback : void 0; +} +var init_task_options = __esm2({ + "src/lib/utils/task-options.ts"() { + init_argument_filters(); + init_util(); + } +}); +function callTaskParser(parser3, streams) { + return parser3(streams.stdOut, streams.stdErr); +} +function parseStringResponse(result, parsers12, texts, trim = true) { + asArray(texts).forEach((text2) => { + for (let lines = toLinesWithContent(text2, trim), i = 0, max = lines.length; i < max; i++) { + const line = (offset = 0) => { + if (i + offset >= max) { + return; + } + return lines[i + offset]; + }; + parsers12.some(({ parse: parse2 }) => parse2(line, result)); + } + }); + return result; +} +var init_task_parser = __esm2({ + "src/lib/utils/task-parser.ts"() { + init_util(); + } +}); +var utils_exports = {}; +__export2(utils_exports, { + ExitCodes: () => ExitCodes, + GitOutputStreams: () => GitOutputStreams, + LineParser: () => LineParser, + NOOP: () => NOOP, + NULL: () => NULL, + RemoteLineParser: () => RemoteLineParser, + append: () => append, + appendTaskOptions: () => appendTaskOptions, + asArray: () => asArray, + asFunction: () => asFunction, + asNumber: () => asNumber, + asStringArray: () => asStringArray, + bufferToString: () => bufferToString, + callTaskParser: () => callTaskParser, + createInstanceConfig: () => createInstanceConfig, + delay: () => delay, + filterArray: () => filterArray, + filterFunction: () => filterFunction, + filterHasLength: () => filterHasLength, + filterPlainObject: () => filterPlainObject, + filterPrimitives: () => filterPrimitives, + filterString: () => filterString, + filterStringArray: () => filterStringArray, + filterStringOrStringArray: () => filterStringOrStringArray, + filterType: () => filterType, + first: () => first, + folderExists: () => folderExists, + forEachLineWithContent: () => forEachLineWithContent, + getTrailingOptions: () => getTrailingOptions, + including: () => including, + isUserFunction: () => isUserFunction, + last: () => last, + objectToString: () => objectToString, + parseStringResponse: () => parseStringResponse, + pick: () => pick, + prefixedArray: () => prefixedArray, + remove: () => remove2, + splitOn: () => splitOn, + toLinesWithContent: () => toLinesWithContent, + trailingFunctionArgument: () => trailingFunctionArgument, + trailingOptionsArgument: () => trailingOptionsArgument +}); +var init_utils = __esm2({ + "src/lib/utils/index.ts"() { + init_argument_filters(); + init_exit_codes(); + init_git_output_streams(); + init_line_parser(); + init_simple_git_options(); + init_task_options(); + init_task_parser(); + init_util(); + } +}); +var check_is_repo_exports = {}; +__export2(check_is_repo_exports, { + CheckRepoActions: () => CheckRepoActions, + checkIsBareRepoTask: () => checkIsBareRepoTask, + checkIsRepoRootTask: () => checkIsRepoRootTask, + checkIsRepoTask: () => checkIsRepoTask +}); +function checkIsRepoTask(action) { + switch (action) { + case "bare": + return checkIsBareRepoTask(); + case "root": + return checkIsRepoRootTask(); + } + const commands2 = ["rev-parse", "--is-inside-work-tree"]; + return { + commands: commands2, + format: "utf-8", + onError, + parser + }; +} +function checkIsRepoRootTask() { + const commands2 = ["rev-parse", "--git-dir"]; + return { + commands: commands2, + format: "utf-8", + onError, + parser(path2) { + return /^\.(git)?$/.test(path2.trim()); + } + }; +} +function checkIsBareRepoTask() { + const commands2 = ["rev-parse", "--is-bare-repository"]; + return { + commands: commands2, + format: "utf-8", + onError, + parser + }; +} +function isNotRepoMessage(error) { + return /(Not a git repository|Kein Git-Repository)/i.test(String(error)); +} +var CheckRepoActions; +var onError; +var parser; +var init_check_is_repo = __esm2({ + "src/lib/tasks/check-is-repo.ts"() { + init_utils(); + CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { + CheckRepoActions2["BARE"] = "bare"; + CheckRepoActions2["IN_TREE"] = "tree"; + CheckRepoActions2["IS_REPO_ROOT"] = "root"; + return CheckRepoActions2; + })(CheckRepoActions || {}); + onError = ({ exitCode }, error, done, fail) => { + if (exitCode === 128 && isNotRepoMessage(error)) { + return done(Buffer.from("false")); + } + fail(error); + }; + parser = (text2) => { + return text2.trim() === "true"; + }; + } +}); +function cleanSummaryParser(dryRun, text2) { + const summary = new CleanResponse(dryRun); + const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp; + toLinesWithContent(text2).forEach((line) => { + const removed = line.replace(regexp, ""); + summary.paths.push(removed); + (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed); + }); + return summary; +} +var CleanResponse; +var removalRegexp; +var dryRunRemovalRegexp; +var isFolderRegexp; +var init_CleanSummary = __esm2({ + "src/lib/responses/CleanSummary.ts"() { + init_utils(); + CleanResponse = class { + constructor(dryRun) { + this.dryRun = dryRun; + this.paths = []; + this.files = []; + this.folders = []; + } + }; + removalRegexp = /^[a-z]+\s*/i; + dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i; + isFolderRegexp = /\/$/; + } +}); +var task_exports = {}; +__export2(task_exports, { + EMPTY_COMMANDS: () => EMPTY_COMMANDS, + adhocExecTask: () => adhocExecTask, + configurationErrorTask: () => configurationErrorTask, + isBufferTask: () => isBufferTask, + isEmptyTask: () => isEmptyTask, + straightThroughBufferTask: () => straightThroughBufferTask, + straightThroughStringTask: () => straightThroughStringTask +}); +function adhocExecTask(parser3) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser: parser3 + }; +} +function configurationErrorTask(error) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser() { + throw typeof error === "string" ? new TaskConfigurationError(error) : error; + } + }; +} +function straightThroughStringTask(commands2, trimmed2 = false) { + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return trimmed2 ? String(text2).trim() : text2; + } + }; +} +function straightThroughBufferTask(commands2) { + return { + commands: commands2, + format: "buffer", + parser(buffer2) { + return buffer2; + } + }; +} +function isBufferTask(task) { + return task.format === "buffer"; +} +function isEmptyTask(task) { + return task.format === "empty" || !task.commands.length; +} +var EMPTY_COMMANDS; +var init_task = __esm2({ + "src/lib/tasks/task.ts"() { + init_task_configuration_error(); + EMPTY_COMMANDS = []; + } +}); +var clean_exports = {}; +__export2(clean_exports, { + CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE, + CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED, + CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION, + CleanOptions: () => CleanOptions, + cleanTask: () => cleanTask, + cleanWithOptionsTask: () => cleanWithOptionsTask, + isCleanOptionsArray: () => isCleanOptionsArray +}); +function cleanWithOptionsTask(mode, customArgs) { + const { cleanMode, options, valid } = getCleanOptions(mode); + if (!cleanMode) { + return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED); + } + if (!valid.options) { + return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode)); + } + options.push(...customArgs); + if (options.some(isInteractiveMode)) { + return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE); + } + return cleanTask(cleanMode, options); +} +function cleanTask(mode, customArgs) { + const commands2 = ["clean", `-${mode}`, ...customArgs]; + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return cleanSummaryParser(mode === "n", text2); + } + }; +} +function isCleanOptionsArray(input) { + return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test)); +} +function getCleanOptions(input) { + let cleanMode; + let options = []; + let valid = { cleanMode: false, options: true }; + input.replace(/[^a-z]i/g, "").split("").forEach((char) => { + if (isCleanMode(char)) { + cleanMode = char; + valid.cleanMode = true; + } else { + valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`); + } + }); + return { + cleanMode, + options, + valid + }; +} +function isCleanMode(cleanMode) { + return cleanMode === "f" || cleanMode === "n"; +} +function isKnownOption(option) { + return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1)); +} +function isInteractiveMode(option) { + if (/^-[^\-]/.test(option)) { + return option.indexOf("i") > 0; + } + return option === "--interactive"; +} +var CONFIG_ERROR_INTERACTIVE_MODE; +var CONFIG_ERROR_MODE_REQUIRED; +var CONFIG_ERROR_UNKNOWN_OPTION; +var CleanOptions; +var CleanOptionValues; +var init_clean = __esm2({ + "src/lib/tasks/clean.ts"() { + init_CleanSummary(); + init_utils(); + init_task(); + CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; + CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; + CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; + CleanOptions = /* @__PURE__ */ ((CleanOptions2) => { + CleanOptions2["DRY_RUN"] = "n"; + CleanOptions2["FORCE"] = "f"; + CleanOptions2["IGNORED_INCLUDED"] = "x"; + CleanOptions2["IGNORED_ONLY"] = "X"; + CleanOptions2["EXCLUDING"] = "e"; + CleanOptions2["QUIET"] = "q"; + CleanOptions2["RECURSIVE"] = "d"; + return CleanOptions2; + })(CleanOptions || {}); + CleanOptionValues = /* @__PURE__ */ new Set([ + "i", + ...asStringArray(Object.values(CleanOptions)) + ]); + } +}); +function configListParser(text2) { + const config = new ConfigList(); + for (const item of configParser(text2)) { + config.addValue(item.file, String(item.key), item.value); + } + return config; +} +function configGetParser(text2, key2) { + let value = null; + const values = []; + const scopes = /* @__PURE__ */ new Map(); + for (const item of configParser(text2, key2)) { + if (item.key !== key2) { + continue; + } + values.push(value = item.value); + if (!scopes.has(item.file)) { + scopes.set(item.file, []); + } + scopes.get(item.file).push(value); + } + return { + key: key2, + paths: Array.from(scopes.keys()), + scopes, + value, + values + }; +} +function configFilePath(filePath) { + return filePath.replace(/^(file):/, ""); +} +function* configParser(text2, requestedKey = null) { + const lines = text2.split("\0"); + for (let i = 0, max = lines.length - 1; i < max; ) { + const file = configFilePath(lines[i++]); + let value = lines[i++]; + let key2 = requestedKey; + if (value.includes("\n")) { + const line = splitOn(value, "\n"); + key2 = line[0]; + value = line[1]; + } + yield { file, key: key2, value }; + } +} +var ConfigList; +var init_ConfigList = __esm2({ + "src/lib/responses/ConfigList.ts"() { + init_utils(); + ConfigList = class { + constructor() { + this.files = []; + this.values = /* @__PURE__ */ Object.create(null); + } + get all() { + if (!this._all) { + this._all = this.files.reduce((all, file) => { + return Object.assign(all, this.values[file]); + }, {}); + } + return this._all; + } + addFile(file) { + if (!(file in this.values)) { + const latest = last(this.files); + this.values[file] = latest ? Object.create(this.values[latest]) : {}; + this.files.push(file); + } + return this.values[file]; + } + addValue(file, key2, value) { + const values = this.addFile(file); + if (!values.hasOwnProperty(key2)) { + values[key2] = value; + } else if (Array.isArray(values[key2])) { + values[key2].push(value); + } else { + values[key2] = [values[key2], value]; + } + this._all = void 0; + } + }; + } +}); +function asConfigScope(scope, fallback) { + if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) { + return scope; + } + return fallback; +} +function addConfigTask(key2, value, append22, scope) { + const commands2 = ["config", `--${scope}`]; + if (append22) { + commands2.push("--add"); + } + commands2.push(key2, value); + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return text2; + } + }; +} +function getConfigTask(key2, scope) { + const commands2 = ["config", "--null", "--show-origin", "--get-all", key2]; + if (scope) { + commands2.splice(1, 0, `--${scope}`); + } + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return configGetParser(text2, key2); + } + }; +} +function listConfigTask(scope) { + const commands2 = ["config", "--list", "--show-origin", "--null"]; + if (scope) { + commands2.push(`--${scope}`); + } + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return configListParser(text2); + } + }; +} +function config_default() { + return { + addConfig(key2, value, ...rest) { + return this._runTask(addConfigTask(key2, value, rest[0] === true, asConfigScope( + rest[1], + "local" + /* local */ + )), trailingFunctionArgument(arguments)); + }, + getConfig(key2, scope) { + return this._runTask(getConfigTask(key2, asConfigScope(scope, void 0)), trailingFunctionArgument(arguments)); + }, + listConfig(...rest) { + return this._runTask(listConfigTask(asConfigScope(rest[0], void 0)), trailingFunctionArgument(arguments)); + } + }; +} +var GitConfigScope; +var init_config = __esm2({ + "src/lib/tasks/config.ts"() { + init_ConfigList(); + init_utils(); + GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { + GitConfigScope2["system"] = "system"; + GitConfigScope2["global"] = "global"; + GitConfigScope2["local"] = "local"; + GitConfigScope2["worktree"] = "worktree"; + return GitConfigScope2; + })(GitConfigScope || {}); + } +}); +function grepQueryBuilder(...params) { + return new GrepQuery().param(...params); +} +function parseGrep(grep) { + const paths = /* @__PURE__ */ new Set(); + const results = {}; + forEachLineWithContent(grep, (input) => { + const [path2, line, preview] = input.split(NULL); + paths.add(path2); + (results[path2] = results[path2] || []).push({ + line: asNumber(line), + path: path2, + preview + }); + }); + return { + paths, + results + }; +} +function grep_default() { + return { + grep(searchTerm) { + const then = trailingFunctionArgument(arguments); + const options = getTrailingOptions(arguments); + for (const option of disallowedOptions) { + if (options.includes(option)) { + return this._runTask(configurationErrorTask(`git.grep: use of "${option}" is not supported.`), then); + } + } + if (typeof searchTerm === "string") { + searchTerm = grepQueryBuilder().param(searchTerm); + } + const commands2 = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm]; + return this._runTask({ + commands: commands2, + format: "utf-8", + parser(stdOut) { + return parseGrep(stdOut); + } + }, then); + } + }; +} +var disallowedOptions; +var Query; +var _a; +var GrepQuery; +var init_grep = __esm2({ + "src/lib/tasks/grep.ts"() { + init_utils(); + init_task(); + disallowedOptions = ["-h"]; + Query = Symbol("grepQuery"); + GrepQuery = class { + constructor() { + this[_a] = []; + } + *[(_a = Query, Symbol.iterator)]() { + for (const query of this[Query]) { + yield query; + } + } + and(...and) { + and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")"); + return this; + } + param(...param) { + this[Query].push(...prefixedArray(param, "-e")); + return this; + } + }; + } +}); +var reset_exports = {}; +__export2(reset_exports, { + ResetMode: () => ResetMode, + getResetMode: () => getResetMode, + resetTask: () => resetTask +}); +function resetTask(mode, customArgs) { + const commands2 = ["reset"]; + if (isValidResetMode(mode)) { + commands2.push(`--${mode}`); + } + commands2.push(...customArgs); + return straightThroughStringTask(commands2); +} +function getResetMode(mode) { + if (isValidResetMode(mode)) { + return mode; + } + switch (typeof mode) { + case "string": + case "undefined": + return "soft"; + } + return; +} +function isValidResetMode(mode) { + return ResetModes.includes(mode); +} +var ResetMode; +var ResetModes; +var init_reset = __esm2({ + "src/lib/tasks/reset.ts"() { + init_task(); + ResetMode = /* @__PURE__ */ ((ResetMode2) => { + ResetMode2["MIXED"] = "mixed"; + ResetMode2["SOFT"] = "soft"; + ResetMode2["HARD"] = "hard"; + ResetMode2["MERGE"] = "merge"; + ResetMode2["KEEP"] = "keep"; + return ResetMode2; + })(ResetMode || {}); + ResetModes = Array.from(Object.values(ResetMode)); + } +}); +function createLog() { + return (0, import_debug.default)("simple-git"); +} +function prefixedLogger(to, prefix, forward) { + if (!prefix || !String(prefix).replace(/\s*/, "")) { + return !forward ? to : (message, ...args) => { + to(message, ...args); + forward(message, ...args); + }; + } + return (message, ...args) => { + to(`%s ${message}`, prefix, ...args); + if (forward) { + forward(message, ...args); + } + }; +} +function childLoggerName(name, childDebugger, { namespace: parentNamespace }) { + if (typeof name === "string") { + return name; + } + const childNamespace = childDebugger && childDebugger.namespace || ""; + if (childNamespace.startsWith(parentNamespace)) { + return childNamespace.substr(parentNamespace.length + 1); + } + return childNamespace || parentNamespace; +} +function createLogger(label, verbose, initialStep, infoDebugger = createLog()) { + const labelPrefix = label && `[${label}]` || ""; + const spawned = []; + const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose; + const key2 = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger); + return step(initialStep); + function sibling(name, initial) { + return append(spawned, createLogger(label, key2.replace(/^[^:]+/, name), initial, infoDebugger)); + } + function step(phase) { + const stepPrefix = phase && `[${phase}]` || ""; + const debug22 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP; + const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug22); + return Object.assign(debugDebugger ? debug22 : info, { + label, + sibling, + info, + step + }); + } +} +var init_git_logger = __esm2({ + "src/lib/git-logger.ts"() { + init_utils(); + import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); + import_debug.default.formatters.B = (value) => { + if (Buffer.isBuffer(value)) { + return value.toString("utf8"); + } + return objectToString(value); + }; + } +}); +var _TasksPendingQueue; +var TasksPendingQueue; +var init_tasks_pending_queue = __esm2({ + "src/lib/runners/tasks-pending-queue.ts"() { + init_git_error(); + init_git_logger(); + _TasksPendingQueue = class { + constructor(logLabel = "GitExecutor") { + this.logLabel = logLabel; + this._queue = /* @__PURE__ */ new Map(); + } + withProgress(task) { + return this._queue.get(task); + } + createProgress(task) { + const name = _TasksPendingQueue.getName(task.commands[0]); + const logger = createLogger(this.logLabel, name); + return { + task, + logger, + name + }; + } + push(task) { + const progress = this.createProgress(task); + progress.logger("Adding task to the queue, commands = %o", task.commands); + this._queue.set(task, progress); + return progress; + } + fatal(err) { + for (const [task, { logger }] of Array.from(this._queue.entries())) { + if (task === err.task) { + logger.info(`Failed %o`, err); + logger(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`); + } else { + logger.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`, err.message); + } + this.complete(task); + } + if (this._queue.size !== 0) { + throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`); + } + } + complete(task) { + const progress = this.withProgress(task); + if (progress) { + this._queue.delete(task); + } + } + attempt(task) { + const progress = this.withProgress(task); + if (!progress) { + throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task"); + } + progress.logger("Starting task"); + return progress; + } + static getName(name = "empty") { + return `task:${name}:${++_TasksPendingQueue.counter}`; + } + }; + TasksPendingQueue = _TasksPendingQueue; + TasksPendingQueue.counter = 0; + } +}); +function pluginContext(task, commands2) { + return { + method: first(task.commands) || "", + commands: commands2 + }; +} +function onErrorReceived(target, logger) { + return (err) => { + logger(`[ERROR] child process exception %o`, err); + target.push(Buffer.from(String(err.stack), "ascii")); + }; +} +function onDataReceived(target, name, logger, output) { + return (buffer2) => { + logger(`%s received %L bytes`, name, buffer2); + output(`%B`, buffer2); + target.push(buffer2); + }; +} +var GitExecutorChain; +var init_git_executor_chain = __esm2({ + "src/lib/runners/git-executor-chain.ts"() { + init_git_error(); + init_task(); + init_utils(); + init_tasks_pending_queue(); + GitExecutorChain = class { + constructor(_executor, _scheduler, _plugins) { + this._executor = _executor; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = Promise.resolve(); + this._queue = new TasksPendingQueue(); + } + get binary() { + return this._executor.binary; + } + get cwd() { + return this._cwd || this._executor.cwd; + } + set cwd(cwd) { + this._cwd = cwd; + } + get env() { + return this._executor.env; + } + get outputHandler() { + return this._executor.outputHandler; + } + chain() { + return this; + } + push(task) { + this._queue.push(task); + return this._chain = this._chain.then(() => this.attemptTask(task)); + } + attemptTask(task) { + return __async(this, null, function* () { + const onScheduleComplete = yield this._scheduler.next(); + const onQueueComplete = () => this._queue.complete(task); + try { + const { logger } = this._queue.attempt(task); + return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger); + } catch (e) { + throw this.onFatalException(task, e); + } finally { + onQueueComplete(); + onScheduleComplete(); + } + }); + } + onFatalException(task, e) { + const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e)); + this._chain = Promise.resolve(); + this._queue.fatal(gitError); + return gitError; + } + attemptRemoteTask(task, logger) { + return __async(this, null, function* () { + const args = this._plugins.exec("spawn.args", [...task.commands], pluginContext(task, task.commands)); + const raw = yield this.gitResponse(task, this.binary, args, this.outputHandler, logger.step("SPAWN")); + const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE")); + logger(`passing response to task's parser as a %s`, task.format); + if (isBufferTask(task)) { + return callTaskParser(task.parser, outputStreams); + } + return callTaskParser(task.parser, outputStreams.asStrings()); + }); + } + attemptEmptyTask(task, logger) { + return __async(this, null, function* () { + logger(`empty task bypassing child process to call to task's parser`); + return task.parser(this); + }); + } + handleTaskData(task, args, result, logger) { + const { exitCode, rejection, stdOut, stdErr } = result; + return new Promise((done, fail) => { + logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode); + const { error } = this._plugins.exec("task.error", { error: rejection }, __spreadValues(__spreadValues({}, pluginContext(task, args)), result)); + if (error && task.onError) { + logger.info(`exitCode=%s handling with custom error handler`); + return task.onError(result, error, (newStdOut) => { + logger.info(`custom error handler treated as success`); + logger(`custom error returned a %s`, objectToString(newStdOut)); + done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, Buffer.concat(stdErr))); + }, fail); + } + if (error) { + logger.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`, exitCode, stdErr.length, rejection); + return fail(error); + } + logger.info(`retrieving task output complete`); + done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr))); + }); + } + gitResponse(task, command, args, outputHandler, logger) { + return __async(this, null, function* () { + const outputLogger = logger.sibling("output"); + const spawnOptions = this._plugins.exec("spawn.options", { + cwd: this.cwd, + env: this.env, + windowsHide: true + }, pluginContext(task, task.commands)); + return new Promise((done) => { + const stdOut = []; + const stdErr = []; + logger.info(`%s %o`, command, args); + logger("%O", spawnOptions); + let rejection = this._beforeSpawn(task, args); + if (rejection) { + return done({ + stdOut, + stdErr, + exitCode: 9901, + rejection + }); + } + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + const spawned = (0, import_child_process.spawn)(command, args, spawnOptions); + spawned.stdout.on("data", onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut"))); + spawned.stderr.on("data", onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr"))); + spawned.on("error", onErrorReceived(stdErr, logger)); + if (outputHandler) { + logger(`Passing child process stdOut/stdErr to custom outputHandler`); + outputHandler(command, spawned.stdout, spawned.stderr, [...args]); + } + this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + spawned, + close(exitCode, reason) { + done({ + stdOut, + stdErr, + exitCode, + rejection: rejection || reason + }); + }, + kill(reason) { + if (spawned.killed) { + return; + } + rejection = reason; + spawned.kill("SIGINT"); + } + })); + }); + }); + } + _beforeSpawn(task, args) { + let rejection; + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + return rejection; + } + }; + } +}); +var git_executor_exports = {}; +__export2(git_executor_exports, { + GitExecutor: () => GitExecutor +}); +var GitExecutor; +var init_git_executor = __esm2({ + "src/lib/runners/git-executor.ts"() { + init_git_executor_chain(); + GitExecutor = class { + constructor(binary = "git", cwd, _scheduler, _plugins) { + this.binary = binary; + this.cwd = cwd; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = new GitExecutorChain(this, this._scheduler, this._plugins); + } + chain() { + return new GitExecutorChain(this, this._scheduler, this._plugins); + } + push(task) { + return this._chain.push(task); + } + }; + } +}); +function taskCallback(task, response, callback = NOOP) { + const onSuccess = (data) => { + callback(null, data); + }; + const onError2 = (err) => { + if ((err == null ? void 0 : err.task) === task) { + callback(err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, void 0); + } + }; + response.then(onSuccess, onError2); +} +function addDeprecationNoticeToError(err) { + let log2 = (name) => { + console.warn(`simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`); + log2 = NOOP; + }; + return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {})); + function descriptorReducer(all, name) { + if (name in err) { + return all; + } + all[name] = { + enumerable: false, + configurable: false, + get() { + log2(name); + return err.git[name]; + } + }; + return all; + } +} +var init_task_callback = __esm2({ + "src/lib/task-callback.ts"() { + init_git_response_error(); + init_utils(); + } +}); +function changeWorkingDirectoryTask(directory, root2) { + return adhocExecTask((instance10) => { + if (!folderExists(directory)) { + throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`); + } + return (root2 || instance10).cwd = directory; + }); +} +var init_change_working_directory = __esm2({ + "src/lib/tasks/change-working-directory.ts"() { + init_utils(); + init_task(); + } +}); +function checkoutTask(args) { + const commands2 = ["checkout", ...args]; + if (commands2[1] === "-b" && commands2.includes("-B")) { + commands2[1] = remove2(commands2, "-B"); + } + return straightThroughStringTask(commands2); +} +function checkout_default() { + return { + checkout() { + return this._runTask(checkoutTask(getTrailingOptions(arguments, 1)), trailingFunctionArgument(arguments)); + }, + checkoutBranch(branchName, startPoint) { + return this._runTask(checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + }, + checkoutLocalBranch(branchName) { + return this._runTask(checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + }; +} +var init_checkout = __esm2({ + "src/lib/tasks/checkout.ts"() { + init_utils(); + init_task(); + } +}); +function parseCommitResult(stdOut) { + const result = { + author: null, + branch: "", + commit: "", + root: false, + summary: { + changes: 0, + insertions: 0, + deletions: 0 + } + }; + return parseStringResponse(result, parsers, stdOut); +} +var parsers; +var init_parse_commit = __esm2({ + "src/lib/parsers/parse-commit.ts"() { + init_utils(); + parsers = [ + new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch2, root2, commit2]) => { + result.branch = branch2; + result.commit = commit2; + result.root = !!root2; + }), + new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => { + const parts = author.split("<"); + const email = parts.pop(); + if (!email || !email.includes("@")) { + return; + } + result.author = { + email: email.substr(0, email.length - 1), + name: parts.join("<").trim() + }; + }), + new LineParser(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, (result, [changes, insertions, deletions]) => { + result.summary.changes = parseInt(changes, 10) || 0; + result.summary.insertions = parseInt(insertions, 10) || 0; + result.summary.deletions = parseInt(deletions, 10) || 0; + }), + new LineParser(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, (result, [changes, lines, direction]) => { + result.summary.changes = parseInt(changes, 10) || 0; + const count = parseInt(lines, 10) || 0; + if (direction === "-") { + result.summary.deletions = count; + } else if (direction === "+") { + result.summary.insertions = count; + } + }) + ]; + } +}); +function commitTask(message, files, customArgs) { + const commands2 = [ + "-c", + "core.abbrev=40", + "commit", + ...prefixedArray(message, "-m"), + ...files, + ...customArgs + ]; + return { + commands: commands2, + format: "utf-8", + parser: parseCommitResult + }; +} +function commit_default() { + return { + commit(message, ...rest) { + const next = trailingFunctionArgument(arguments); + const task = rejectDeprecatedSignatures(message) || commitTask(asArray(message), asArray(filterType(rest[0], filterStringOrStringArray, [])), [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]); + return this._runTask(task, next); + } + }; + function rejectDeprecatedSignatures(message) { + return !filterStringOrStringArray(message) && configurationErrorTask(`git.commit: requires the commit message to be supplied as a string/string[]`); + } +} +var init_commit = __esm2({ + "src/lib/tasks/commit.ts"() { + init_parse_commit(); + init_utils(); + init_task(); + } +}); +function hashObjectTask(filePath, write) { + const commands2 = ["hash-object", filePath]; + if (write) { + commands2.push("-w"); + } + return straightThroughStringTask(commands2, true); +} +var init_hash_object = __esm2({ + "src/lib/tasks/hash-object.ts"() { + init_task(); + } +}); +function parseInit(bare, path2, text2) { + const response = String(text2).trim(); + let result; + if (result = initResponseRegex.exec(response)) { + return new InitSummary(bare, path2, false, result[1]); + } + if (result = reInitResponseRegex.exec(response)) { + return new InitSummary(bare, path2, true, result[1]); + } + let gitDir = ""; + const tokens = response.split(" "); + while (tokens.length) { + const token = tokens.shift(); + if (token === "in") { + gitDir = tokens.join(" "); + break; + } + } + return new InitSummary(bare, path2, /^re/i.test(response), gitDir); +} +var InitSummary; +var initResponseRegex; +var reInitResponseRegex; +var init_InitSummary = __esm2({ + "src/lib/responses/InitSummary.ts"() { + InitSummary = class { + constructor(bare, path2, existing, gitDir) { + this.bare = bare; + this.path = path2; + this.existing = existing; + this.gitDir = gitDir; + } + }; + initResponseRegex = /^Init.+ repository in (.+)$/; + reInitResponseRegex = /^Rein.+ in (.+)$/; + } +}); +function hasBareCommand(command) { + return command.includes(bareCommand); +} +function initTask(bare = false, path2, customArgs) { + const commands2 = ["init", ...customArgs]; + if (bare && !hasBareCommand(commands2)) { + commands2.splice(1, 0, bareCommand); + } + return { + commands: commands2, + format: "utf-8", + parser(text2) { + return parseInit(commands2.includes("--bare"), path2, text2); + } + }; +} +var bareCommand; +var init_init = __esm2({ + "src/lib/tasks/init.ts"() { + init_InitSummary(); + bareCommand = "--bare"; + } +}); +function logFormatFromCommand(customArgs) { + for (let i = 0; i < customArgs.length; i++) { + const format = logFormatRegex.exec(customArgs[i]); + if (format) { + return `--${format[1]}`; + } + } + return ""; +} +function isLogFormat(customArg) { + return logFormatRegex.test(customArg); +} +var logFormatRegex; +var init_log_format = __esm2({ + "src/lib/args/log-format.ts"() { + logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/; + } +}); +var DiffSummary; +var init_DiffSummary = __esm2({ + "src/lib/responses/DiffSummary.ts"() { + DiffSummary = class { + constructor() { + this.changed = 0; + this.deletions = 0; + this.insertions = 0; + this.files = []; + } + }; + } +}); +function getDiffParser(format = "") { + const parser3 = diffSummaryParsers[format]; + return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false); +} +var statParser; +var numStatParser; +var nameOnlyParser; +var nameStatusParser; +var diffSummaryParsers; +var init_parse_diff_summary = __esm2({ + "src/lib/parsers/parse-diff-summary.ts"() { + init_log_format(); + init_DiffSummary(); + init_utils(); + statParser = [ + new LineParser(/(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, (result, [file, changes, alterations = ""]) => { + result.files.push({ + file: file.trim(), + changes: asNumber(changes), + insertions: alterations.replace(/[^+]/g, "").length, + deletions: alterations.replace(/[^-]/g, "").length, + binary: false + }); + }), + new LineParser(/(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, (result, [file, before, after]) => { + result.files.push({ + file: file.trim(), + before: asNumber(before), + after: asNumber(after), + binary: true + }); + }), + new LineParser(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, (result, [changed, summary]) => { + const inserted = /(\d+) i/.exec(summary); + const deleted = /(\d+) d/.exec(summary); + result.changed = asNumber(changed); + result.insertions = asNumber(inserted == null ? void 0 : inserted[1]); + result.deletions = asNumber(deleted == null ? void 0 : deleted[1]); + }) + ]; + numStatParser = [ + new LineParser(/(\d+)\t(\d+)\t(.+)$/, (result, [changesInsert, changesDelete, file]) => { + const insertions = asNumber(changesInsert); + const deletions = asNumber(changesDelete); + result.changed++; + result.insertions += insertions; + result.deletions += deletions; + result.files.push({ + file, + changes: insertions + deletions, + insertions, + deletions, + binary: false + }); + }), + new LineParser(/-\t-\t(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + after: 0, + before: 0, + binary: true + }); + }) + ]; + nameOnlyParser = [ + new LineParser(/(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + nameStatusParser = [ + new LineParser(/([ACDMRTUXB])([0-9][0-9][0-9])?\t(.[^\t]+)\t?(.*)?$/, (result, [status2, _similarity, from, to]) => { + result.changed++; + result.files.push({ + file: to != null ? to : from, + changes: 0, + status: status2, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + diffSummaryParsers = { + [ + "" + /* NONE */ + ]: statParser, + [ + "--stat" + /* STAT */ + ]: statParser, + [ + "--numstat" + /* NUM_STAT */ + ]: numStatParser, + [ + "--name-status" + /* NAME_STATUS */ + ]: nameStatusParser, + [ + "--name-only" + /* NAME_ONLY */ + ]: nameOnlyParser + }; + } +}); +function lineBuilder(tokens, fields) { + return fields.reduce((line, field, index2) => { + line[field] = tokens[index2] || ""; + return line; + }, /* @__PURE__ */ Object.create({ diff: null })); +} +function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "") { + const parseDiffResult = getDiffParser(logFormat); + return function(stdOut) { + const all = toLinesWithContent(stdOut, true, START_BOUNDARY).map(function(item) { + const lineDetail = item.trim().split(COMMIT_BOUNDARY); + const listLogLine = lineBuilder(lineDetail[0].trim().split(splitter), fields); + if (lineDetail.length > 1 && !!lineDetail[1].trim()) { + listLogLine.diff = parseDiffResult(lineDetail[1]); + } + return listLogLine; + }); + return { + all, + latest: all.length && all[0] || null, + total: all.length + }; + }; +} +var START_BOUNDARY; +var COMMIT_BOUNDARY; +var SPLITTER; +var defaultFieldNames; +var init_parse_list_log_summary = __esm2({ + "src/lib/parsers/parse-list-log-summary.ts"() { + init_utils(); + init_parse_diff_summary(); + init_log_format(); + START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 "; + COMMIT_BOUNDARY = " \xF2\xF2"; + SPLITTER = " \xF2 "; + defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"]; + } +}); +var diff_exports = {}; +__export2(diff_exports, { + diffSummaryTask: () => diffSummaryTask, + validateLogFormatConfig: () => validateLogFormatConfig +}); +function diffSummaryTask(customArgs) { + let logFormat = logFormatFromCommand(customArgs); + const commands2 = ["diff"]; + if (logFormat === "") { + logFormat = "--stat"; + commands2.push("--stat=4096"); + } + commands2.push(...customArgs); + return validateLogFormatConfig(commands2) || { + commands: commands2, + format: "utf-8", + parser: getDiffParser(logFormat) + }; +} +function validateLogFormatConfig(customArgs) { + const flags = customArgs.filter(isLogFormat); + if (flags.length > 1) { + return configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${flags.join(",")}`); + } + if (flags.length && customArgs.includes("-z")) { + return configurationErrorTask(`Summary flag ${flags} parsing is not compatible with null termination option '-z'`); + } +} +var init_diff = __esm2({ + "src/lib/tasks/diff.ts"() { + init_log_format(); + init_parse_diff_summary(); + init_task(); + } +}); +function prettyFormat(format, splitter) { + const fields = []; + const formatStr = []; + Object.keys(format).forEach((field) => { + fields.push(field); + formatStr.push(String(format[field])); + }); + return [fields, formatStr.join(splitter)]; +} +function userOptions(input) { + return Object.keys(input).reduce((out, key2) => { + if (!(key2 in excludeOptions)) { + out[key2] = input[key2]; + } + return out; + }, {}); +} +function parseLogOptions(opt = {}, customArgs = []) { + const splitter = filterType(opt.splitter, filterString, SPLITTER); + const format = !filterPrimitives(opt.format) && opt.format ? opt.format : { + hash: "%H", + date: opt.strictDate === false ? "%ai" : "%aI", + message: "%s", + refs: "%D", + body: opt.multiLine ? "%B" : "%b", + author_name: opt.mailMap !== false ? "%aN" : "%an", + author_email: opt.mailMap !== false ? "%aE" : "%ae" + }; + const [fields, formatStr] = prettyFormat(format, splitter); + const suffix = []; + const command = [ + `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`, + ...customArgs + ]; + const maxCount = opt.n || opt["max-count"] || opt.maxCount; + if (maxCount) { + command.push(`--max-count=${maxCount}`); + } + if (opt.from || opt.to) { + const rangeOperator = opt.symmetric !== false ? "..." : ".."; + suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`); + } + if (filterString(opt.file)) { + suffix.push("--follow", opt.file); + } + appendTaskOptions(userOptions(opt), command); + return { + fields, + splitter, + commands: [...command, ...suffix] + }; +} +function logTask(splitter, fields, customArgs) { + const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs)); + return { + commands: ["log", ...customArgs], + format: "utf-8", + parser: parser3 + }; +} +function log_default() { + return { + log(...rest) { + const next = trailingFunctionArgument(arguments); + const options = parseLogOptions(trailingOptionsArgument(arguments), filterType(arguments[0], filterArray)); + const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options); + return this._runTask(task, next); + } + }; + function createLogTask(options) { + return logTask(options.splitter, options.fields, options.commands); + } + function rejectDeprecatedSignatures(from, to) { + return filterString(from) && filterString(to) && configurationErrorTask(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`); + } +} +var excludeOptions; +var init_log = __esm2({ + "src/lib/tasks/log.ts"() { + init_log_format(); + init_parse_list_log_summary(); + init_utils(); + init_task(); + init_diff(); + excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { + excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty"; + excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count"; + excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount"; + excludeOptions2[excludeOptions2["n"] = 3] = "n"; + excludeOptions2[excludeOptions2["file"] = 4] = "file"; + excludeOptions2[excludeOptions2["format"] = 5] = "format"; + excludeOptions2[excludeOptions2["from"] = 6] = "from"; + excludeOptions2[excludeOptions2["to"] = 7] = "to"; + excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter"; + excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric"; + excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap"; + excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine"; + excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate"; + return excludeOptions2; + })(excludeOptions || {}); + } +}); +var MergeSummaryConflict; +var MergeSummaryDetail; +var init_MergeSummary = __esm2({ + "src/lib/responses/MergeSummary.ts"() { + MergeSummaryConflict = class { + constructor(reason, file = null, meta) { + this.reason = reason; + this.file = file; + this.meta = meta; + } + toString() { + return `${this.file}:${this.reason}`; + } + }; + MergeSummaryDetail = class { + constructor() { + this.conflicts = []; + this.merges = []; + this.result = "success"; + } + get failed() { + return this.conflicts.length > 0; + } + get reason() { + return this.result; + } + toString() { + if (this.conflicts.length) { + return `CONFLICTS: ${this.conflicts.join(", ")}`; + } + return "OK"; + } + }; + } +}); +var PullSummary; +var PullFailedSummary; +var init_PullSummary = __esm2({ + "src/lib/responses/PullSummary.ts"() { + PullSummary = class { + constructor() { + this.remoteMessages = { + all: [] + }; + this.created = []; + this.deleted = []; + this.files = []; + this.deletions = {}; + this.insertions = {}; + this.summary = { + changes: 0, + deletions: 0, + insertions: 0 + }; + } + }; + PullFailedSummary = class { + constructor() { + this.remote = ""; + this.hash = { + local: "", + remote: "" + }; + this.branch = { + local: "", + remote: "" + }; + this.message = ""; + } + toString() { + return this.message; + } + }; + } +}); +function objectEnumerationResult(remoteMessages) { + return remoteMessages.objects = remoteMessages.objects || { + compressing: 0, + counting: 0, + enumerating: 0, + packReused: 0, + reused: { count: 0, delta: 0 }, + total: { count: 0, delta: 0 } + }; +} +function asObjectCount(source) { + const count = /^\s*(\d+)/.exec(source); + const delta = /delta (\d+)/i.exec(source); + return { + count: asNumber(count && count[1] || "0"), + delta: asNumber(delta && delta[1] || "0") + }; +} +var remoteMessagesObjectParsers; +var init_parse_remote_objects = __esm2({ + "src/lib/parsers/parse-remote-objects.ts"() { + init_utils(); + remoteMessagesObjectParsers = [ + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, (result, [action, count]) => { + const key2 = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key2]: asNumber(count) }); + }), + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, (result, [action, count]) => { + const key2 = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key2]: asNumber(count) }); + }), + new RemoteLineParser(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, (result, [total, reused, packReused]) => { + const objects = objectEnumerationResult(result.remoteMessages); + objects.total = asObjectCount(total); + objects.reused = asObjectCount(reused); + objects.packReused = asNumber(packReused); + }) + ]; + } +}); +function parseRemoteMessages(_stdOut, stdErr) { + return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr); +} +var parsers2; +var RemoteMessageSummary; +var init_parse_remote_messages = __esm2({ + "src/lib/parsers/parse-remote-messages.ts"() { + init_utils(); + init_parse_remote_objects(); + parsers2 = [ + new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text2]) => { + result.remoteMessages.all.push(text2.trim()); + return false; + }), + ...remoteMessagesObjectParsers, + new RemoteLineParser([/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], (result, [pullRequestUrl]) => { + result.remoteMessages.pullRequestUrl = pullRequestUrl; + }), + new RemoteLineParser([/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], (result, [count, summary, url]) => { + result.remoteMessages.vulnerabilities = { + count: asNumber(count), + summary, + url + }; + }) + ]; + RemoteMessageSummary = class { + constructor() { + this.all = []; + } + }; + } +}); +function parsePullErrorResult(stdOut, stdErr) { + const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]); + return pullError.message && pullError; +} +var FILE_UPDATE_REGEX; +var SUMMARY_REGEX; +var ACTION_REGEX; +var parsers3; +var errorParsers; +var parsePullDetail; +var parsePullResult; +var init_parse_pull = __esm2({ + "src/lib/parsers/parse-pull.ts"() { + init_PullSummary(); + init_utils(); + init_parse_remote_messages(); + FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; + SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; + ACTION_REGEX = /^(create|delete) mode \d+ (.+)/; + parsers3 = [ + new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => { + result.files.push(file); + if (insertions) { + result.insertions[file] = insertions.length; + } + if (deletions) { + result.deletions[file] = deletions.length; + } + }), + new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => { + if (insertions !== void 0 || deletions !== void 0) { + result.summary.changes = +changes || 0; + result.summary.insertions = +insertions || 0; + result.summary.deletions = +deletions || 0; + return true; + } + return false; + }), + new LineParser(ACTION_REGEX, (result, [action, file]) => { + append(result.files, file); + append(action === "create" ? result.created : result.deleted, file); + }) + ]; + errorParsers = [ + new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)), + new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)), + new LineParser(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => { + result.branch.local = branchLocal; + result.hash.local = hashLocal; + result.branch.remote = branchRemote; + result.hash.remote = hashRemote; + }) + ]; + parsePullDetail = (stdOut, stdErr) => { + return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]); + }; + parsePullResult = (stdOut, stdErr) => { + return Object.assign(new PullSummary(), parsePullDetail(stdOut, stdErr), parseRemoteMessages(stdOut, stdErr)); + }; + } +}); +var parsers4; +var parseMergeResult; +var parseMergeDetail; +var init_parse_merge = __esm2({ + "src/lib/parsers/parse-merge.ts"() { + init_MergeSummary(); + init_utils(); + init_parse_pull(); + parsers4 = [ + new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { + summary.merges.push(autoMerge); + }), + new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file)); + }), + new LineParser(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, (summary, [reason, file, deleteRef2]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef: deleteRef2 })); + }), + new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, null)); + }), + new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => { + summary.result = result; + }) + ]; + parseMergeResult = (stdOut, stdErr) => { + return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr)); + }; + parseMergeDetail = (stdOut) => { + return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut); + }; + } +}); +function mergeTask(customArgs) { + if (!customArgs.length) { + return configurationErrorTask("Git.merge requires at least one option"); + } + return { + commands: ["merge", ...customArgs], + format: "utf-8", + parser(stdOut, stdErr) { + const merge2 = parseMergeResult(stdOut, stdErr); + if (merge2.failed) { + throw new GitResponseError(merge2); + } + return merge2; + } + }; +} +var init_merge = __esm2({ + "src/lib/tasks/merge.ts"() { + init_git_response_error(); + init_parse_merge(); + init_task(); + } +}); +function pushResultPushedItem(local, remote, status2) { + const deleted = status2.includes("deleted"); + const tag2 = status2.includes("tag") || /^refs\/tags/.test(local); + const alreadyUpdated = !status2.includes("new"); + return { + deleted, + tag: tag2, + branch: !tag2, + new: !alreadyUpdated, + alreadyUpdated, + local, + remote + }; +} +var parsers5; +var parsePushResult; +var parsePushDetail; +var init_parse_push = __esm2({ + "src/lib/parsers/parse-push.ts"() { + init_utils(); + init_parse_remote_messages(); + parsers5 = [ + new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { + result.repo = repo; + }), + new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => { + result.ref = __spreadProps(__spreadValues({}, result.ref || {}), { + local + }); + }), + new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => { + result.pushed.push(pushResultPushedItem(local, remote, type)); + }), + new LineParser(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, (result, [local, remote, remoteName]) => { + result.branch = __spreadProps(__spreadValues({}, result.branch || {}), { + local, + remote, + remoteName + }); + }), + new LineParser(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, (result, [local, remote, from, to]) => { + result.update = { + head: { + local, + remote + }, + hash: { + from, + to + } + }; + }) + ]; + parsePushResult = (stdOut, stdErr) => { + const pushDetail = parsePushDetail(stdOut, stdErr); + const responseDetail = parseRemoteMessages(stdOut, stdErr); + return __spreadValues(__spreadValues({}, pushDetail), responseDetail); + }; + parsePushDetail = (stdOut, stdErr) => { + return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]); + }; + } +}); +var push_exports = {}; +__export2(push_exports, { + pushTagsTask: () => pushTagsTask, + pushTask: () => pushTask +}); +function pushTagsTask(ref = {}, customArgs) { + append(customArgs, "--tags"); + return pushTask(ref, customArgs); +} +function pushTask(ref = {}, customArgs) { + const commands2 = ["push", ...customArgs]; + if (ref.branch) { + commands2.splice(1, 0, ref.branch); + } + if (ref.remote) { + commands2.splice(1, 0, ref.remote); + } + remove2(commands2, "-v"); + append(commands2, "--verbose"); + append(commands2, "--porcelain"); + return { + commands: commands2, + format: "utf-8", + parser: parsePushResult + }; +} +var init_push = __esm2({ + "src/lib/tasks/push.ts"() { + init_parse_push(); + init_utils(); + } +}); +var fromPathRegex; +var FileStatusSummary; +var init_FileStatusSummary = __esm2({ + "src/lib/responses/FileStatusSummary.ts"() { + fromPathRegex = /^(.+) -> (.+)$/; + FileStatusSummary = class { + constructor(path2, index2, working_dir) { + this.path = path2; + this.index = index2; + this.working_dir = working_dir; + if (index2 + working_dir === "R") { + const detail = fromPathRegex.exec(path2) || [null, path2, path2]; + this.from = detail[1] || ""; + this.path = detail[2] || ""; + } + } + }; + } +}); +function renamedFile(line) { + const [to, from] = line.split(NULL); + return { + from: from || to, + to + }; +} +function parser2(indexX, indexY, handler) { + return [`${indexX}${indexY}`, handler]; +} +function conflicts(indexX, ...indexY) { + return indexY.map((y) => parser2(indexX, y, (result, file) => append(result.conflicted, file))); +} +function splitLine(result, lineStr) { + const trimmed2 = lineStr.trim(); + switch (" ") { + case trimmed2.charAt(2): + return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3)); + case trimmed2.charAt(1): + return data(" ", trimmed2.charAt(0), trimmed2.substr(2)); + default: + return; + } + function data(index2, workingDir, path2) { + const raw = `${index2}${workingDir}`; + const handler = parsers6.get(raw); + if (handler) { + handler(result, path2); + } + if (raw !== "##" && raw !== "!!") { + result.files.push(new FileStatusSummary(path2.replace(/\0.+$/, ""), index2, workingDir)); + } + } +} +var StatusSummary; +var parsers6; +var parseStatusSummary; +var init_StatusSummary = __esm2({ + "src/lib/responses/StatusSummary.ts"() { + init_utils(); + init_FileStatusSummary(); + StatusSummary = class { + constructor() { + this.not_added = []; + this.conflicted = []; + this.created = []; + this.deleted = []; + this.ignored = void 0; + this.modified = []; + this.renamed = []; + this.files = []; + this.staged = []; + this.ahead = 0; + this.behind = 0; + this.current = null; + this.tracking = null; + this.detached = false; + this.isClean = () => { + return !this.files.length; + }; + } + }; + parsers6 = new Map([ + parser2(" ", "A", (result, file) => append(result.created, file)), + parser2(" ", "D", (result, file) => append(result.deleted, file)), + parser2(" ", "M", (result, file) => append(result.modified, file)), + parser2("A", " ", (result, file) => append(result.created, file) && append(result.staged, file)), + parser2("A", "M", (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file)), + parser2("D", " ", (result, file) => append(result.deleted, file) && append(result.staged, file)), + parser2("M", " ", (result, file) => append(result.modified, file) && append(result.staged, file)), + parser2("M", "M", (result, file) => append(result.modified, file) && append(result.staged, file)), + parser2("R", " ", (result, file) => { + append(result.renamed, renamedFile(file)); + }), + parser2("R", "M", (result, file) => { + const renamed = renamedFile(file); + append(result.renamed, renamed); + append(result.modified, renamed.to); + }), + parser2("!", "!", (_result, _file) => { + append(_result.ignored = _result.ignored || [], _file); + }), + parser2("?", "?", (result, file) => append(result.not_added, file)), + ...conflicts( + "A", + "A", + "U" + /* UNMERGED */ + ), + ...conflicts( + "D", + "D", + "U" + /* UNMERGED */ + ), + ...conflicts( + "U", + "A", + "D", + "U" + /* UNMERGED */ + ), + [ + "##", + (result, line) => { + const aheadReg = /ahead (\d+)/; + const behindReg = /behind (\d+)/; + const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; + const trackingReg = /\.{3}(\S*)/; + const onEmptyBranchReg = /\son\s([\S]+)$/; + let regexResult; + regexResult = aheadReg.exec(line); + result.ahead = regexResult && +regexResult[1] || 0; + regexResult = behindReg.exec(line); + result.behind = regexResult && +regexResult[1] || 0; + regexResult = currentReg.exec(line); + result.current = regexResult && regexResult[1]; + regexResult = trackingReg.exec(line); + result.tracking = regexResult && regexResult[1]; + regexResult = onEmptyBranchReg.exec(line); + result.current = regexResult && regexResult[1] || result.current; + result.detached = /\(no branch\)/.test(line); + } + ] + ]); + parseStatusSummary = function(text2) { + const lines = text2.split(NULL); + const status2 = new StatusSummary(); + for (let i = 0, l = lines.length; i < l; ) { + let line = lines[i++].trim(); + if (!line) { + continue; + } + if (line.charAt(0) === "R") { + line += NULL + (lines[i++] || ""); + } + splitLine(status2, line); + } + return status2; + }; + } +}); +function statusTask(customArgs) { + const commands2 = [ + "status", + "--porcelain", + "-b", + "-u", + "--null", + ...customArgs.filter((arg) => !ignoredOptions.includes(arg)) + ]; + return { + format: "utf-8", + commands: commands2, + parser(text2) { + return parseStatusSummary(text2); + } + }; +} +var ignoredOptions; +var init_status = __esm2({ + "src/lib/tasks/status.ts"() { + init_StatusSummary(); + ignoredOptions = ["--null", "-z"]; + } +}); +function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) { + return Object.defineProperty({ + major, + minor, + patch, + agent, + installed + }, "toString", { + value() { + return `${this.major}.${this.minor}.${this.patch}`; + }, + configurable: false, + enumerable: false + }); +} +function notInstalledResponse() { + return versionResponse(0, 0, 0, "", false); +} +function version_default() { + return { + version() { + return this._runTask({ + commands: ["--version"], + format: "utf-8", + parser: versionParser, + onError(result, error, done, fail) { + if (result.exitCode === -2) { + return done(Buffer.from(NOT_INSTALLED)); + } + fail(error); + } + }); + } + }; +} +function versionParser(stdOut) { + if (stdOut === NOT_INSTALLED) { + return notInstalledResponse(); + } + return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut); +} +var NOT_INSTALLED; +var parsers7; +var init_version = __esm2({ + "src/lib/tasks/version.ts"() { + init_utils(); + NOT_INSTALLED = "installed=false"; + parsers7 = [ + new LineParser(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)); + }), + new LineParser(/version (\d+)\.(\d+)\.(\D+)(.+)?$/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent)); + }) + ]; + } +}); +var simple_git_api_exports = {}; +__export2(simple_git_api_exports, { + SimpleGitApi: () => SimpleGitApi +}); +var SimpleGitApi; +var init_simple_git_api = __esm2({ + "src/lib/simple-git-api.ts"() { + init_task_callback(); + init_change_working_directory(); + init_checkout(); + init_commit(); + init_config(); + init_grep(); + init_hash_object(); + init_init(); + init_log(); + init_merge(); + init_push(); + init_status(); + init_task(); + init_version(); + init_utils(); + SimpleGitApi = class { + constructor(_executor) { + this._executor = _executor; + } + _runTask(task, then) { + const chain = this._executor.chain(); + const promise2 = chain.push(task); + if (then) { + taskCallback(task, promise2, then); + } + return Object.create(this, { + then: { value: promise2.then.bind(promise2) }, + catch: { value: promise2.catch.bind(promise2) }, + _executor: { value: chain } + }); + } + add(files) { + return this._runTask(straightThroughStringTask(["add", ...asArray(files)]), trailingFunctionArgument(arguments)); + } + cwd(directory) { + const next = trailingFunctionArgument(arguments); + if (typeof directory === "string") { + return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next); + } + if (typeof (directory == null ? void 0 : directory.path) === "string") { + return this._runTask(changeWorkingDirectoryTask(directory.path, directory.root && this._executor || void 0), next); + } + return this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), next); + } + hashObject(path2, write) { + return this._runTask(hashObjectTask(path2, write === true), trailingFunctionArgument(arguments)); + } + init(bare) { + return this._runTask(initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + merge() { + return this._runTask(mergeTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + mergeFromTo(remote, branch2) { + if (!(filterString(remote) && filterString(branch2))) { + return this._runTask(configurationErrorTask(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`)); + } + return this._runTask(mergeTask([remote, branch2, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments, false)); + } + outputHandler(handler) { + this._executor.outputHandler = handler; + return this; + } + push() { + const task = pushTask({ + remote: filterType(arguments[0], filterString), + branch: filterType(arguments[1], filterString) + }, getTrailingOptions(arguments)); + return this._runTask(task, trailingFunctionArgument(arguments)); + } + stash() { + return this._runTask(straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + status() { + return this._runTask(statusTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + }; + Object.assign(SimpleGitApi.prototype, checkout_default(), commit_default(), config_default(), grep_default(), log_default(), version_default()); + } +}); +var scheduler_exports = {}; +__export2(scheduler_exports, { + Scheduler: () => Scheduler +}); +var createScheduledTask; +var Scheduler; +var init_scheduler = __esm2({ + "src/lib/runners/scheduler.ts"() { + init_utils(); + init_git_logger(); + createScheduledTask = /* @__PURE__ */ (() => { + let id = 0; + return () => { + id++; + const { promise: promise2, done } = (0, import_promise_deferred.createDeferred)(); + return { + promise: promise2, + done, + id + }; + }; + })(); + Scheduler = class { + constructor(concurrency = 2) { + this.concurrency = concurrency; + this.logger = createLogger("", "scheduler"); + this.pending = []; + this.running = []; + this.logger(`Constructed, concurrency=%s`, concurrency); + } + schedule() { + if (!this.pending.length || this.running.length >= this.concurrency) { + this.logger(`Schedule attempt ignored, pending=%s running=%s concurrency=%s`, this.pending.length, this.running.length, this.concurrency); + return; + } + const task = append(this.running, this.pending.shift()); + this.logger(`Attempting id=%s`, task.id); + task.done(() => { + this.logger(`Completing id=`, task.id); + remove2(this.running, task); + this.schedule(); + }); + } + next() { + const { promise: promise2, id } = append(this.pending, createScheduledTask()); + this.logger(`Scheduling id=%s`, id); + this.schedule(); + return promise2; + } + }; + } +}); +var apply_patch_exports = {}; +__export2(apply_patch_exports, { + applyPatchTask: () => applyPatchTask +}); +function applyPatchTask(patches, customArgs) { + return straightThroughStringTask(["apply", ...customArgs, ...patches]); +} +var init_apply_patch = __esm2({ + "src/lib/tasks/apply-patch.ts"() { + init_task(); + } +}); +function branchDeletionSuccess(branch2, hash2) { + return { + branch: branch2, + hash: hash2, + success: true + }; +} +function branchDeletionFailure(branch2) { + return { + branch: branch2, + hash: null, + success: false + }; +} +var BranchDeletionBatch; +var init_BranchDeleteSummary = __esm2({ + "src/lib/responses/BranchDeleteSummary.ts"() { + BranchDeletionBatch = class { + constructor() { + this.all = []; + this.branches = {}; + this.errors = []; + } + get success() { + return !this.errors.length; + } + }; + } +}); +function hasBranchDeletionError(data, processExitCode) { + return processExitCode === 1 && deleteErrorRegex.test(data); +} +var deleteSuccessRegex; +var deleteErrorRegex; +var parsers8; +var parseBranchDeletions; +var init_parse_branch_delete = __esm2({ + "src/lib/parsers/parse-branch-delete.ts"() { + init_BranchDeleteSummary(); + init_utils(); + deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; + deleteErrorRegex = /^error[^']+'([^']+)'/m; + parsers8 = [ + new LineParser(deleteSuccessRegex, (result, [branch2, hash2]) => { + const deletion = branchDeletionSuccess(branch2, hash2); + result.all.push(deletion); + result.branches[branch2] = deletion; + }), + new LineParser(deleteErrorRegex, (result, [branch2]) => { + const deletion = branchDeletionFailure(branch2); + result.errors.push(deletion); + result.all.push(deletion); + result.branches[branch2] = deletion; + }) + ]; + parseBranchDeletions = (stdOut, stdErr) => { + return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]); + }; + } +}); +var BranchSummaryResult; +var init_BranchSummary = __esm2({ + "src/lib/responses/BranchSummary.ts"() { + BranchSummaryResult = class { + constructor() { + this.all = []; + this.branches = {}; + this.current = ""; + this.detached = false; + } + push(status2, detached, name, commit2, label) { + if (status2 === "*") { + this.detached = detached; + this.current = name; + } + this.all.push(name); + this.branches[name] = { + current: status2 === "*", + linkedWorkTree: status2 === "+", + name, + commit: commit2, + label + }; + } + }; + } +}); +function branchStatus(input) { + return input ? input.charAt(0) : ""; +} +function parseBranchSummary(stdOut) { + return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut); +} +var parsers9; +var init_parse_branch = __esm2({ + "src/lib/parsers/parse-branch.ts"() { + init_BranchSummary(); + init_utils(); + parsers9 = [ + new LineParser(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, (result, [current, name, commit2, label]) => { + result.push(branchStatus(current), true, name, commit2, label); + }), + new LineParser(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s, (result, [current, name, commit2, label]) => { + result.push(branchStatus(current), false, name, commit2, label); + }) + ]; + } +}); +var branch_exports = {}; +__export2(branch_exports, { + branchLocalTask: () => branchLocalTask, + branchTask: () => branchTask, + containsDeleteBranchCommand: () => containsDeleteBranchCommand, + deleteBranchTask: () => deleteBranchTask, + deleteBranchesTask: () => deleteBranchesTask +}); +function containsDeleteBranchCommand(commands2) { + const deleteCommands = ["-d", "-D", "--delete"]; + return commands2.some((command) => deleteCommands.includes(command)); +} +function branchTask(customArgs) { + const isDelete = containsDeleteBranchCommand(customArgs); + const commands2 = ["branch", ...customArgs]; + if (commands2.length === 1) { + commands2.push("-a"); + } + if (!commands2.includes("-v")) { + commands2.splice(1, 0, "-v"); + } + return { + format: "utf-8", + commands: commands2, + parser(stdOut, stdErr) { + if (isDelete) { + return parseBranchDeletions(stdOut, stdErr).all[0]; + } + return parseBranchSummary(stdOut); + } + }; +} +function branchLocalTask() { + const parser3 = parseBranchSummary; + return { + format: "utf-8", + commands: ["branch", "-v"], + parser: parser3 + }; +} +function deleteBranchesTask(branches, forceDelete = false) { + return { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr); + }, + onError({ exitCode, stdOut }, error, done, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + done(stdOut); + } + }; +} +function deleteBranchTask(branch2, forceDelete = false) { + const task = { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch2], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr).branches[branch2]; + }, + onError({ exitCode, stdErr, stdOut }, error, _, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + throw new GitResponseError(task.parser(bufferToString(stdOut), bufferToString(stdErr)), String(error)); + } + }; + return task; +} +var init_branch = __esm2({ + "src/lib/tasks/branch.ts"() { + init_git_response_error(); + init_parse_branch_delete(); + init_parse_branch(); + init_utils(); + } +}); +var parseCheckIgnore; +var init_CheckIgnore = __esm2({ + "src/lib/responses/CheckIgnore.ts"() { + parseCheckIgnore = (text2) => { + return text2.split(/\n/g).map((line) => line.trim()).filter((file) => !!file); + }; + } +}); +var check_ignore_exports = {}; +__export2(check_ignore_exports, { + checkIgnoreTask: () => checkIgnoreTask +}); +function checkIgnoreTask(paths) { + return { + commands: ["check-ignore", ...paths], + format: "utf-8", + parser: parseCheckIgnore + }; +} +var init_check_ignore = __esm2({ + "src/lib/tasks/check-ignore.ts"() { + init_CheckIgnore(); + } +}); +var clone_exports = {}; +__export2(clone_exports, { + cloneMirrorTask: () => cloneMirrorTask, + cloneTask: () => cloneTask +}); +function disallowedCommand(command) { + return /^--upload-pack(=|$)/.test(command); +} +function cloneTask(repo, directory, customArgs) { + const commands2 = ["clone", ...customArgs]; + filterString(repo) && commands2.push(repo); + filterString(directory) && commands2.push(directory); + const banned = commands2.find(disallowedCommand); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return straightThroughStringTask(commands2); +} +function cloneMirrorTask(repo, directory, customArgs) { + append(customArgs, "--mirror"); + return cloneTask(repo, directory, customArgs); +} +var init_clone = __esm2({ + "src/lib/tasks/clone.ts"() { + init_task(); + init_utils(); + } +}); +function parseFetchResult(stdOut, stdErr) { + const result = { + raw: stdOut, + remote: null, + branches: [], + tags: [], + updated: [], + deleted: [] + }; + return parseStringResponse(result, parsers10, [stdOut, stdErr]); +} +var parsers10; +var init_parse_fetch = __esm2({ + "src/lib/parsers/parse-fetch.ts"() { + init_utils(); + parsers10 = [ + new LineParser(/From (.+)$/, (result, [remote]) => { + result.remote = remote; + }), + new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.branches.push({ + name, + tracking + }); + }), + new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.tags.push({ + name, + tracking + }); + }), + new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => { + result.deleted.push({ + tracking + }); + }), + new LineParser(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, (result, [from, to, name, tracking]) => { + result.updated.push({ + name, + tracking, + to, + from + }); + }) + ]; + } +}); +var fetch_exports = {}; +__export2(fetch_exports, { + fetchTask: () => fetchTask +}); +function disallowedCommand2(command) { + return /^--upload-pack(=|$)/.test(command); +} +function fetchTask(remote, branch2, customArgs) { + const commands2 = ["fetch", ...customArgs]; + if (remote && branch2) { + commands2.push(remote, branch2); + } + const banned = commands2.find(disallowedCommand2); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return { + commands: commands2, + format: "utf-8", + parser: parseFetchResult + }; +} +var init_fetch = __esm2({ + "src/lib/tasks/fetch.ts"() { + init_parse_fetch(); + init_task(); + } +}); +function parseMoveResult(stdOut) { + return parseStringResponse({ moves: [] }, parsers11, stdOut); +} +var parsers11; +var init_parse_move = __esm2({ + "src/lib/parsers/parse-move.ts"() { + init_utils(); + parsers11 = [ + new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { + result.moves.push({ from, to }); + }) + ]; + } +}); +var move_exports = {}; +__export2(move_exports, { + moveTask: () => moveTask +}); +function moveTask(from, to) { + return { + commands: ["mv", "-v", ...asArray(from), to], + format: "utf-8", + parser: parseMoveResult + }; +} +var init_move = __esm2({ + "src/lib/tasks/move.ts"() { + init_parse_move(); + init_utils(); + } +}); +var pull_exports = {}; +__export2(pull_exports, { + pullTask: () => pullTask +}); +function pullTask(remote, branch2, customArgs) { + const commands2 = ["pull", ...customArgs]; + if (remote && branch2) { + commands2.splice(1, 0, remote, branch2); + } + return { + commands: commands2, + format: "utf-8", + parser(stdOut, stdErr) { + return parsePullResult(stdOut, stdErr); + }, + onError(result, _error, _done, fail) { + const pullError = parsePullErrorResult(bufferToString(result.stdOut), bufferToString(result.stdErr)); + if (pullError) { + return fail(new GitResponseError(pullError)); + } + fail(_error); + } + }; +} +var init_pull = __esm2({ + "src/lib/tasks/pull.ts"() { + init_git_response_error(); + init_parse_pull(); + init_utils(); + } +}); +function parseGetRemotes(text2) { + const remotes = {}; + forEach(text2, ([name]) => remotes[name] = { name }); + return Object.values(remotes); +} +function parseGetRemotesVerbose(text2) { + const remotes = {}; + forEach(text2, ([name, url, purpose]) => { + if (!remotes.hasOwnProperty(name)) { + remotes[name] = { + name, + refs: { fetch: "", push: "" } + }; + } + if (purpose && url) { + remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url; + } + }); + return Object.values(remotes); +} +function forEach(text2, handler) { + forEachLineWithContent(text2, (line) => handler(line.split(/\s+/))); +} +var init_GetRemoteSummary = __esm2({ + "src/lib/responses/GetRemoteSummary.ts"() { + init_utils(); + } +}); +var remote_exports = {}; +__export2(remote_exports, { + addRemoteTask: () => addRemoteTask, + getRemotesTask: () => getRemotesTask, + listRemotesTask: () => listRemotesTask, + remoteTask: () => remoteTask, + removeRemoteTask: () => removeRemoteTask +}); +function addRemoteTask(remoteName, remoteRepo, customArgs = []) { + return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]); +} +function getRemotesTask(verbose) { + const commands2 = ["remote"]; + if (verbose) { + commands2.push("-v"); + } + return { + commands: commands2, + format: "utf-8", + parser: verbose ? parseGetRemotesVerbose : parseGetRemotes + }; +} +function listRemotesTask(customArgs = []) { + const commands2 = [...customArgs]; + if (commands2[0] !== "ls-remote") { + commands2.unshift("ls-remote"); + } + return straightThroughStringTask(commands2); +} +function remoteTask(customArgs = []) { + const commands2 = [...customArgs]; + if (commands2[0] !== "remote") { + commands2.unshift("remote"); + } + return straightThroughStringTask(commands2); +} +function removeRemoteTask(remoteName) { + return straightThroughStringTask(["remote", "remove", remoteName]); +} +var init_remote = __esm2({ + "src/lib/tasks/remote.ts"() { + init_GetRemoteSummary(); + init_task(); + } +}); +var stash_list_exports = {}; +__export2(stash_list_exports, { + stashListTask: () => stashListTask +}); +function stashListTask(opt = {}, customArgs) { + const options = parseLogOptions(opt); + const commands2 = ["stash", "list", ...options.commands, ...customArgs]; + const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands2)); + return validateLogFormatConfig(commands2) || { + commands: commands2, + format: "utf-8", + parser: parser3 + }; +} +var init_stash_list = __esm2({ + "src/lib/tasks/stash-list.ts"() { + init_log_format(); + init_parse_list_log_summary(); + init_diff(); + init_log(); + } +}); +var sub_module_exports = {}; +__export2(sub_module_exports, { + addSubModuleTask: () => addSubModuleTask, + initSubModuleTask: () => initSubModuleTask, + subModuleTask: () => subModuleTask, + updateSubModuleTask: () => updateSubModuleTask +}); +function addSubModuleTask(repo, path2) { + return subModuleTask(["add", repo, path2]); +} +function initSubModuleTask(customArgs) { + return subModuleTask(["init", ...customArgs]); +} +function subModuleTask(customArgs) { + const commands2 = [...customArgs]; + if (commands2[0] !== "submodule") { + commands2.unshift("submodule"); + } + return straightThroughStringTask(commands2); +} +function updateSubModuleTask(customArgs) { + return subModuleTask(["update", ...customArgs]); +} +var init_sub_module = __esm2({ + "src/lib/tasks/sub-module.ts"() { + init_task(); + } +}); +function singleSorted(a, b) { + const aIsNum = isNaN(a); + const bIsNum = isNaN(b); + if (aIsNum !== bIsNum) { + return aIsNum ? 1 : -1; + } + return aIsNum ? sorted(a, b) : 0; +} +function sorted(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} +function trimmed(input) { + return input.trim(); +} +function toNumber(input) { + if (typeof input === "string") { + return parseInt(input.replace(/^\D+/g, ""), 10) || 0; + } + return 0; +} +var TagList; +var parseTagList; +var init_TagList = __esm2({ + "src/lib/responses/TagList.ts"() { + TagList = class { + constructor(all, latest) { + this.all = all; + this.latest = latest; + } + }; + parseTagList = function(data, customSort = false) { + const tags = data.split("\n").map(trimmed).filter(Boolean); + if (!customSort) { + tags.sort(function(tagA, tagB) { + const partsA = tagA.split("."); + const partsB = tagB.split("."); + if (partsA.length === 1 || partsB.length === 1) { + return singleSorted(toNumber(partsA[0]), toNumber(partsB[0])); + } + for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) { + const diff3 = sorted(toNumber(partsA[i]), toNumber(partsB[i])); + if (diff3) { + return diff3; + } + } + return 0; + }); + } + const latest = customSort ? tags[0] : [...tags].reverse().find((tag2) => tag2.indexOf(".") >= 0); + return new TagList(tags, latest); + }; + } +}); +var tag_exports = {}; +__export2(tag_exports, { + addAnnotatedTagTask: () => addAnnotatedTagTask, + addTagTask: () => addTagTask, + tagListTask: () => tagListTask +}); +function tagListTask(customArgs = []) { + const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option)); + return { + format: "utf-8", + commands: ["tag", "-l", ...customArgs], + parser(text2) { + return parseTagList(text2, hasCustomSort); + } + }; +} +function addTagTask(name) { + return { + format: "utf-8", + commands: ["tag", name], + parser() { + return { name }; + } + }; +} +function addAnnotatedTagTask(name, tagMessage) { + return { + format: "utf-8", + commands: ["tag", "-a", "-m", tagMessage, name], + parser() { + return { name }; + } + }; +} +var init_tag = __esm2({ + "src/lib/tasks/tag.ts"() { + init_TagList(); + } +}); +var require_git = __commonJS2({ + "src/git.js"(exports2, module2) { + var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS2(git_executor_exports)); + var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS2(simple_git_api_exports)); + var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS2(scheduler_exports)); + var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS2(task_exports)); + var { + asArray: asArray2, + filterArray: filterArray2, + filterPrimitives: filterPrimitives2, + filterString: filterString2, + filterStringOrStringArray: filterStringOrStringArray2, + filterType: filterType2, + getTrailingOptions: getTrailingOptions2, + trailingFunctionArgument: trailingFunctionArgument2, + trailingOptionsArgument: trailingOptionsArgument2 + } = (init_utils(), __toCommonJS2(utils_exports)); + var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS2(apply_patch_exports)); + var { + branchTask: branchTask2, + branchLocalTask: branchLocalTask2, + deleteBranchesTask: deleteBranchesTask2, + deleteBranchTask: deleteBranchTask2 + } = (init_branch(), __toCommonJS2(branch_exports)); + var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS2(check_ignore_exports)); + var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS2(check_is_repo_exports)); + var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS2(clone_exports)); + var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS2(clean_exports)); + var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS2(diff_exports)); + var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS2(fetch_exports)); + var { moveTask: moveTask2 } = (init_move(), __toCommonJS2(move_exports)); + var { pullTask: pullTask2 } = (init_pull(), __toCommonJS2(pull_exports)); + var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS2(push_exports)); + var { + addRemoteTask: addRemoteTask2, + getRemotesTask: getRemotesTask2, + listRemotesTask: listRemotesTask2, + remoteTask: remoteTask2, + removeRemoteTask: removeRemoteTask2 + } = (init_remote(), __toCommonJS2(remote_exports)); + var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS2(reset_exports)); + var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS2(stash_list_exports)); + var { + addSubModuleTask: addSubModuleTask2, + initSubModuleTask: initSubModuleTask2, + subModuleTask: subModuleTask2, + updateSubModuleTask: updateSubModuleTask2 + } = (init_sub_module(), __toCommonJS2(sub_module_exports)); + var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS2(tag_exports)); + var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS2(task_exports)); + function Git2(options, plugins) { + this._executor = new GitExecutor2(options.binary, options.baseDir, new Scheduler2(options.maxConcurrentProcesses), plugins); + this._trimmed = options.trimmed; + } + (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2; + Git2.prototype.customBinary = function(command) { + this._executor.binary = command; + return this; + }; + Git2.prototype.env = function(name, value) { + if (arguments.length === 1 && typeof name === "object") { + this._executor.env = name; + } else { + (this._executor.env = this._executor.env || {})[name] = value; + } + return this; + }; + Git2.prototype.stashList = function(options) { + return this._runTask(stashListTask2(trailingOptionsArgument2(arguments) || {}, filterArray2(options) && options || []), trailingFunctionArgument2(arguments)); + }; + function createCloneTask(api, task, repoPath, localPath) { + if (typeof repoPath !== "string") { + return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`); + } + return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments)); + } + Git2.prototype.clone = function() { + return this._runTask(createCloneTask("clone", cloneTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mirror = function() { + return this._runTask(createCloneTask("mirror", cloneMirrorTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mv = function(from, to) { + return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkoutLatestTag = function(then) { + var git = this; + return this.pull(function() { + git.tags(function(err, tags) { + git.checkout(tags.latest, then); + }); + }); + }; + Git2.prototype.pull = function(remote, branch2, options, then) { + return this._runTask(pullTask2(filterType2(remote, filterString2), filterType2(branch2, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.fetch = function(remote, branch2) { + return this._runTask(fetchTask2(filterType2(remote, filterString2), filterType2(branch2, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.silent = function(silence) { + console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"); + return this; + }; + Git2.prototype.tags = function(options, then) { + return this._runTask(tagListTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rebase = function() { + return this._runTask(straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.reset = function(mode) { + return this._runTask(resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revert = function(commit2) { + const next = trailingFunctionArgument2(arguments); + if (typeof commit2 !== "string") { + return this._runTask(configurationErrorTask2("Commit must be a string"), next); + } + return this._runTask(straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit2]), next); + }; + Git2.prototype.addTag = function(name) { + const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name"); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) { + return this._runTask(addAnnotatedTagTask2(tagName, tagMessage), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) { + return this._runTask(deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) { + return this._runTask(deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branch = function(options, then) { + return this._runTask(branchTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branchLocal = function(then) { + return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.raw = function(commands2) { + const createRestCommands = !Array.isArray(commands2); + const command = [].slice.call(createRestCommands ? arguments : commands2, 0); + for (let i = 0; i < command.length && createRestCommands; i++) { + if (!filterPrimitives2(command[i])) { + command.splice(i, command.length - i); + break; + } + } + command.push(...getTrailingOptions2(arguments, 0, true)); + var next = trailingFunctionArgument2(arguments); + if (!command.length) { + return this._runTask(configurationErrorTask2("Raw: must supply one or more command to execute"), next); + } + return this._runTask(straightThroughStringTask2(command, this._trimmed), next); + }; + Git2.prototype.submoduleAdd = function(repo, path2, then) { + return this._runTask(addSubModuleTask2(repo, path2), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleUpdate = function(args, then) { + return this._runTask(updateSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleInit = function(args, then) { + return this._runTask(initSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.subModule = function(options, then) { + return this._runTask(subModuleTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.listRemote = function() { + return this._runTask(listRemotesTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addRemote = function(remoteName, remoteRepo, then) { + return this._runTask(addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.removeRemote = function(remoteName, then) { + return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.getRemotes = function(verbose, then) { + return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.remote = function(options, then) { + return this._runTask(remoteTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.tag = function(options, then) { + const command = getTrailingOptions2(arguments); + if (command[0] !== "tag") { + command.unshift("tag"); + } + return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.updateServerInfo = function(then) { + return this._runTask(straightThroughStringTask2(["update-server-info"]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.pushTags = function(remote, then) { + const task = pushTagsTask2({ remote: filterType2(remote, filterString2) }, getTrailingOptions2(arguments)); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rm = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rmKeepLocal = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.catFile = function(options, then) { + return this._catFile("utf-8", arguments); + }; + Git2.prototype.binaryCatFile = function() { + return this._catFile("buffer", arguments); + }; + Git2.prototype._catFile = function(format, args) { + var handler = trailingFunctionArgument2(args); + var command = ["cat-file"]; + var options = args[0]; + if (typeof options === "string") { + return this._runTask(configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), handler); + } + if (Array.isArray(options)) { + command.push.apply(command, options); + } + const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command); + return this._runTask(task, handler); + }; + Git2.prototype.diff = function(options, then) { + const task = filterString2(options) ? configurationErrorTask2("git.diff: supplying options as a single string is no longer supported, switch to an array of strings") : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.diffSummary = function() { + return this._runTask(diffSummaryTask2(getTrailingOptions2(arguments, 1)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.applyPatch = function(patches) { + const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(`git.applyPatch requires one or more string patches as the first argument`) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1))); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revparse = function() { + const commands2 = ["rev-parse", ...getTrailingOptions2(arguments, true)]; + return this._runTask(straightThroughStringTask2(commands2, true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.show = function(options, then) { + return this._runTask(straightThroughStringTask2(["show", ...getTrailingOptions2(arguments, 1)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.clean = function(mode, options, then) { + const usingCleanOptionsArray = isCleanOptionsArray2(mode); + const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || ""; + const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0)); + return this._runTask(cleanWithOptionsTask2(cleanMode, customArgs), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.exec = function(then) { + const task = { + commands: [], + format: "utf-8", + parser() { + if (typeof then === "function") { + then(); + } + } + }; + return this._runTask(task); + }; + Git2.prototype.clearQueue = function() { + return this; + }; + Git2.prototype.checkIgnore = function(pathnames, then) { + return this._runTask(checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkIsRepo = function(checkType, then) { + return this._runTask(checkIsRepoTask2(filterType2(checkType, filterString2)), trailingFunctionArgument2(arguments)); + }; + module2.exports = Git2; + } +}); +init_git_error(); +var GitConstructError = class extends GitError { + constructor(config, message) { + super(void 0, message); + this.config = config; + } +}; +init_git_error(); +init_git_error(); +var GitPluginError = class extends GitError { + constructor(task, plugin, message) { + super(task, message); + this.task = task; + this.plugin = plugin; + Object.setPrototypeOf(this, new.target.prototype); + } +}; +init_git_response_error(); +init_task_configuration_error(); +init_check_is_repo(); +init_clean(); +init_config(); +init_grep(); +init_reset(); +function abortPlugin(signal) { + if (!signal) { + return; + } + const onSpawnAfter = { + type: "spawn.after", + action(_data, context) { + function kill() { + context.kill(new GitPluginError(void 0, "abort", "Abort signal received")); + } + signal.addEventListener("abort", kill); + context.spawned.on("close", () => signal.removeEventListener("abort", kill)); + } + }; + const onSpawnBefore = { + type: "spawn.before", + action(_data, context) { + if (signal.aborted) { + context.kill(new GitPluginError(void 0, "abort", "Abort already signaled")); + } + } + }; + return [onSpawnBefore, onSpawnAfter]; +} +function isConfigSwitch(arg) { + return typeof arg === "string" && arg.trim().toLowerCase() === "-c"; +} +function preventProtocolOverride(arg, next) { + if (!isConfigSwitch(arg)) { + return; + } + if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) { + return; + } + throw new GitPluginError(void 0, "unsafe", "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol"); +} +function preventUploadPack(arg, method2) { + if (/^\s*--(upload|receive)-pack/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`); + } + if (method2 === "clone" && /^\s*-u\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of clone with option -u is not permitted without enabling allowUnsafePack`); + } + if (method2 === "push" && /^\s*--exec\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of push with option --exec is not permitted without enabling allowUnsafePack`); + } +} +function blockUnsafeOperationsPlugin({ + allowUnsafeProtocolOverride = false, + allowUnsafePack = false +} = {}) { + return { + type: "spawn.args", + action(args, context) { + args.forEach((current, index2) => { + const next = index2 < args.length ? args[index2 + 1] : ""; + allowUnsafeProtocolOverride || preventProtocolOverride(current, next); + allowUnsafePack || preventUploadPack(current, context.method); + }); + return args; + } + }; +} +init_utils(); +function commandConfigPrefixingPlugin(configuration) { + const prefix = prefixedArray(configuration, "-c"); + return { + type: "spawn.args", + action(data) { + return [...prefix, ...data]; + } + }; +} +init_utils(); +var never = (0, import_promise_deferred2.deferred)().promise; +function completionDetectionPlugin({ + onClose = true, + onExit = 50 +} = {}) { + function createEvents() { + let exitCode = -1; + const events = { + close: (0, import_promise_deferred2.deferred)(), + closeTimeout: (0, import_promise_deferred2.deferred)(), + exit: (0, import_promise_deferred2.deferred)(), + exitTimeout: (0, import_promise_deferred2.deferred)() + }; + const result = Promise.race([ + onClose === false ? never : events.closeTimeout.promise, + onExit === false ? never : events.exitTimeout.promise + ]); + configureTimeout(onClose, events.close, events.closeTimeout); + configureTimeout(onExit, events.exit, events.exitTimeout); + return { + close(code) { + exitCode = code; + events.close.done(); + }, + exit(code) { + exitCode = code; + events.exit.done(); + }, + get exitCode() { + return exitCode; + }, + result + }; + } + function configureTimeout(flag, event, timeout) { + if (flag === false) { + return; + } + (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done); + } + return { + type: "spawn.after", + action(_0, _1) { + return __async(this, arguments, function* (_data, { spawned, close }) { + var _a2, _b; + const events = createEvents(); + let deferClose = true; + let quickClose = () => void (deferClose = false); + (_a2 = spawned.stdout) == null ? void 0 : _a2.on("data", quickClose); + (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose); + spawned.on("error", quickClose); + spawned.on("close", (code) => events.close(code)); + spawned.on("exit", (code) => events.exit(code)); + try { + yield events.result; + if (deferClose) { + yield delay(50); + } + close(events.exitCode); + } catch (err) { + close(events.exitCode, err); + } + }); + } + }; +} +init_git_error(); +function isTaskError(result) { + return !!(result.exitCode && result.stdErr.length); +} +function getErrorMessage(result) { + return Buffer.concat([...result.stdOut, ...result.stdErr]); +} +function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) { + return (error, result) => { + if (!overwrite && error || !isError(result)) { + return error; + } + return errorMessage(result); + }; +} +function errorDetectionPlugin(config) { + return { + type: "task.error", + action(data, context) { + const error = config(data.error, { + stdErr: context.stdErr, + stdOut: context.stdOut, + exitCode: context.exitCode + }); + if (Buffer.isBuffer(error)) { + return { error: new GitError(void 0, error.toString("utf-8")) }; + } + return { + error + }; + } + }; +} +init_utils(); +var PluginStore = class { + constructor() { + this.plugins = /* @__PURE__ */ new Set(); + } + add(plugin) { + const plugins = []; + asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2))); + return () => { + plugins.forEach((plugin2) => this.plugins.delete(plugin2)); + }; + } + exec(type, data, context) { + let output = data; + const contextual = Object.freeze(Object.create(context)); + for (const plugin of this.plugins) { + if (plugin.type === type) { + output = plugin.action(output, contextual); + } + } + return output; + } +}; +init_utils(); +function progressMonitorPlugin(progress) { + const progressCommand = "--progress"; + const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; + const onProgress = { + type: "spawn.after", + action(_data, context) { + var _a2; + if (!context.commands.includes(progressCommand)) { + return; + } + (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => { + const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8")); + if (!message) { + return; + } + progress({ + method: context.method, + stage: progressEventStage(message[1]), + progress: asNumber(message[2]), + processed: asNumber(message[3]), + total: asNumber(message[4]) + }); + }); + } + }; + const onArgs = { + type: "spawn.args", + action(args, context) { + if (!progressMethods.includes(context.method)) { + return args; + } + return including(args, progressCommand); + } + }; + return [onArgs, onProgress]; +} +function progressEventStage(input) { + return String(input.toLowerCase().split(" ", 1)) || "unknown"; +} +init_utils(); +function spawnOptionsPlugin(spawnOptions) { + const options = pick(spawnOptions, ["uid", "gid"]); + return { + type: "spawn.options", + action(data) { + return __spreadValues(__spreadValues({}, options), data); + } + }; +} +function timeoutPlugin({ + block, + stdErr = true, + stdOut = true +}) { + if (block > 0) { + return { + type: "spawn.after", + action(_data, context) { + var _a2, _b; + let timeout; + function wait3() { + timeout && clearTimeout(timeout); + timeout = setTimeout(kill, block); + } + function stop() { + var _a3, _b2; + (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait3); + (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait3); + context.spawned.off("exit", stop); + context.spawned.off("close", stop); + timeout && clearTimeout(timeout); + } + function kill() { + stop(); + context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`)); + } + stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait3)); + stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait3)); + context.spawned.on("exit", stop); + context.spawned.on("close", stop); + wait3(); + } + }; + } +} +init_utils(); +var Git = require_git(); +function gitInstanceFactory(baseDir, options) { + const plugins = new PluginStore(); + const config = createInstanceConfig(baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, options); + if (!folderExists(config.baseDir)) { + throw new GitConstructError(config, `Cannot use simple-git on a directory that does not exist`); + } + if (Array.isArray(config.config)) { + plugins.add(commandConfigPrefixingPlugin(config.config)); + } + plugins.add(blockUnsafeOperationsPlugin(config.unsafe)); + plugins.add(completionDetectionPlugin(config.completion)); + config.abort && plugins.add(abortPlugin(config.abort)); + config.progress && plugins.add(progressMonitorPlugin(config.progress)); + config.timeout && plugins.add(timeoutPlugin(config.timeout)); + config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions)); + plugins.add(errorDetectionPlugin(errorDetectionHandler(true))); + config.errors && plugins.add(errorDetectionPlugin(config.errors)); + return new Git(config, plugins); +} +init_git_response_error(); +var esm_default = gitInstanceFactory; + +// src/constants.ts +init_polyfill_buffer(); +var import_obsidian2 = require("obsidian"); +var DATE_FORMAT = "YYYY-MM-DD"; +var DATE_TIME_FORMAT_MINUTES = `${DATE_FORMAT} HH:mm`; +var DATE_TIME_FORMAT_SECONDS = `${DATE_FORMAT} HH:mm:ss`; +var GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH = 40; +var DEFAULT_SETTINGS = { + commitMessage: "vault backup: {{date}}", + commitDateFormat: DATE_TIME_FORMAT_SECONDS, + autoSaveInterval: 0, + autoPushInterval: 0, + autoPullInterval: 0, + autoPullOnBoot: false, + disablePush: false, + pullBeforePush: true, + disablePopups: false, + disablePopupsForNoChanges: false, + listChangedFilesInMessageBody: false, + showStatusBar: true, + updateSubmodules: false, + syncMethod: "merge", + customMessageOnAutoBackup: false, + autoBackupAfterFileChange: false, + treeStructure: false, + refreshSourceControl: import_obsidian2.Platform.isDesktopApp, + basePath: "", + differentIntervalCommitAndPush: false, + changedFilesInStatusBar: false, + showedMobileNotice: false, + refreshSourceControlTimer: 7e3, + showBranchStatusBar: true, + setLastSaveToLastCommit: false, + submoduleRecurseCheckout: false, + gitDir: "", + showFileMenu: true, + authorInHistoryView: "hide", + dateInHistoryView: false, + lineAuthor: { + show: false, + followMovement: "inactive", + authorDisplay: "initials", + showCommitHash: false, + dateTimeFormatOptions: "date", + dateTimeFormatCustomString: DATE_TIME_FORMAT_MINUTES, + dateTimeTimezone: "viewer-local", + coloringMaxAge: "1y", + // colors were picked via: + // https://color.adobe.com/de/create/color-accessibility + colorNew: { r: 255, g: 150, b: 150 }, + colorOld: { r: 120, g: 160, b: 255 }, + textColorCss: "var(--text-muted)", + // more pronounced than line numbers, but less than the content text + ignoreWhitespace: false, + gutterSpacingFallbackLength: 5 + } +}; +var SOURCE_CONTROL_VIEW_CONFIG = { + type: "git-view", + name: "Source Control", + icon: "git-pull-request" +}; +var HISTORY_VIEW_CONFIG = { + type: "git-history-view", + name: "History", + icon: "history" +}; +var DIFF_VIEW_CONFIG = { + type: "diff-view", + name: "Diff View", + icon: "git-pull-request" +}; + +// src/types.ts +init_polyfill_buffer(); +function mergeSettingsByPriority(low, high) { + const lineAuthor = Object.assign({}, low.lineAuthor, high.lineAuthor); + return Object.assign({}, low, high, { lineAuthor }); +} + +// src/utils.ts +init_polyfill_buffer(); +var cssColorConverter = __toESM(require_lib3()); +var import_deep_equal = __toESM(require_deep_equal()); +var import_obsidian3 = require("obsidian"); +var worthWalking2 = (filepath, root2) => { + if (filepath === "." || root2 == null || root2.length === 0 || root2 === ".") { + return true; + } + if (root2.length >= filepath.length) { + return root2.startsWith(filepath); + } else { + return filepath.startsWith(root2); + } +}; +function getNewLeaf(event) { + let leaf; + if (event) { + if (event.button === 0 || event.button === 1) { + const type = import_obsidian3.Keymap.isModEvent(event); + leaf = app.workspace.getLeaf(type); + } + } else { + leaf = app.workspace.getLeaf(false); + } + return leaf; +} +function impossibleBranch(x) { + throw new Error("Impossible branch: " + x); +} +function rgbToString(rgb) { + return `rgb(${rgb.r},${rgb.g},${rgb.b})`; +} +function convertToRgb(str) { + var _a2; + const color = (_a2 = cssColorConverter.fromString(str)) == null ? void 0 : _a2.toRgbaArray(); + if (color === void 0) { + return void 0; + } + const [r, g, b] = color; + return { r, g, b }; +} +function momentToEpochSeconds(instant) { + return instant.diff(import_obsidian3.moment.unix(0), "seconds"); +} +function median(array) { + if (array.length === 0) + return void 0; + return array.slice().sort()[Math.floor(array.length / 2)]; +} +function strictDeepEqual(a, b) { + return (0, import_deep_equal.default)(a, b, { strict: true }); +} +function resizeToLength(original, desiredLength, fillChar) { + if (original.length <= desiredLength) { + const prefix = new Array(desiredLength - original.length).fill(fillChar).join(""); + return prefix + original; + } else { + return original.substring(original.length - desiredLength); + } +} +function prefixOfLengthAsWhitespace(toBeRenderedText, whitespacePrefixLength) { + if (whitespacePrefixLength <= 0) + return toBeRenderedText; + const whitespacePrefix = new Array(whitespacePrefixLength).fill(" ").join(""); + const originalSuffix = toBeRenderedText.substring( + whitespacePrefixLength, + toBeRenderedText.length + ); + return whitespacePrefix + originalSuffix; +} +function between(l, x, r) { + return l <= x && x <= r; +} +function splitRemoteBranch(remoteBranch) { + const [remote, ...branch2] = remoteBranch.split("/"); + return [remote, branch2.length === 0 ? void 0 : branch2.join("/")]; +} +function getDisplayPath(path2) { + if (path2.endsWith("/")) + return path2; + return path2.split("/").last().replace(".md", ""); +} +function formatMinutes(minutes) { + if (minutes === 1) + return "1 minute"; + return `${minutes} minutes`; +} + +// src/gitManager/gitManager.ts +init_polyfill_buffer(); +var GitManager = class { + constructor(plugin) { + this.plugin = plugin; + this.app = plugin.app; + } + // Constructs a path relative to the vault from a path relative to the git repository + getRelativeVaultPath(path2) { + if (this.plugin.settings.basePath) { + return this.plugin.settings.basePath + "/" + path2; + } else { + return path2; + } + } + // Constructs a path relative to the git repository from a path relative to the vault + // + // @param doConversion - If false, the path is returned as is. This is added because that parameter is often passed on to functions where this method is called. + getRelativeRepoPath(path2, doConversion = true) { + if (doConversion) { + if (this.plugin.settings.basePath.length > 0) { + return path2.substring(this.plugin.settings.basePath.length + 1); + } + } + return path2; + } + _getTreeStructure(children2, beginLength = 0) { + const list = []; + children2 = [...children2]; + while (children2.length > 0) { + const first2 = children2.first(); + const restPath = first2.path.substring(beginLength); + if (restPath.contains("/")) { + const title = restPath.substring(0, restPath.indexOf("/")); + const childrenWithSameTitle = children2.filter((item) => { + return item.path.substring(beginLength).startsWith(title + "/"); + }); + childrenWithSameTitle.forEach((item) => children2.remove(item)); + const path2 = first2.path.substring( + 0, + restPath.indexOf("/") + beginLength + ); + list.push({ + title, + path: path2, + vaultPath: this.getRelativeVaultPath(path2), + children: this._getTreeStructure( + childrenWithSameTitle, + (beginLength > 0 ? beginLength + title.length : title.length) + 1 + ) + }); + } else { + list.push({ + title: restPath, + data: first2, + path: first2.path, + vaultPath: this.getRelativeVaultPath(first2.path) + }); + children2.remove(first2); + } + } + return list; + } + /* + * Sorts the children and simplifies the title + * If a node only contains another subdirectory, that subdirectory is moved up one level and integrated into the parent node + */ + simplify(tree) { + var _a2, _b, _c, _d; + for (const node of tree) { + while (true) { + const singleChild = ((_a2 = node.children) == null ? void 0 : _a2.length) == 1; + const singleChildIsDir = ((_c = (_b = node.children) == null ? void 0 : _b.first()) == null ? void 0 : _c.data) == void 0; + if (!(node.children != void 0 && singleChild && singleChildIsDir)) + break; + const child = node.children.first(); + node.title += "/" + child.title; + node.data = child.data; + node.path = child.path; + node.vaultPath = child.vaultPath; + node.children = child.children; + } + if (node.children != void 0) { + this.simplify(node.children); + } + (_d = node.children) == null ? void 0 : _d.sort((a, b) => { + const dirCompare = (b.data == void 0 ? 1 : 0) - (a.data == void 0 ? 1 : 0); + if (dirCompare != 0) { + return dirCompare; + } else { + return a.title.localeCompare(b.title); + } + }); + } + return tree.sort((a, b) => { + const dirCompare = (b.data == void 0 ? 1 : 0) - (a.data == void 0 ? 1 : 0); + if (dirCompare != 0) { + return dirCompare; + } else { + return a.title.localeCompare(b.title); + } + }); + } + getTreeStructure(children2) { + const tree = this._getTreeStructure(children2); + const res = this.simplify(tree); + return res; + } + async formatCommitMessage(template) { + let status2; + if (template.includes("{{numFiles}}")) { + status2 = await this.status(); + const numFiles = status2.staged.length; + template = template.replace("{{numFiles}}", String(numFiles)); + } + if (template.includes("{{hostname}}")) { + const hostname = this.plugin.localStorage.getHostname() || ""; + template = template.replace("{{hostname}}", hostname); + } + if (template.includes("{{files}}")) { + status2 = status2 != null ? status2 : await this.status(); + const changeset = {}; + status2.staged.forEach((value) => { + if (value.index in changeset) { + changeset[value.index].push(value.path); + } else { + changeset[value.index] = [value.path]; + } + }); + const chunks = []; + for (const [action, files2] of Object.entries(changeset)) { + chunks.push(action + " " + files2.join(" ")); + } + const files = chunks.join(", "); + template = template.replace("{{files}}", files); + } + const moment6 = window.moment; + template = template.replace( + "{{date}}", + moment6().format(this.plugin.settings.commitDateFormat) + ); + if (this.plugin.settings.listChangedFilesInMessageBody) { + template = template + "\n\nAffected files:\n" + (status2 != null ? status2 : await this.status()).staged.map((e) => e.path).join("\n"); + } + return template; + } +}; + +// src/gitManager/simpleGit.ts +var SimpleGit = class extends GitManager { + constructor(plugin) { + super(plugin); + } + async setGitInstance(ignoreError = false) { + if (this.isGitInstalled()) { + const adapter = this.app.vault.adapter; + const path2 = adapter.getBasePath(); + let basePath = path2; + if (this.plugin.settings.basePath) { + const exists2 = await adapter.exists( + (0, import_obsidian4.normalizePath)(this.plugin.settings.basePath) + ); + if (exists2) { + basePath = path2 + import_path.sep + this.plugin.settings.basePath; + } else if (!ignoreError) { + new import_obsidian4.Notice("ObsidianGit: Base path does not exist"); + } + } + this.git = esm_default({ + baseDir: basePath, + binary: this.plugin.localStorage.getGitPath() || void 0, + config: ["core.quotepath=off"] + }); + const pathPaths = this.plugin.localStorage.getPATHPaths(); + const envVars = this.plugin.localStorage.getEnvVars(); + const gitDir = this.plugin.settings.gitDir; + if (pathPaths.length > 0) { + const path3 = process.env["PATH"] + ":" + pathPaths.join(":"); + process.env["PATH"] = path3; + } + if (gitDir) { + process.env["GIT_DIR"] = gitDir; + } + for (const envVar of envVars) { + const [key2, value] = envVar.split("="); + process.env[key2] = value; + } + import_debug2.default.enable("simple-git"); + if (await this.git.checkIsRepo()) { + await this.git.cwd(await this.git.revparse("--show-toplevel")); + } + } + } + async status() { + this.plugin.setState(1 /* status */); + const status2 = await this.git.status((err) => this.onError(err)); + this.plugin.setState(0 /* idle */); + const allFilesFormatted = status2.files.map((e) => { + const res = this.formatPath(e); + return { + path: res.path, + from: res.from, + index: e.index === "?" ? "U" : e.index, + working_dir: e.working_dir === "?" ? "U" : e.working_dir, + vault_path: this.getRelativeVaultPath(res.path) + }; + }); + return { + all: allFilesFormatted, + changed: allFilesFormatted.filter((e) => e.working_dir !== " "), + staged: allFilesFormatted.filter( + (e) => e.index !== " " && e.index != "U" + ), + conflicted: status2.conflicted.map( + (path2) => this.formatPath({ path: path2 }).path + ) + }; + } + async submoduleAwareHeadRevisonInContainingDirectory(filepath) { + const repoPath = this.getRelativeRepoPath(filepath); + const containingDirectory = path.dirname(repoPath); + const args = ["-C", containingDirectory, "rev-parse", "HEAD"]; + const result = this.git.raw(args); + result.catch( + (err) => console.warn("obsidian-git: rev-parse error:", err) + ); + return result; + } + async getSubmodulePaths() { + return new Promise(async (resolve) => { + this.git.outputHandler(async (cmd, stdout, stderr, args) => { + if (!(args.contains("submodule") && args.contains("foreach"))) { + return; + } + let body = ""; + const root2 = this.app.vault.adapter.getBasePath() + (this.plugin.settings.basePath ? "/" + this.plugin.settings.basePath : ""); + stdout.on("data", (chunk) => { + body += chunk.toString("utf8"); + }); + stdout.on("end", async () => { + const submods = body.split("\n"); + const strippedSubmods = submods.map((i) => { + const submod = i.match(/'([^']*)'/); + if (submod != void 0) { + return root2 + "/" + submod[1] + import_path.sep; + } + }).filter((i) => !!i); + strippedSubmods.reverse(); + resolve(strippedSubmods); + }); + }); + await this.git.subModule(["foreach", "--recursive", ""]); + this.git.outputHandler(() => { + }); + }); + } + //Remove wrong `"` like "My file.md" + formatPath(path2, renamed = false) { + function format(path3) { + if (path3 == void 0) + return void 0; + if (path3.startsWith('"') && path3.endsWith('"')) { + return path3.substring(1, path3.length - 1); + } else { + return path3; + } + } + if (renamed) { + return { + from: format(path2.from), + path: format(path2.path) + }; + } else { + return { + path: format(path2.path) + }; + } + } + async blame(path2, trackMovement, ignoreWhitespace) { + path2 = this.getRelativeRepoPath(path2); + if (!await this.isTracked(path2)) + return "untracked"; + const inSubmodule = await this.getSubmoduleOfFile(path2); + const args = inSubmodule ? ["-C", inSubmodule.submodule] : []; + const relativePath = inSubmodule ? inSubmodule.relativeFilepath : path2; + args.push("blame", "--porcelain"); + if (ignoreWhitespace) + args.push("-w"); + const trackCArg = `-C${GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH}`; + switch (trackMovement) { + case "inactive": + break; + case "same-commit": + args.push("-C", trackCArg); + break; + case "all-commits": + args.push("-C", "-C", trackCArg); + break; + default: + impossibleBranch(trackMovement); + } + args.push("--", relativePath); + const rawBlame = await this.git.raw( + args, + (err) => err && console.warn("git-blame", err) + ); + return parseBlame(rawBlame); + } + async isTracked(path2) { + const inSubmodule = await this.getSubmoduleOfFile(path2); + const args = inSubmodule ? ["-C", inSubmodule.submodule] : []; + const relativePath = inSubmodule ? inSubmodule.relativeFilepath : path2; + args.push("ls-files", "--", relativePath); + return this.git.raw(args, (err) => err && console.warn("ls-files", err)).then((x) => x.trim() !== ""); + } + async commitAll({ message }) { + if (this.plugin.settings.updateSubmodules) { + this.plugin.setState(4 /* commit */); + const submodulePaths = await this.getSubmodulePaths(); + for (const item of submodulePaths) { + await this.git.cwd({ path: item, root: false }).add("-A", (err) => this.onError(err)); + await this.git.cwd({ path: item, root: false }).commit( + await this.formatCommitMessage(message), + (err) => this.onError(err) + ); + } + } + this.plugin.setState(3 /* add */); + await this.git.add("-A", (err) => this.onError(err)); + this.plugin.setState(4 /* commit */); + const res = await this.git.commit( + await this.formatCommitMessage(message), + (err) => this.onError(err) + ); + dispatchEvent(new CustomEvent("git-head-update")); + return res.summary.changes; + } + async commit({ + message, + amend + }) { + this.plugin.setState(4 /* commit */); + const res = (await this.git.commit( + await this.formatCommitMessage(message), + amend ? ["--amend"] : [], + (err) => this.onError(err) + )).summary.changes; + dispatchEvent(new CustomEvent("git-head-update")); + this.plugin.setState(0 /* idle */); + return res; + } + async stage(path2, relativeToVault) { + this.plugin.setState(3 /* add */); + path2 = this.getRelativeRepoPath(path2, relativeToVault); + await this.git.add(["--", path2], (err) => this.onError(err)); + this.plugin.setState(0 /* idle */); + } + async stageAll({ dir }) { + this.plugin.setState(3 /* add */); + await this.git.add(dir != null ? dir : "-A", (err) => this.onError(err)); + this.plugin.setState(0 /* idle */); + } + async unstageAll({ dir }) { + this.plugin.setState(3 /* add */); + await this.git.reset( + dir != void 0 ? ["--", dir] : [], + (err) => this.onError(err) + ); + this.plugin.setState(0 /* idle */); + } + async unstage(path2, relativeToVault) { + this.plugin.setState(3 /* add */); + path2 = this.getRelativeRepoPath(path2, relativeToVault); + await this.git.reset(["--", path2], (err) => this.onError(err)); + this.plugin.setState(0 /* idle */); + } + async discard(filepath) { + this.plugin.setState(3 /* add */); + await this.git.checkout(["--", filepath], (err) => this.onError(err)); + this.plugin.setState(0 /* idle */); + } + async hashObject(filepath) { + filepath = this.getRelativeRepoPath(filepath); + const inSubmodule = await this.getSubmoduleOfFile(filepath); + const args = inSubmodule ? ["-C", inSubmodule.submodule] : []; + const relativeFilepath = inSubmodule ? inSubmodule.relativeFilepath : filepath; + args.push("hash-object", "--", relativeFilepath); + const revision = this.git.raw(args); + revision.catch( + (err) => err && console.warn("obsidian-git. hash-object failed:", err == null ? void 0 : err.message) + ); + return revision; + } + async discardAll({ dir }) { + return this.discard(dir != null ? dir : "."); + } + async pull() { + this.plugin.setState(2 /* pull */); + if (this.plugin.settings.updateSubmodules) + await this.git.subModule( + ["update", "--remote", "--merge", "--recursive"], + (err) => this.onError(err) + ); + const branchInfo = await this.branchInfo(); + const localCommit = await this.git.revparse( + [branchInfo.current], + (err) => this.onError(err) + ); + if (!branchInfo.tracking && this.plugin.settings.updateSubmodules) { + this.plugin.log( + "No tracking branch found. Ignoring pull of main repo and updating submodules only." + ); + return; + } + await this.git.fetch((err) => this.onError(err)); + const upstreamCommit = await this.git.revparse( + [branchInfo.tracking], + (err) => this.onError(err) + ); + if (localCommit !== upstreamCommit) { + if (this.plugin.settings.syncMethod === "merge" || this.plugin.settings.syncMethod === "rebase") { + try { + switch (this.plugin.settings.syncMethod) { + case "merge": + await this.git.merge([branchInfo.tracking]); + break; + case "rebase": + await this.git.rebase([branchInfo.tracking]); + } + } catch (err) { + this.plugin.displayError( + `Pull failed (${this.plugin.settings.syncMethod}): ${err.message}` + ); + return; + } + } else if (this.plugin.settings.syncMethod === "reset") { + try { + await this.git.raw( + [ + "update-ref", + `refs/heads/${branchInfo.current}`, + upstreamCommit + ], + (err) => this.onError(err) + ); + await this.unstageAll({}); + } catch (err) { + this.plugin.displayError( + `Sync failed (${this.plugin.settings.syncMethod}): ${err.message}` + ); + } + } + dispatchEvent(new CustomEvent("git-head-update")); + const afterMergeCommit = await this.git.revparse( + [branchInfo.current], + (err) => this.onError(err) + ); + const filesChanged = await this.git.diff([ + `${localCommit}..${afterMergeCommit}`, + "--name-only" + ]); + return filesChanged.split(/\r\n|\r|\n/).filter((value) => value.length > 0).map((e) => { + return { + path: e, + working_dir: "P", + vault_path: this.getRelativeVaultPath(e) + }; + }); + } else { + return []; + } + } + async push() { + this.plugin.setState(5 /* push */); + if (this.plugin.settings.updateSubmodules) { + const res = await this.git.env({ ...process.env, OBSIDIAN_GIT: 1 }).subModule( + [ + "foreach", + "--recursive", + `tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"); echo $tracking; if [ ! -z "$(git diff --shortstat $tracking)" ]; then git push; fi` + ], + (err) => this.onError(err) + ); + console.log(res); + } + const status2 = await this.git.status(); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + if (!trackingBranch && this.plugin.settings.updateSubmodules) { + this.plugin.log( + "No tracking branch found. Ignoring push of main repo and updating submodules only." + ); + return void 0; + } + const remoteChangedFiles = (await this.git.diffSummary( + [currentBranch2, trackingBranch, "--"], + (err) => this.onError(err) + )).changed; + await this.git.env({ ...process.env, OBSIDIAN_GIT: 1 }).push((err) => this.onError(err)); + return remoteChangedFiles; + } + async getUnpushedCommits() { + const status2 = await this.git.status(); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + if (trackingBranch == null || currentBranch2 == null) { + return 0; + } + const remoteChangedFiles = (await this.git.diffSummary( + [currentBranch2, trackingBranch, "--"], + (err) => this.onError(err) + )).changed; + return remoteChangedFiles; + } + async canPush() { + if (this.plugin.settings.updateSubmodules === true) { + return true; + } + const status2 = await this.git.status((err) => this.onError(err)); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + if (!trackingBranch) { + return false; + } + const remoteChangedFiles = (await this.git.diffSummary([currentBranch2, trackingBranch, "--"])).changed; + return remoteChangedFiles !== 0; + } + async checkRequirements() { + if (!this.isGitInstalled()) { + return "missing-git"; + } + if (!await this.git.checkIsRepo()) { + return "missing-repo"; + } + return "valid"; + } + async branchInfo() { + const status2 = await this.git.status((err) => this.onError(err)); + const branches = await this.git.branch( + ["--no-color"], + (err) => this.onError(err) + ); + return { + current: status2.current || void 0, + tracking: status2.tracking || void 0, + branches: branches.all + }; + } + async getRemoteUrl(remote) { + try { + return await this.git.remote(["get-url", remote]) || void 0; + } catch (error) { + if (error.toString().contains(remote)) { + return void 0; + } else { + this.onError(error); + } + } + } + // https://github.com/kometenstaub/obsidian-version-history-diff/issues/3 + async log(file, relativeToVault = true, limit) { + let path2; + if (file) { + path2 = this.getRelativeRepoPath(file, relativeToVault); + } + const res = await this.git.log( + { + file: path2, + maxCount: limit, + "-m": null, + "--name-status": null + }, + (err) => this.onError(err) + ); + return res.all.map((e) => { + var _a2, _b, _c, _d; + return { + ...e, + author: { + name: e.author_name, + email: e.author_email + }, + refs: e.refs.split(", ").filter((e2) => e2.length > 0), + diff: { + ...e.diff, + files: (_b = (_a2 = e.diff) == null ? void 0 : _a2.files.map((f) => ({ + ...f, + status: f.status, + path: f.file, + hash: e.hash, + vault_path: this.getRelativeVaultPath(f.file) + }))) != null ? _b : [] + }, + fileName: (_d = (_c = e.diff) == null ? void 0 : _c.files.first()) == null ? void 0 : _d.file + }; + }); + } + async show(commitHash, file, relativeToVault = true) { + const path2 = this.getRelativeRepoPath(file, relativeToVault); + return this.git.show( + [commitHash + ":" + path2], + (err) => this.onError(err) + ); + } + async checkout(branch2, remote) { + if (remote) { + branch2 = `${remote}/${branch2}`; + } + await this.git.checkout(branch2, (err) => this.onError(err)); + if (this.plugin.settings.submoduleRecurseCheckout) { + const submodulePaths = await this.getSubmodulePaths(); + for (const submodulePath of submodulePaths) { + const branchSummary = await this.git.cwd({ path: submodulePath, root: false }).branch(); + if (Object.keys(branchSummary.branches).includes(branch2)) { + await this.git.cwd({ path: submodulePath, root: false }).checkout(branch2, (err) => this.onError(err)); + } + } + } + } + async createBranch(branch2) { + await this.git.checkout(["-b", branch2], (err) => this.onError(err)); + } + async deleteBranch(branch2, force) { + await this.git.branch( + [force ? "-D" : "-d", branch2], + (err) => this.onError(err) + ); + } + async branchIsMerged(branch2) { + const notMergedBranches = await this.git.branch( + ["--no-merged"], + (err) => this.onError(err) + ); + return !notMergedBranches.all.contains(branch2); + } + async init() { + await this.git.init(false, (err) => this.onError(err)); + } + async clone(url, dir, depth) { + await this.git.clone( + url, + path.join( + this.app.vault.adapter.getBasePath(), + dir + ), + depth ? ["--depth", `${depth}`] : [], + (err) => this.onError(err) + ); + } + async setConfig(path2, value) { + if (value == void 0) { + await this.git.raw(["config", "--local", "--unset", path2]); + } else { + await this.git.addConfig(path2, value, (err) => this.onError(err)); + } + } + async getConfig(path2) { + const config = await this.git.listConfig( + "local", + (err) => this.onError(err) + ); + return config.all[path2]; + } + async fetch(remote) { + await this.git.fetch( + remote != void 0 ? [remote] : [], + (err) => this.onError(err) + ); + } + async setRemote(name, url) { + if ((await this.getRemotes()).includes(name)) + await this.git.remote( + ["set-url", name, url], + (err) => this.onError(err) + ); + else { + await this.git.remote( + ["add", name, url], + (err) => this.onError(err) + ); + } + } + async getRemoteBranches(remote) { + const res = await this.git.branch( + ["-r", "--list", `${remote}*`], + (err) => this.onError(err) + ); + const list = []; + for (const item in res.branches) { + list.push(res.branches[item].name); + } + return list; + } + async getRemotes() { + const res = await this.git.remote([], (err) => this.onError(err)); + if (res) { + return res.trim().split("\n"); + } else { + return []; + } + } + async removeRemote(remoteName) { + await this.git.removeRemote(remoteName); + } + async updateUpstreamBranch(remoteBranch) { + try { + await this.git.branch(["--set-upstream-to", remoteBranch]); + } catch (e) { + console.error(e); + try { + await this.git.branch(["--set-upstream", remoteBranch]); + } catch (e2) { + console.error(e2); + await this.git.push( + // A type error occurs here because the third element could be undefined. + // However, it is unlikely to be undefined due to the `remoteBranch`'s format, and error handling is in place. + // Therefore, we temporarily ignore the error. + // @ts-ignore + ["--set-upstream", ...splitRemoteBranch(remoteBranch)], + (err) => this.onError(err) + ); + } + } + } + updateGitPath(gitPath) { + this.setGitInstance(); + } + updateBasePath(basePath) { + this.setGitInstance(true); + } + async getDiffString(filePath, stagedChanges = false, hash2) { + if (stagedChanges) + return await this.git.diff(["--cached", "--", filePath]); + if (hash2) + return await this.git.show([`${hash2}`, "--", filePath]); + else + return await this.git.diff(["--", filePath]); + } + async diff(file, commit1, commit2) { + return await this.git.diff([`${commit1}..${commit2}`, "--", file]); + } + async getSubmoduleOfFile(repositoryRelativeFile) { + let submoduleRoot = await this.git.raw( + [ + "-C", + path.dirname(repositoryRelativeFile), + "rev-parse", + "--show-toplevel" + ], + (err) => err && console.warn("get-submodule-of-file", err == null ? void 0 : err.message) + ); + submoduleRoot = submoduleRoot.trim(); + const superProject = await this.git.raw( + [ + "-C", + path.dirname(repositoryRelativeFile), + "rev-parse", + "--show-superproject-working-tree" + ], + (err) => err && console.warn("get-submodule-of-file", err == null ? void 0 : err.message) + ); + if (superProject.trim() === "") { + return void 0; + } + const fsAdapter = this.app.vault.adapter; + const absolutePath = fsAdapter.getFullPath( + path.normalize(repositoryRelativeFile) + ); + const newRelativePath = path.relative(submoduleRoot, absolutePath); + return { submodule: submoduleRoot, relativeFilepath: newRelativePath }; + } + async getLastCommitTime() { + const res = await this.git.log({ n: 1 }, (err) => this.onError(err)); + if (res != null && res.latest != null) { + return new Date(res.latest.date); + } + } + isGitInstalled() { + const command = (0, import_child_process2.spawnSync)( + this.plugin.localStorage.getGitPath() || "git", + ["--version"], + { + stdio: "ignore" + } + ); + if (command.error) { + console.error(command.error); + return false; + } + return true; + } + onError(error) { + if (error) { + const networkFailure = error.message.contains("Could not resolve host") || error.message.match( + /ssh: connect to host .*? port .*?: Operation timed out/ + ) || error.message.match( + /ssh: connect to host .*? port .*?: Network is unreachable/ + ); + if (!networkFailure) { + this.plugin.displayError(error.message); + this.plugin.setState(0 /* idle */); + } else if (!this.plugin.offlineMode) { + this.plugin.displayError( + "Git: Going into offline mode. Future network errors will no longer be displayed.", + 2e3 + ); + } + if (networkFailure) { + this.plugin.offlineMode = true; + this.plugin.setState(0 /* idle */); + } + } + } +}; +var zeroCommit = { + hash: "000000", + isZeroCommit: true, + summary: "" +}; +function parseBlame(blameOutputUnnormalized) { + const blameOutput = blameOutputUnnormalized.replace("\r\n", "\n"); + const blameLines = blameOutput.split("\n"); + const result = { + commits: /* @__PURE__ */ new Map(), + hashPerLine: [void 0], + // one-based indices + originalFileLineNrPerLine: [void 0], + finalFileLineNrPerLine: [void 0], + groupSizePerStartingLine: /* @__PURE__ */ new Map() + }; + let line = 1; + for (let bi = 0; bi < blameLines.length; ) { + if (startsWithNonWhitespace(blameLines[bi])) { + const lineInfo = blameLines[bi].split(" "); + const commitHash = parseLineInfoInto(lineInfo, line, result); + bi++; + for (; startsWithNonWhitespace(blameLines[bi]); bi++) { + const spaceSeparatedHeaderValues = blameLines[bi].split(" "); + parseHeaderInto(spaceSeparatedHeaderValues, result, line); + } + finalizeBlameCommitInfo(result.commits.get(commitHash)); + line += 1; + } else if (blameLines[bi] === "" && bi === blameLines.length - 1) { + } else { + throw Error( + `Expected non-whitespace line or EOF, but found: ${blameLines[bi]}` + ); + } + bi++; + } + return result; +} +function parseLineInfoInto(lineInfo, line, result) { + const hash2 = lineInfo[0]; + result.hashPerLine.push(hash2); + result.originalFileLineNrPerLine.push(parseInt(lineInfo[1])); + result.finalFileLineNrPerLine.push(parseInt(lineInfo[2])); + lineInfo.length >= 4 && result.groupSizePerStartingLine.set(line, parseInt(lineInfo[3])); + if (parseInt(lineInfo[2]) !== line) { + throw Error( + `git-blame output is out of order: ${line} vs ${lineInfo[2]}` + ); + } + return hash2; +} +function parseHeaderInto(header, out, line) { + const key2 = header[0]; + const value = header.slice(1).join(" "); + const commitHash = out.hashPerLine[line]; + const commit2 = out.commits.get(commitHash) || { + hash: commitHash, + author: {}, + committer: {}, + previous: {} + }; + switch (key2) { + case "summary": + commit2.summary = value; + break; + case "author": + commit2.author.name = value; + break; + case "author-mail": + commit2.author.email = removeEmailBrackets(value); + break; + case "author-time": + commit2.author.epochSeconds = parseInt(value); + break; + case "author-tz": + commit2.author.tz = value; + break; + case "committer": + commit2.committer.name = value; + break; + case "committer-mail": + commit2.committer.email = removeEmailBrackets(value); + break; + case "committer-time": + commit2.committer.epochSeconds = parseInt(value); + break; + case "committer-tz": + commit2.committer.tz = value; + break; + case "previous": + commit2.previous.commitHash = value; + break; + case "filename": + commit2.previous.filename = value; + break; + } + out.commits.set(commitHash, commit2); +} +function finalizeBlameCommitInfo(commit2) { + if (commit2.summary === void 0) { + throw Error(`Summary not provided for commit: ${commit2.hash}`); + } + if (isUndefinedOrEmptyObject(commit2.author)) { + commit2.author = void 0; + } + if (isUndefinedOrEmptyObject(commit2.committer)) { + commit2.committer = void 0; + } + if (isUndefinedOrEmptyObject(commit2.previous)) { + commit2.previous = void 0; + } + commit2.isZeroCommit = Boolean(commit2.hash.match(/^0*$/)); +} +function isUndefinedOrEmptyObject(obj) { + return !obj || Object.keys(obj).length === 0; +} +function startsWithNonWhitespace(str) { + return str.length > 0 && str[0].trim() === str[0]; +} +function removeEmailBrackets(gitEmail) { + const prefixCleaned = gitEmail.startsWith("<") ? gitEmail.substring(1) : gitEmail; + return prefixCleaned.endsWith(">") ? prefixCleaned.substring(0, prefixCleaned.length - 1) : prefixCleaned; +} + +// src/lineAuthor/lineAuthorProvider.ts +init_polyfill_buffer(); +var import_state4 = require("@codemirror/state"); + +// src/lineAuthor/control.ts +init_polyfill_buffer(); +var import_state2 = require("@codemirror/state"); +var import_obsidian9 = require("obsidian"); + +// src/lineAuthor/eventsPerFilepath.ts +init_polyfill_buffer(); +var SECONDS = 1e3; +var REMOVE_STALES_FREQUENCY = 60 * SECONDS; +var EventsPerFilePath = class { + constructor() { + this.eventsPerFilepath = /* @__PURE__ */ new Map(); + this.startRemoveStalesSubscribersInterval(); + } + /** + * Run the {@link handler} on the subscribers to {@link filepath}. + */ + ifFilepathDefinedTransformSubscribers(filepath, handler) { + if (!filepath) + return; + this.ensureInitialized(filepath); + return handler(this.eventsPerFilepath.get(filepath)); + } + forEachSubscriber(handler) { + this.eventsPerFilepath.forEach((subs) => subs.forEach(handler)); + } + ensureInitialized(filepath) { + if (!this.eventsPerFilepath.get(filepath)) + this.eventsPerFilepath.set(filepath, /* @__PURE__ */ new Set()); + } + startRemoveStalesSubscribersInterval() { + this.removeStalesSubscribersTimer = window.setInterval( + () => this == null ? void 0 : this.forEachSubscriber((las) => las == null ? void 0 : las.removeIfStale()), + REMOVE_STALES_FREQUENCY + ); + } + clear() { + window.clearInterval(this.removeStalesSubscribersTimer); + this.eventsPerFilepath.clear(); + } +}; +var eventsPerFilePathSingleton = new EventsPerFilePath(); + +// src/lineAuthor/model.ts +init_polyfill_buffer(); +var import_state = require("@codemirror/state"); +var import_js_sha256 = __toESM(require_sha256()); + +// src/setting/settings.ts +init_polyfill_buffer(); +var import_obsidian8 = require("obsidian"); + +// src/gitManager/isomorphicGit.ts +init_polyfill_buffer(); + +// node_modules/.pnpm/diff@5.2.0/node_modules/diff/lib/index.mjs +init_polyfill_buffer(); +function Diff() { +} +Diff.prototype = { + diff: function diff(oldString, newString) { + var _options$timeout; + var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + var callback = options.callback; + if (typeof options === "function") { + callback = options; + options = {}; + } + this.options = options; + var self2 = this; + function done(value) { + if (callback) { + setTimeout(function() { + callback(void 0, value); + }, 0); + return true; + } else { + return value; + } + } + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + if (options.maxEditLength) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; + var abortAfterTimestamp = Date.now() + maxExecutionTime; + var bestPath = [{ + oldPos: -1, + lastComponent: void 0 + }]; + var newPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done([{ + value: this.join(newString), + count: newString.length + }]); + } + var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + function execEditLength() { + for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + var basePath = void 0; + var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + bestPath[diagonalPath - 1] = void 0; + } + var canAdd = false; + if (addPath) { + var addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + var canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { + basePath = self2.addToPath(addPath, true, void 0, 0); + } else { + basePath = self2.addToPath(removePath, void 0, true, 1); + } + newPos = self2.extractCommon(basePath, newString, oldString, diagonalPath); + if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(buildValues(self2, basePath.lastComponent, newString, oldString, self2.useLongestToken)); + } else { + bestPath[diagonalPath] = basePath; + if (basePath.oldPos + 1 >= oldLen) { + maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); + } + if (newPos + 1 >= newLen) { + minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + } + } + } + editLength++; + } + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { + return callback(); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + addToPath: function addToPath(path2, added, removed, oldPosInc) { + var last2 = path2.lastComponent; + if (last2 && last2.added === added && last2.removed === removed) { + return { + oldPos: path2.oldPos + oldPosInc, + lastComponent: { + count: last2.count + 1, + added, + removed, + previousComponent: last2.previousComponent + } + }; + } else { + return { + oldPos: path2.oldPos + oldPosInc, + lastComponent: { + count: 1, + added, + removed, + previousComponent: last2 + } + }; + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + if (commonCount) { + basePath.lastComponent = { + count: commonCount, + previousComponent: basePath.lastComponent + }; + } + basePath.oldPos = oldPos; + return newPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(""); + }, + join: function join3(chars) { + return chars.join(""); + } +}; +function buildValues(diff3, lastComponent, newString, oldString, useLongestToken) { + var components = []; + var nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = diff3.join(value); + } else { + component.value = diff3.join(newString.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff3.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } + var finalComponent = components[componentLen - 1]; + if (componentLen > 1 && typeof finalComponent.value === "string" && (finalComponent.added || finalComponent.removed) && diff3.equals("", finalComponent.value)) { + components[componentLen - 2].value += finalComponent.value; + components.pop(); + } + return components; +} +var characterDiff = new Diff(); +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); +wordDiff.equals = function(left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; +wordDiff.tokenize = function(value) { + var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); + for (var i = 0; i < tokens.length - 1; i++) { + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + return tokens; +}; +var lineDiff = new Diff(); +lineDiff.tokenize = function(value) { + if (this.options.stripTrailingCr) { + value = value.replace(/\r\n/g, "\n"); + } + var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + retLines.push(line); + } + } + return retLines; +}; +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} +var sentenceDiff = new Diff(); +sentenceDiff.tokenize = function(value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; +var cssDiff = new Diff(); +cssDiff.tokenize = function(value) { + return value.split(/([{}:;,]|\s+)/); +}; +function _typeof(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function(obj2) { + return typeof obj2; + }; + } else { + _typeof = function(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; + } + return _typeof(obj); +} +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) + return _arrayLikeToArray(arr); +} +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) + return Array.from(iter); +} +function _unsupportedIterableToArray(o, minLen) { + if (!o) + return; + if (typeof o === "string") + return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) + n = o.constructor.name; + if (n === "Map" || n === "Set") + return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) + return _arrayLikeToArray(o, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) + arr2[i] = arr[i]; + return arr2; +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; +jsonDiff.castInput = function(value) { + var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) { + return typeof v === "undefined" ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " "); +}; +jsonDiff.equals = function(left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1")); +}; +function canonicalize(obj, stack, replacementStack, replacer, key2) { + stack = stack || []; + replacementStack = replacementStack || []; + if (replacer) { + obj = replacer(key2, obj); + } + var i; + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + var canonicalizedObj; + if ("[object Array]" === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key2); + } + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + if (_typeof(obj) === "object" && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], _key; + for (_key in obj) { + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; +} +var arrayDiff = new Diff(); +arrayDiff.tokenize = function(value) { + return value.slice(); +}; +arrayDiff.join = arrayDiff.removeEmpty = function(value) { + return value; +}; +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + if (typeof options.context === "undefined") { + options.context = 4; + } + var diff3 = diffLines(oldStr, newStr, options); + if (!diff3) { + return; + } + diff3.push({ + value: "", + lines: [] + }); + function contextLines(lines) { + return lines.map(function(entry) { + return " " + entry; + }); + } + var hunks = []; + var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + var _loop = function _loop2(i2) { + var current = diff3[i2], lines = current.lines || current.value.replace(/\n$/, "").split("\n"); + current.lines = lines; + if (current.added || current.removed) { + var _curRange; + if (!oldRangeStart) { + var prev = diff3[i2 - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) { + return (current.added ? "+" : "-") + entry; + }))); + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + if (lines.length <= options.context * 2 && i2 < diff3.length - 2) { + var _curRange2; + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + var contextSize = Math.min(lines.length, options.context); + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + if (i2 >= diff3.length - 2 && lines.length <= options.context) { + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { + curRange.splice(hunk.oldLines, 0, "\\ No newline at end of file"); + } + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push("\\ No newline at end of file"); + } + } + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + }; + for (var i = 0; i < diff3.length; i++) { + _loop(i); + } + return { + oldFileName, + newFileName, + oldHeader, + newHeader, + hunks + }; +} +function formatPatch(diff3) { + if (Array.isArray(diff3)) { + return diff3.map(formatPatch).join("\n"); + } + var ret = []; + if (diff3.oldFileName == diff3.newFileName) { + ret.push("Index: " + diff3.oldFileName); + } + ret.push("==================================================================="); + ret.push("--- " + diff3.oldFileName + (typeof diff3.oldHeader === "undefined" ? "" : " " + diff3.oldHeader)); + ret.push("+++ " + diff3.newFileName + (typeof diff3.newHeader === "undefined" ? "" : " " + diff3.newHeader)); + for (var i = 0; i < diff3.hunks.length; i++) { + var hunk = diff3.hunks[i]; + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); + ret.push.apply(ret, hunk.lines); + } + return ret.join("\n") + "\n"; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +// src/gitManager/isomorphicGit.ts +var import_obsidian7 = require("obsidian"); + +// src/ui/modals/generalModal.ts +init_polyfill_buffer(); +var import_obsidian5 = require("obsidian"); +var generalModalConfigDefaults = { + options: [], + placeholder: "", + allowEmpty: false, + onlySelection: false, + initialValue: void 0 +}; +var GeneralModal = class extends import_obsidian5.SuggestModal { + constructor(config) { + super(app); + this.config = { ...generalModalConfigDefaults, ...config }; + this.setPlaceholder(this.config.placeholder); + } + open() { + super.open(); + if (this.config.initialValue != void 0) { + this.inputEl.value = this.config.initialValue; + this.inputEl.dispatchEvent(new Event("input")); + } + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + selectSuggestion(value, evt) { + if (this.resolve) { + let res; + if (this.config.allowEmpty && value === " ") + res = ""; + else if (value === "...") + res = void 0; + else + res = value; + this.resolve(res); + } + super.selectSuggestion(value, evt); + } + onClose() { + if (this.resolve) + this.resolve(void 0); + } + getSuggestions(query) { + if (this.config.onlySelection) { + return this.config.options; + } else if (this.config.allowEmpty) { + return [query.length > 0 ? query : " ", ...this.config.options]; + } else { + return [query.length > 0 ? query : "...", ...this.config.options]; + } + } + renderSuggestion(value, el) { + el.setText(value); + } + onChooseSuggestion(item, evt) { + } +}; + +// src/gitManager/myAdapter.ts +init_polyfill_buffer(); +var import_obsidian6 = require("obsidian"); +var MyAdapter = class { + constructor(vault, plugin) { + this.plugin = plugin; + this.promises = {}; + this.adapter = vault.adapter; + this.vault = vault; + this.lastBasePath = this.plugin.settings.basePath; + this.promises.readFile = this.readFile.bind(this); + this.promises.writeFile = this.writeFile.bind(this); + this.promises.readdir = this.readdir.bind(this); + this.promises.mkdir = this.mkdir.bind(this); + this.promises.rmdir = this.rmdir.bind(this); + this.promises.stat = this.stat.bind(this); + this.promises.unlink = this.unlink.bind(this); + this.promises.lstat = this.lstat.bind(this); + this.promises.readlink = this.readlink.bind(this); + this.promises.symlink = this.symlink.bind(this); + } + async readFile(path2, opts) { + var _a2; + this.maybeLog("Read: " + path2 + JSON.stringify(opts)); + if (opts == "utf8" || opts.encoding == "utf8") { + const file = this.vault.getAbstractFileByPath(path2); + if (file instanceof import_obsidian6.TFile) { + this.maybeLog("Reuse"); + return this.vault.read(file); + } else { + return this.adapter.read(path2); + } + } else { + if (path2.endsWith(this.gitDir + "/index")) { + if (this.plugin.settings.basePath != this.lastBasePath) { + this.clearIndex(); + this.lastBasePath = this.plugin.settings.basePath; + return this.adapter.readBinary(path2); + } + return (_a2 = this.index) != null ? _a2 : this.adapter.readBinary(path2); + } + const file = this.vault.getAbstractFileByPath(path2); + if (file instanceof import_obsidian6.TFile) { + this.maybeLog("Reuse"); + return this.vault.readBinary(file); + } else { + return this.adapter.readBinary(path2); + } + } + } + async writeFile(path2, data) { + this.maybeLog("Write: " + path2); + if (typeof data === "string") { + const file = this.vault.getAbstractFileByPath(path2); + if (file instanceof import_obsidian6.TFile) { + return this.vault.modify(file, data); + } else { + return this.adapter.write(path2, data); + } + } else { + if (path2.endsWith(this.gitDir + "/index")) { + this.index = data; + this.indexmtime = Date.now(); + } else { + const file = this.vault.getAbstractFileByPath(path2); + if (file instanceof import_obsidian6.TFile) { + return this.vault.modifyBinary(file, data); + } else { + return this.adapter.writeBinary(path2, data); + } + } + } + } + async readdir(path2) { + if (path2 === ".") + path2 = "/"; + const res = await this.adapter.list(path2); + const all = [...res.files, ...res.folders]; + let formattedAll; + if (path2 !== "/") { + formattedAll = all.map( + (e) => (0, import_obsidian6.normalizePath)(e.substring(path2.length)) + ); + } else { + formattedAll = all; + } + return formattedAll; + } + async mkdir(path2) { + return this.adapter.mkdir(path2); + } + async rmdir(path2, opts) { + var _a2, _b; + return this.adapter.rmdir(path2, (_b = (_a2 = opts == null ? void 0 : opts.options) == null ? void 0 : _a2.recursive) != null ? _b : false); + } + async stat(path2) { + if (path2.endsWith(this.gitDir + "/index")) { + if (this.index !== void 0 && this.indexctime != void 0 && this.indexmtime != void 0) { + return { + isFile: () => true, + isDirectory: () => false, + isSymbolicLink: () => false, + size: this.index.length, + type: "file", + ctimeMs: this.indexctime, + mtimeMs: this.indexmtime + }; + } else { + const stat = await this.adapter.stat(path2); + if (stat == void 0) { + throw { code: "ENOENT" }; + } + this.indexctime = stat.ctime; + this.indexmtime = stat.mtime; + return { + ctimeMs: stat.ctime, + mtimeMs: stat.mtime, + size: stat.size, + type: "file", + isFile: () => true, + isDirectory: () => false, + isSymbolicLink: () => false + }; + } + } + if (path2 === ".") + path2 = "/"; + const file = this.vault.getAbstractFileByPath(path2); + this.maybeLog("Stat: " + path2); + if (file instanceof import_obsidian6.TFile) { + this.maybeLog("Reuse stat"); + return { + ctimeMs: file.stat.ctime, + mtimeMs: file.stat.mtime, + size: file.stat.size, + type: "file", + isFile: () => true, + isDirectory: () => false, + isSymbolicLink: () => false + }; + } else { + const stat = await this.adapter.stat(path2); + if (stat) { + return { + ctimeMs: stat.ctime, + mtimeMs: stat.mtime, + size: stat.size, + type: stat.type === "folder" ? "directory" : stat.type, + isFile: () => stat.type === "file", + isDirectory: () => stat.type === "folder", + isSymbolicLink: () => false + }; + } else { + throw { code: "ENOENT" }; + } + } + } + async unlink(path2) { + return this.adapter.remove(path2); + } + async lstat(path2) { + return this.stat(path2); + } + async readlink(path2) { + throw new Error(`readlink of (${path2}) is not implemented.`); + } + async symlink(path2) { + throw new Error(`symlink of (${path2}) is not implemented.`); + } + async saveAndClear() { + if (this.index !== void 0) { + await this.adapter.writeBinary( + this.plugin.gitManager.getRelativeVaultPath( + this.gitDir + "/index" + ), + this.index, + { + ctime: this.indexctime, + mtime: this.indexmtime + } + ); + } + this.clearIndex(); + } + clearIndex() { + this.index = void 0; + this.indexctime = void 0; + this.indexmtime = void 0; + } + get gitDir() { + return this.plugin.settings.gitDir || ".git"; + } + maybeLog(text2) { + } +}; + +// src/gitManager/isomorphicGit.ts +var IsomorphicGit = class extends GitManager { + constructor(plugin) { + super(plugin); + this.FILE = 0; + this.HEAD = 1; + this.WORKDIR = 2; + this.STAGE = 3; + // Mapping from statusMatrix to git status codes based off git status --short + // See: https://isomorphic-git.org/docs/en/statusMatrix + this.status_mapping = { + "000": " ", + "003": "AD", + "020": "??", + "022": "A ", + "023": "AM", + "100": "D ", + "101": " D", + "103": "MD", + "110": "DA", + // Technically, two files: first one is deleted "D " and second one is untracked "??" + "111": " ", + "113": "MM", + "120": "DA", + // Same as "110" + "121": " M", + "122": "M ", + "123": "MM" + }; + this.noticeLength = 999999; + this.fs = new MyAdapter(this.app.vault, this.plugin); + } + getRepo() { + return { + fs: this.fs, + dir: this.plugin.settings.basePath, + gitdir: this.plugin.settings.gitDir || void 0, + onAuth: () => { + var _a2, _b; + return { + username: (_a2 = this.plugin.localStorage.getUsername()) != null ? _a2 : void 0, + password: (_b = this.plugin.localStorage.getPassword()) != null ? _b : void 0 + }; + }, + onAuthFailure: async () => { + new import_obsidian7.Notice( + "Authentication failed. Please try with different credentials" + ); + const username = await new GeneralModal({ + placeholder: "Specify your username" + }).open(); + if (username) { + const password = await new GeneralModal({ + placeholder: "Specify your password/personal access token" + }).open(); + if (password) { + this.plugin.localStorage.setUsername(username); + this.plugin.localStorage.setPassword(password); + return { + username, + password + }; + } + } + return { cancel: true }; + }, + http: { + async request({ + url, + method: method2, + headers, + body + }) { + if (body) { + body = await collect2(body); + body = body.buffer; + } + const res = await (0, import_obsidian7.requestUrl)({ + url, + method: method2, + headers, + body, + throw: false + }); + return { + url, + method: method2, + headers: res.headers, + body: [new Uint8Array(res.arrayBuffer)], + statusCode: res.status, + statusMessage: res.status.toString() + }; + } + } + }; + } + async wrapFS(call) { + try { + const res = await call; + await this.fs.saveAndClear(); + return res; + } catch (error) { + await this.fs.saveAndClear(); + throw error; + } + } + async status() { + let notice; + const timeout = window.setTimeout(function() { + notice = new import_obsidian7.Notice( + "This takes longer: Getting status", + this.noticeLength + ); + }, 2e4); + try { + this.plugin.setState(1 /* status */); + const status2 = (await this.wrapFS(isomorphic_git_default.statusMatrix({ ...this.getRepo() }))).map((row) => this.getFileStatusResult(row)); + const changed = status2.filter( + (fileStatus) => fileStatus.working_dir !== " " + ); + const staged = status2.filter( + (fileStatus) => fileStatus.index !== " " && fileStatus.index !== "U" + ); + const conflicted = []; + window.clearTimeout(timeout); + notice == null ? void 0 : notice.hide(); + return { all: status2, changed, staged, conflicted }; + } catch (error) { + window.clearTimeout(timeout); + notice == null ? void 0 : notice.hide(); + this.plugin.displayError(error); + throw error; + } + } + async commitAll({ + message, + status: status2, + unstagedFiles + }) { + try { + await this.checkAuthorInfo(); + await this.stageAll({ status: status2, unstagedFiles }); + return this.commit({ message }); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async commit({ + message + }) { + try { + await this.checkAuthorInfo(); + this.plugin.setState(4 /* commit */); + const formatMessage = await this.formatCommitMessage(message); + const hadConflict = this.plugin.localStorage.getConflict(); + let parent = void 0; + if (hadConflict) { + const branchInfo = await this.branchInfo(); + parent = [branchInfo.current, branchInfo.tracking]; + } + await this.wrapFS( + isomorphic_git_default.commit({ + ...this.getRepo(), + message: formatMessage, + parent + }) + ); + this.plugin.localStorage.setConflict(false); + return; + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async stage(filepath, relativeToVault) { + const gitPath = this.getRelativeRepoPath(filepath, relativeToVault); + let vaultPath; + if (relativeToVault) { + vaultPath = filepath; + } else { + vaultPath = this.getRelativeVaultPath(filepath); + } + try { + this.plugin.setState(3 /* add */); + if (await this.app.vault.adapter.exists(vaultPath)) { + await this.wrapFS( + isomorphic_git_default.add({ ...this.getRepo(), filepath: gitPath }) + ); + } else { + await this.wrapFS( + isomorphic_git_default.remove({ ...this.getRepo(), filepath: gitPath }) + ); + } + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async stageAll({ + dir, + status: status2, + unstagedFiles + }) { + try { + if (status2) { + await Promise.all( + status2.changed.map( + (file) => file.working_dir !== "D" ? this.wrapFS( + isomorphic_git_default.add({ + ...this.getRepo(), + filepath: file.path + }) + ) : isomorphic_git_default.remove({ + ...this.getRepo(), + filepath: file.path + }) + ) + ); + } else { + const filesToStage = unstagedFiles != null ? unstagedFiles : await this.getUnstagedFiles(dir != null ? dir : "."); + await Promise.all( + filesToStage.map( + ({ filepath, deleted }) => deleted ? isomorphic_git_default.remove({ ...this.getRepo(), filepath }) : this.wrapFS( + isomorphic_git_default.add({ ...this.getRepo(), filepath }) + ) + ) + ); + } + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async unstage(filepath, relativeToVault) { + try { + this.plugin.setState(3 /* add */); + filepath = this.getRelativeRepoPath(filepath, relativeToVault); + await this.wrapFS( + isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async unstageAll({ + dir, + status: status2 + }) { + try { + let staged; + if (status2) { + staged = status2.staged.map((file) => file.path); + } else { + const res = await this.getStagedFiles(dir != null ? dir : "."); + staged = res.map(({ filepath }) => filepath); + } + await this.wrapFS( + Promise.all( + staged.map( + (file) => isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath: file }) + ) + ) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async discard(filepath) { + try { + this.plugin.setState(3 /* add */); + await this.wrapFS( + isomorphic_git_default.checkout({ + ...this.getRepo(), + filepaths: [filepath], + force: true + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async discardAll({ + dir, + status: status2 + }) { + let files = []; + if (status2) { + if (dir != void 0) { + files = status2.changed.filter((file) => file.path.startsWith(dir)).map((file) => file.path); + } else { + files = status2.changed.map((file) => file.path); + } + } else { + files = (await this.getUnstagedFiles(dir)).map( + ({ filepath }) => filepath + ); + } + try { + await this.wrapFS( + isomorphic_git_default.checkout({ + ...this.getRepo(), + filepaths: files, + force: true + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + getProgressText(action, event) { + let out = `${action} progress:`; + if (event.phase) { + out = `${out} ${event.phase}:`; + } + if (event.loaded) { + out = `${out} ${event.loaded}`; + if (event.total) { + out = `${out} of ${event.total}`; + } + } + return out; + } + resolveRef(ref) { + return this.wrapFS(isomorphic_git_default.resolveRef({ ...this.getRepo(), ref })); + } + async pull() { + const progressNotice = this.showNotice("Initializing pull"); + try { + this.plugin.setState(2 /* pull */); + const localCommit = await this.resolveRef("HEAD"); + await this.fetch(); + const branchInfo = await this.branchInfo(); + await this.checkAuthorInfo(); + const mergeRes = await this.wrapFS( + isomorphic_git_default.merge({ + ...this.getRepo(), + ours: branchInfo.current, + theirs: branchInfo.tracking, + abortOnConflict: false + }) + ); + if (!mergeRes.alreadyMerged) { + await this.wrapFS( + isomorphic_git_default.checkout({ + ...this.getRepo(), + ref: branchInfo.current, + onProgress: (progress) => { + if (progressNotice !== void 0) { + progressNotice.noticeEl.innerText = this.getProgressText("Checkout", progress); + } + }, + remote: branchInfo.remote + }) + ); + } + progressNotice == null ? void 0 : progressNotice.hide(); + const upstreamCommit = await this.resolveRef("HEAD"); + const changedFiles = await this.getFileChangesCount( + localCommit, + upstreamCommit + ); + this.showNotice("Finished pull", false); + return changedFiles.map((file) => ({ + path: file.path, + working_dir: "P", + index: "P", + vault_path: this.getRelativeVaultPath(file.path) + })); + } catch (error) { + progressNotice == null ? void 0 : progressNotice.hide(); + if (error instanceof Errors.MergeConflictError) { + this.plugin.handleConflict( + error.data.filepaths.map( + (file) => this.getRelativeVaultPath(file) + ) + ); + } + this.plugin.displayError(error); + throw error; + } + } + async push() { + if (!await this.canPush()) { + return 0; + } + const progressNotice = this.showNotice("Initializing push"); + try { + this.plugin.setState(1 /* status */); + const status2 = await this.branchInfo(); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + const numChangedFiles = (await this.getFileChangesCount(currentBranch2, trackingBranch)).length; + this.plugin.setState(5 /* push */); + await this.wrapFS( + isomorphic_git_default.push({ + ...this.getRepo(), + onProgress: (progress) => { + if (progressNotice !== void 0) { + progressNotice.noticeEl.innerText = this.getProgressText("Pushing", progress); + } + } + }) + ); + progressNotice == null ? void 0 : progressNotice.hide(); + return numChangedFiles; + } catch (error) { + progressNotice == null ? void 0 : progressNotice.hide(); + this.plugin.displayError(error); + throw error; + } + } + async getUnpushedCommits() { + const status2 = await this.branchInfo(); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + if (trackingBranch == null || currentBranch2 == null) { + return 0; + } + const localCommit = await this.resolveRef(currentBranch2); + const upstreamCommit = await this.resolveRef(trackingBranch); + const changedFiles = await this.getFileChangesCount( + localCommit, + upstreamCommit + ); + return changedFiles.length; + } + async canPush() { + const status2 = await this.branchInfo(); + const trackingBranch = status2.tracking; + const currentBranch2 = status2.current; + const current = await this.resolveRef(currentBranch2); + const tracking = await this.resolveRef(trackingBranch); + return current != tracking; + } + async checkRequirements() { + const headExists = await this.plugin.app.vault.adapter.exists( + `${this.getRepo().dir}/.git/HEAD` + ); + return headExists ? "valid" : "missing-repo"; + } + async branchInfo() { + var _a2, _b; + try { + const current = await isomorphic_git_default.currentBranch(this.getRepo()) || ""; + const branches = await isomorphic_git_default.listBranches(this.getRepo()); + const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin"; + const trackingBranch = (_b = await this.getConfig(`branch.${current}.merge`)) == null ? void 0 : _b.split("refs/heads")[1]; + const tracking = trackingBranch ? remote + trackingBranch : void 0; + return { + current, + tracking, + branches, + remote + }; + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async getCurrentRemote() { + var _a2; + const current = await isomorphic_git_default.currentBranch(this.getRepo()) || ""; + const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin"; + return remote; + } + async checkout(branch2, remote) { + try { + return this.wrapFS( + isomorphic_git_default.checkout({ + ...this.getRepo(), + ref: branch2, + force: !!remote, + remote + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async createBranch(branch2) { + try { + await this.wrapFS( + isomorphic_git_default.branch({ ...this.getRepo(), ref: branch2, checkout: true }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async deleteBranch(branch2) { + try { + await this.wrapFS( + isomorphic_git_default.deleteBranch({ ...this.getRepo(), ref: branch2 }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async branchIsMerged(_) { + return true; + } + async init() { + try { + await this.wrapFS(isomorphic_git_default.init(this.getRepo())); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async clone(url, dir, depth) { + const progressNotice = this.showNotice("Initializing clone"); + try { + await this.wrapFS( + isomorphic_git_default.clone({ + ...this.getRepo(), + dir, + url, + depth, + onProgress: (progress) => { + if (progressNotice !== void 0) { + progressNotice.noticeEl.innerText = this.getProgressText("Cloning", progress); + } + } + }) + ); + progressNotice == null ? void 0 : progressNotice.hide(); + } catch (error) { + progressNotice == null ? void 0 : progressNotice.hide(); + this.plugin.displayError(error); + throw error; + } + } + async setConfig(path2, value) { + try { + return this.wrapFS( + isomorphic_git_default.setConfig({ + ...this.getRepo(), + path: path2, + value + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async getConfig(path2) { + try { + return this.wrapFS( + isomorphic_git_default.getConfig({ + ...this.getRepo(), + path: path2 + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async fetch(remote) { + const progressNotice = this.showNotice("Initializing fetch"); + try { + const args = { + ...this.getRepo(), + onProgress: (progress) => { + if (progressNotice !== void 0) { + progressNotice.noticeEl.innerText = this.getProgressText("Fetching", progress); + } + }, + remote: remote != null ? remote : await this.getCurrentRemote() + }; + await this.wrapFS(isomorphic_git_default.fetch(args)); + progressNotice == null ? void 0 : progressNotice.hide(); + } catch (error) { + this.plugin.displayError(error); + progressNotice == null ? void 0 : progressNotice.hide(); + throw error; + } + } + async setRemote(name, url) { + try { + await this.wrapFS( + isomorphic_git_default.addRemote({ + ...this.getRepo(), + remote: name, + url, + force: true + }) + ); + } catch (error) { + this.plugin.displayError(error); + throw error; + } + } + async getRemoteBranches(remote) { + let remoteBranches = []; + remoteBranches.push( + ...await this.wrapFS( + isomorphic_git_default.listBranches({ ...this.getRepo(), remote }) + ) + ); + remoteBranches.remove("HEAD"); + remoteBranches = remoteBranches.map((e) => `${remote}/${e}`); + return remoteBranches; + } + async getRemotes() { + return (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).map( + (remoteUrl) => remoteUrl.remote + ); + } + async removeRemote(remoteName) { + await this.wrapFS( + isomorphic_git_default.deleteRemote({ ...this.getRepo(), remote: remoteName }) + ); + } + async getRemoteUrl(remote) { + var _a2; + return (_a2 = (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).filter((item) => item.remote == remote)[0]) == null ? void 0 : _a2.url; + } + async log(_, __ = true, limit) { + const logs = await this.wrapFS( + isomorphic_git_default.log({ ...this.getRepo(), depth: limit }) + ); + return Promise.all( + logs.map(async (log2) => { + const completeMessage = log2.commit.message.split("\n\n"); + return { + message: completeMessage[0], + author: { + name: log2.commit.author.name, + email: log2.commit.author.email + }, + body: completeMessage.slice(1).join("\n\n"), + date: new Date( + log2.commit.committer.timestamp + ).toDateString(), + diff: { + changed: 0, + files: (await this.getFileChangesCount( + log2.commit.parent.first(), + log2.oid + )).map((item) => { + return { + path: item.path, + status: item.type, + vault_path: this.getRelativeVaultPath( + item.path + ), + hash: log2.oid, + binary: void 0 + }; + }) + }, + hash: log2.oid, + refs: [] + }; + }) + ); + } + updateBasePath(basePath) { + this.getRepo().dir = basePath; + } + async updateUpstreamBranch(remoteBranch) { + const [remote, branch2] = splitRemoteBranch(remoteBranch); + const branchInfo = await this.branchInfo(); + await this.setConfig( + `branch.${branchInfo.current}.merge`, + `refs/heads/${branch2}` + ); + await this.setConfig(`branch.${branch2}.remote`, remote); + } + updateGitPath(_) { + return; + } + async getFileChangesCount(commitHash1, commitHash2) { + return this.walkDifference({ + walkers: [ + isomorphic_git_default.TREE({ ref: commitHash1 }), + isomorphic_git_default.TREE({ ref: commitHash2 }) + ] + }); + } + async walkDifference({ + walkers, + dir: base + }) { + const res = await this.wrapFS( + isomorphic_git_default.walk({ + ...this.getRepo(), + trees: walkers, + map: async function(filepath, [A, B]) { + if (!worthWalking2(filepath, base)) { + return null; + } + if (await (A == null ? void 0 : A.type()) === "tree" || await (B == null ? void 0 : B.type()) === "tree") { + return; + } + const Aoid = await (A == null ? void 0 : A.oid()); + const Boid = await (B == null ? void 0 : B.oid()); + let type = "equal"; + if (Aoid !== Boid) { + type = "M"; + } + if (Aoid === void 0) { + type = "A"; + } + if (Boid === void 0) { + type = "D"; + } + if (Aoid === void 0 && Boid === void 0) { + console.log("Something weird happened:"); + console.log(A); + console.log(B); + } + if (type === "equal") { + return; + } + return { + path: filepath, + type + }; + } + }) + ); + return res; + } + async getStagedFiles(dir = ".") { + const res = await this.walkDifference({ + walkers: [isomorphic_git_default.TREE({ ref: "HEAD" }), isomorphic_git_default.STAGE()], + dir + }); + return res.map((file) => { + return { + vault_path: this.getRelativeVaultPath(file.path), + filepath: file.path + }; + }); + } + async getUnstagedFiles(base = ".") { + let notice; + const timeout = window.setTimeout(function() { + notice = new import_obsidian7.Notice( + "This takes longer: Getting status", + this.noticeLength + ); + }, 2e4); + try { + const repo = this.getRepo(); + const res = await this.wrapFS( + //Modified from `git.statusMatrix` + isomorphic_git_default.walk({ + ...repo, + trees: [isomorphic_git_default.WORKDIR(), isomorphic_git_default.STAGE()], + map: async function(filepath, [workdir, stage]) { + if (!stage && workdir) { + const isIgnored2 = await isomorphic_git_default.isIgnored({ + ...repo, + filepath + }); + if (isIgnored2) { + return null; + } + } + if (!worthWalking2(filepath, base)) { + return null; + } + const [workdirType, stageType] = await Promise.all([ + workdir && workdir.type(), + stage && stage.type() + ]); + const isBlob = [workdirType, stageType].includes( + "blob" + ); + if ((workdirType === "tree" || workdirType === "special") && !isBlob) + return; + if (stageType === "commit") + return null; + if ((stageType === "tree" || stageType === "special") && !isBlob) + return; + const stageOid = stageType === "blob" ? await stage.oid() : void 0; + let workdirOid; + if (workdirType === "blob" && stageType !== "blob") { + workdirOid = "42"; + } else if (workdirType === "blob") { + workdirOid = await workdir.oid(); + } + if (!workdirOid) { + return { + filepath, + deleted: true + }; + } + if (workdirOid !== stageOid) { + return { + filepath, + deleted: false + }; + } + return null; + } + }) + ); + window.clearTimeout(timeout); + notice == null ? void 0 : notice.hide(); + return res; + } catch (error) { + window.clearTimeout(timeout); + notice == null ? void 0 : notice.hide(); + this.plugin.displayError(error); + throw error; + } + } + async getDiffString(filePath, stagedChanges = false, hash2) { + const vaultPath = this.getRelativeVaultPath(filePath); + const map = async (file, [A]) => { + if (filePath == file) { + const oid = await A.oid(); + const contents = await isomorphic_git_default.readBlob({ + ...this.getRepo(), + oid + }); + return contents.blob; + } + }; + if (hash2) { + const commitContent = await readBlob({ + ...this.getRepo(), + filepath: filePath, + oid: hash2 + }).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => { + if (err instanceof isomorphic_git_default.Errors.NotFoundError) + return void 0; + throw err; + }); + const commit2 = await isomorphic_git_default.readCommit({ + ...this.getRepo(), + oid: hash2 + }); + const previousContent = await readBlob({ + ...this.getRepo(), + filepath: filePath, + oid: commit2.commit.parent.first() + }).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => { + if (err instanceof isomorphic_git_default.Errors.NotFoundError) + return void 0; + throw err; + }); + const diff3 = createPatch( + vaultPath, + previousContent != null ? previousContent : "", + commitContent != null ? commitContent : "" + ); + return diff3; + } + const stagedBlob = (await isomorphic_git_default.walk({ + ...this.getRepo(), + trees: [isomorphic_git_default.STAGE()], + map + })).first(); + const stagedContent = new TextDecoder().decode(stagedBlob); + if (stagedChanges) { + const headContent = await this.resolveRef("HEAD").then( + (oid) => readBlob({ + ...this.getRepo(), + filepath: filePath, + oid + }) + ).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => { + if (err instanceof isomorphic_git_default.Errors.NotFoundError) + return void 0; + throw err; + }); + const diff3 = createPatch( + vaultPath, + headContent != null ? headContent : "", + stagedContent + ); + return diff3; + } else { + let workdirContent; + if (await this.app.vault.adapter.exists(vaultPath)) { + workdirContent = await this.app.vault.adapter.read(vaultPath); + } else { + workdirContent = ""; + } + const diff3 = createPatch(vaultPath, stagedContent, workdirContent); + return diff3; + } + } + async getLastCommitTime() { + const repo = this.getRepo(); + const oid = await this.resolveRef("HEAD"); + const commit2 = await isomorphic_git_default.readCommit({ ...repo, oid }); + const date = commit2.commit.committer.timestamp; + return new Date(date * 1e3); + } + getFileStatusResult(row) { + const status2 = this.status_mapping[`${row[this.HEAD]}${row[this.WORKDIR]}${row[this.STAGE]}`]; + return { + index: status2[0] == "?" ? "U" : status2[0], + working_dir: status2[1] == "?" ? "U" : status2[1], + path: row[this.FILE], + vault_path: this.getRelativeVaultPath(row[this.FILE]) + }; + } + async checkAuthorInfo() { + const name = await this.getConfig("user.name"); + const email = await this.getConfig("user.email"); + if (!name || !email) { + throw "Git author information is not set. Please set it in the settings."; + } + } + showNotice(message, infinity = true) { + if (!this.plugin.settings.disablePopups) { + return new import_obsidian7.Notice( + message, + infinity ? this.noticeLength : void 0 + ); + } + } +}; +function fromValue2(value) { + let queue = [value]; + return { + next() { + return Promise.resolve({ + done: queue.length === 0, + value: queue.pop() + }); + }, + return() { + queue = []; + return {}; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +function getIterator2(iterable) { + if (iterable[Symbol.asyncIterator]) { + return iterable[Symbol.asyncIterator](); + } + if (iterable[Symbol.iterator]) { + return iterable[Symbol.iterator](); + } + if (iterable.next) { + return iterable; + } + return fromValue2(iterable); +} +async function forAwait2(iterable, cb) { + const iter = getIterator2(iterable); + while (true) { + const { value, done } = await iter.next(); + if (value) + await cb(value); + if (done) + break; + } + if (iter.return) + iter.return(); +} +async function collect2(iterable) { + let size = 0; + const buffers = []; + await forAwait2(iterable, (value) => { + buffers.push(value); + size += value.byteLength; + }); + const result = new Uint8Array(size); + let nextIndex = 0; + for (const buffer2 of buffers) { + result.set(buffer2, nextIndex); + nextIndex += buffer2.byteLength; + } + return result; +} + +// src/setting/settings.ts +var FORMAT_STRING_REFERENCE_URL = "https://momentjs.com/docs/#/parsing/string-format/"; +var LINE_AUTHOR_FEATURE_WIKI_LINK = "https://publish.obsidian.md/git-doc/Line+Authoring"; +var ObsidianGitSettingsTab = class extends import_obsidian8.PluginSettingTab { + constructor() { + super(...arguments); + this.lineAuthorColorSettings = /* @__PURE__ */ new Map(); + } + // narrow type from PluginSettingTab.plugin + get settings() { + return this.plugin.settings; + } + display() { + const { containerEl } = this; + const plugin = this.plugin; + const commitOrBackup = plugin.settings.differentIntervalCommitAndPush ? "commit" : "backup"; + const gitReady = plugin.gitReady; + containerEl.empty(); + containerEl.createEl("h2", { text: "Git Backup settings" }); + if (!gitReady) { + containerEl.createEl("p", { + text: "Git is not ready. When all settings are correct you can configure auto backup, etc." + }); + } + if (gitReady) { + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Automatic" }); + new import_obsidian8.Setting(containerEl).setName("Split automatic commit and push").setDesc("Enable to use separate timer for commit and push").addToggle( + (toggle) => toggle.setValue( + plugin.settings.differentIntervalCommitAndPush + ).onChange((value) => { + plugin.settings.differentIntervalCommitAndPush = value; + plugin.saveSettings(); + plugin.clearAutoBackup(); + plugin.clearAutoPush(); + if (plugin.settings.autoSaveInterval > 0) { + plugin.startAutoBackup( + plugin.settings.autoSaveInterval + ); + } + if (value && plugin.settings.autoPushInterval > 0) { + plugin.startAutoPush( + plugin.settings.autoPushInterval + ); + } + this.display(); + }) + ); + new import_obsidian8.Setting(containerEl).setName(`Vault ${commitOrBackup} interval (minutes)`).setDesc( + `${plugin.settings.differentIntervalCommitAndPush ? "Commit" : "Commit and push"} changes every X minutes. Set to 0 (default) to disable. (See below setting for further configuration!)` + ).addText( + (text2) => text2.setValue(String(plugin.settings.autoSaveInterval)).onChange((value) => { + if (!isNaN(Number(value))) { + plugin.settings.autoSaveInterval = Number(value); + plugin.saveSettings(); + if (plugin.settings.autoSaveInterval > 0) { + plugin.clearAutoBackup(); + plugin.startAutoBackup( + plugin.settings.autoSaveInterval + ); + new import_obsidian8.Notice( + `Automatic ${commitOrBackup} enabled! Every ${formatMinutes( + plugin.settings.autoSaveInterval + )}.` + ); + } else if (plugin.settings.autoSaveInterval <= 0) { + plugin.clearAutoBackup() && new import_obsidian8.Notice( + `Automatic ${commitOrBackup} disabled!` + ); + } + } else { + new import_obsidian8.Notice("Please specify a valid number."); + } + }) + ); + if (!plugin.settings.setLastSaveToLastCommit) + new import_obsidian8.Setting(containerEl).setName(`Auto Backup after stopping file edits`).setDesc( + `Requires the ${commitOrBackup} interval not to be 0. + If turned on, do auto ${commitOrBackup} every ${formatMinutes( + plugin.settings.autoSaveInterval + )} after stopping file edits. + This also prevents auto ${commitOrBackup} while editing a file. If turned off, it's independent from the last change.` + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.autoBackupAfterFileChange).onChange((value) => { + plugin.settings.autoBackupAfterFileChange = value; + this.display(); + plugin.saveSettings(); + plugin.clearAutoBackup(); + if (plugin.settings.autoSaveInterval > 0) { + plugin.startAutoBackup( + plugin.settings.autoSaveInterval + ); + } + }) + ); + if (!plugin.settings.autoBackupAfterFileChange) + new import_obsidian8.Setting(containerEl).setName(`Auto ${commitOrBackup} after latest commit`).setDesc( + `If turned on, set last auto ${commitOrBackup} time to latest commit` + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.setLastSaveToLastCommit).onChange(async (value) => { + plugin.settings.setLastSaveToLastCommit = value; + plugin.saveSettings(); + this.display(); + plugin.clearAutoBackup(); + await plugin.setUpAutoBackup(); + }) + ); + if (plugin.settings.differentIntervalCommitAndPush) { + new import_obsidian8.Setting(containerEl).setName(`Vault push interval (minutes)`).setDesc( + "Push changes every X minutes. Set to 0 (default) to disable." + ).addText( + (text2) => text2.setValue(String(plugin.settings.autoPushInterval)).onChange((value) => { + if (!isNaN(Number(value))) { + plugin.settings.autoPushInterval = Number(value); + plugin.saveSettings(); + if (plugin.settings.autoPushInterval > 0) { + plugin.clearAutoPush(); + plugin.startAutoPush( + plugin.settings.autoPushInterval + ); + new import_obsidian8.Notice( + `Automatic push enabled! Every ${formatMinutes( + plugin.settings.autoPushInterval + )}.` + ); + } else if (plugin.settings.autoPushInterval <= 0) { + plugin.clearAutoPush() && new import_obsidian8.Notice( + "Automatic push disabled!" + ); + } + } else { + new import_obsidian8.Notice( + "Please specify a valid number." + ); + } + }) + ); + } + new import_obsidian8.Setting(containerEl).setName("Auto pull interval (minutes)").setDesc( + "Pull changes every X minutes. Set to 0 (default) to disable." + ).addText( + (text2) => text2.setValue(String(plugin.settings.autoPullInterval)).onChange((value) => { + if (!isNaN(Number(value))) { + plugin.settings.autoPullInterval = Number(value); + plugin.saveSettings(); + if (plugin.settings.autoPullInterval > 0) { + plugin.clearAutoPull(); + plugin.startAutoPull( + plugin.settings.autoPullInterval + ); + new import_obsidian8.Notice( + `Automatic pull enabled! Every ${formatMinutes( + plugin.settings.autoPullInterval + )}.` + ); + } else if (plugin.settings.autoPullInterval <= 0) { + plugin.clearAutoPull() && new import_obsidian8.Notice("Automatic pull disabled!"); + } + } else { + new import_obsidian8.Notice("Please specify a valid number."); + } + }) + ); + new import_obsidian8.Setting(containerEl).setName("Specify custom commit message on auto backup").setDesc("You will get a pop up to specify your message").addToggle( + (toggle) => toggle.setValue(plugin.settings.customMessageOnAutoBackup).onChange((value) => { + plugin.settings.customMessageOnAutoBackup = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Commit message on auto backup/commit").setDesc( + "Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message)" + ).addTextArea( + (text2) => text2.setPlaceholder("vault backup: {{date}}").setValue(plugin.settings.autoCommitMessage).onChange((value) => { + plugin.settings.autoCommitMessage = value; + plugin.saveSettings(); + }) + ); + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Commit message" }); + new import_obsidian8.Setting(containerEl).setName("Commit message on manual backup/commit").setDesc( + "Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message)" + ).addTextArea( + (text2) => text2.setPlaceholder("vault backup: {{date}}").setValue( + plugin.settings.commitMessage ? plugin.settings.commitMessage : "" + ).onChange((value) => { + plugin.settings.commitMessage = value; + plugin.saveSettings(); + }) + ); + const datePlaceholderSetting = new import_obsidian8.Setting(containerEl).setName("{{date}} placeholder format").addText( + (text2) => text2.setPlaceholder(plugin.settings.commitDateFormat).setValue(plugin.settings.commitDateFormat).onChange(async (value) => { + plugin.settings.commitDateFormat = value; + await plugin.saveSettings(); + }) + ); + datePlaceholderSetting.descEl.innerHTML = ` + Specify custom date format. E.g. "${DATE_TIME_FORMAT_SECONDS}. See Moment.js for more formats.`; + new import_obsidian8.Setting(containerEl).setName("{{hostname}} placeholder replacement").setDesc("Specify custom hostname for every device.").addText( + (text2) => { + var _a2; + return text2.setValue((_a2 = plugin.localStorage.getHostname()) != null ? _a2 : "").onChange(async (value) => { + plugin.localStorage.setHostname(value); + }); + } + ); + new import_obsidian8.Setting(containerEl).setName("Preview commit message").addButton( + (button) => button.setButtonText("Preview").onClick(async () => { + const commitMessagePreview = await plugin.gitManager.formatCommitMessage( + plugin.settings.commitMessage + ); + new import_obsidian8.Notice(`${commitMessagePreview}`); + }) + ); + new import_obsidian8.Setting(containerEl).setName("List filenames affected by commit in the commit body").addToggle( + (toggle) => toggle.setValue(plugin.settings.listChangedFilesInMessageBody).onChange((value) => { + plugin.settings.listChangedFilesInMessageBody = value; + plugin.saveSettings(); + }) + ); + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Backup" }); + if (plugin.gitManager instanceof SimpleGit) + new import_obsidian8.Setting(containerEl).setName("Sync Method").setDesc( + "Selects the method used for handling new changes found in your remote git repository." + ).addDropdown((dropdown) => { + const options = { + merge: "Merge", + rebase: "Rebase", + reset: "Other sync service (Only updates the HEAD without touching the working directory)" + }; + dropdown.addOptions(options); + dropdown.setValue(plugin.settings.syncMethod); + dropdown.onChange(async (option) => { + plugin.settings.syncMethod = option; + plugin.saveSettings(); + }); + }); + new import_obsidian8.Setting(containerEl).setName("Pull updates on startup").setDesc("Automatically pull updates when Obsidian starts").addToggle( + (toggle) => toggle.setValue(plugin.settings.autoPullOnBoot).onChange((value) => { + plugin.settings.autoPullOnBoot = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Push on backup").setDesc("Disable to only commit changes").addToggle( + (toggle) => toggle.setValue(!plugin.settings.disablePush).onChange((value) => { + plugin.settings.disablePush = !value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Pull changes before push").setDesc("Commit -> pull -> push (Only if pushing is enabled)").addToggle( + (toggle) => toggle.setValue(plugin.settings.pullBeforePush).onChange((value) => { + plugin.settings.pullBeforePush = value; + plugin.saveSettings(); + }) + ); + if (plugin.gitManager instanceof SimpleGit) { + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Line author information" }); + this.addLineAuthorInfoSettings(); + } + } + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "History View" }); + new import_obsidian8.Setting(containerEl).setName("Show Author").setDesc("Show the author of the commit in the history view").addDropdown((dropdown) => { + const options = { + hide: "Hide", + full: "Full", + initials: "Initials" + }; + dropdown.addOptions(options); + dropdown.setValue(plugin.settings.authorInHistoryView); + dropdown.onChange(async (option) => { + plugin.settings.authorInHistoryView = option; + plugin.saveSettings(); + plugin.refresh(); + }); + }); + new import_obsidian8.Setting(containerEl).setName("Show Date").setDesc( + "Show the date of the commit in the history view. The {{date}} placeholder format is used to display the date." + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.dateInHistoryView).onChange((value) => { + plugin.settings.dateInHistoryView = value; + plugin.saveSettings(); + plugin.refresh(); + }) + ); + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Source Control View" }); + new import_obsidian8.Setting(containerEl).setName( + "Automatically refresh Source Control View on file changes" + ).setDesc( + "On slower machines this may cause lags. If so, just disable this option" + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.refreshSourceControl).onChange((value) => { + plugin.settings.refreshSourceControl = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Source Control View refresh interval").setDesc( + "Milliseconds to wait after file change before refreshing the Source Control View" + ).addText( + (toggle) => toggle.setValue( + plugin.settings.refreshSourceControlTimer.toString() + ).setPlaceholder("7000").onChange((value) => { + plugin.settings.refreshSourceControlTimer = Math.max( + parseInt(value), + 500 + ); + plugin.saveSettings(); + plugin.setRefreshDebouncer(); + }) + ); + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Miscellaneous" }); + new import_obsidian8.Setting(containerEl).setName("Disable notifications").setDesc( + "Disable notifications for git operations to minimize distraction (refer to status bar for updates). Errors are still shown as notifications even if you enable this setting" + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.disablePopups).onChange((value) => { + plugin.settings.disablePopups = value; + this.display(); + plugin.saveSettings(); + }) + ); + if (!plugin.settings.disablePopups) + new import_obsidian8.Setting(containerEl).setName("Hide notifications for no changes").setDesc( + "Don't show notifications when there are no changes to commit/push" + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.disablePopupsForNoChanges).onChange((value) => { + plugin.settings.disablePopupsForNoChanges = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Show status bar").setDesc( + "Obsidian must be restarted for the changes to take affect" + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.showStatusBar).onChange((value) => { + plugin.settings.showStatusBar = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Show stage/unstage button in file menu").addToggle( + (toggle) => toggle.setValue(plugin.settings.showFileMenu).onChange((value) => { + plugin.settings.showFileMenu = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Show branch status bar").setDesc( + "Obsidian must be restarted for the changes to take affect" + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.showBranchStatusBar).onChange((value) => { + plugin.settings.showBranchStatusBar = value; + plugin.saveSettings(); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Show the count of modified files in the status bar").addToggle( + (toggle) => toggle.setValue(plugin.settings.changedFilesInStatusBar).onChange((value) => { + plugin.settings.changedFilesInStatusBar = value; + plugin.saveSettings(); + }) + ); + containerEl.createEl("br"); + if (plugin.gitManager instanceof IsomorphicGit) { + containerEl.createEl("h3", { + text: "Authentication/Commit Author" + }); + } else { + containerEl.createEl("h3", { text: "Commit Author" }); + } + if (plugin.gitManager instanceof IsomorphicGit) + new import_obsidian8.Setting(containerEl).setName( + "Username on your git server. E.g. your username on GitHub" + ).addText((cb) => { + var _a2; + cb.setValue((_a2 = plugin.localStorage.getUsername()) != null ? _a2 : ""); + cb.onChange((value) => { + plugin.localStorage.setUsername(value); + }); + }); + if (plugin.gitManager instanceof IsomorphicGit) + new import_obsidian8.Setting(containerEl).setName("Password/Personal access token").setDesc( + "Type in your password. You won't be able to see it again." + ).addText((cb) => { + cb.inputEl.autocapitalize = "off"; + cb.inputEl.autocomplete = "off"; + cb.inputEl.spellcheck = false; + cb.onChange((value) => { + plugin.localStorage.setPassword(value); + }); + }); + if (plugin.gitReady) + new import_obsidian8.Setting(containerEl).setName("Author name for commit").addText(async (cb) => { + cb.setValue(await plugin.gitManager.getConfig("user.name")); + cb.onChange((value) => { + plugin.gitManager.setConfig( + "user.name", + value == "" ? void 0 : value + ); + }); + }); + if (plugin.gitReady) + new import_obsidian8.Setting(containerEl).setName("Author email for commit").addText(async (cb) => { + cb.setValue( + await plugin.gitManager.getConfig("user.email") + ); + cb.onChange((value) => { + plugin.gitManager.setConfig( + "user.email", + value == "" ? void 0 : value + ); + }); + }); + containerEl.createEl("br"); + containerEl.createEl("h3", { text: "Advanced" }); + if (plugin.gitManager instanceof SimpleGit) { + new import_obsidian8.Setting(containerEl).setName("Update submodules").setDesc( + '"Create backup" and "pull" takes care of submodules. Missing features: Conflicted files, count of pulled/pushed/committed files. Tracking branch needs to be set for each submodule' + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.updateSubmodules).onChange((value) => { + plugin.settings.updateSubmodules = value; + plugin.saveSettings(); + }) + ); + if (plugin.settings.updateSubmodules) { + new import_obsidian8.Setting(containerEl).setName("Submodule recurse checkout/switch").setDesc( + "Whenever a checkout happens on the root repository, recurse the checkout on the submodules (if the branches exist)." + ).addToggle( + (toggle) => toggle.setValue(plugin.settings.submoduleRecurseCheckout).onChange((value) => { + plugin.settings.submoduleRecurseCheckout = value; + plugin.saveSettings(); + }) + ); + } + } + if (plugin.gitManager instanceof SimpleGit) + new import_obsidian8.Setting(containerEl).setName("Custom Git binary path").addText((cb) => { + var _a2; + cb.setValue((_a2 = plugin.localStorage.getGitPath()) != null ? _a2 : ""); + cb.setPlaceholder("git"); + cb.onChange((value) => { + plugin.localStorage.setGitPath(value); + plugin.gitManager.updateGitPath(value || "git"); + }); + }); + if (plugin.gitManager instanceof SimpleGit) + new import_obsidian8.Setting(containerEl).setName("Additional environment variables").setDesc( + "Use each line for a new environment variable in the format KEY=VALUE" + ).addTextArea((cb) => { + cb.setPlaceholder("GIT_DIR=/path/to/git/dir"); + cb.setValue(plugin.localStorage.getEnvVars().join("\n")); + cb.onChange((value) => { + plugin.localStorage.setEnvVars(value.split("\n")); + }); + }); + if (plugin.gitManager instanceof SimpleGit) + new import_obsidian8.Setting(containerEl).setName("Additional PATH environment variable paths").setDesc("Use each line for one path").addTextArea((cb) => { + cb.setValue(plugin.localStorage.getPATHPaths().join("\n")); + cb.onChange((value) => { + plugin.localStorage.setPATHPaths(value.split("\n")); + }); + }); + if (plugin.gitManager instanceof SimpleGit) + new import_obsidian8.Setting(containerEl).setName("Reload with new environment variables").setDesc( + "Removing previously added environment variables will not take effect until Obsidian is restarted." + ).addButton((cb) => { + cb.setButtonText("Reload"); + cb.setCta(); + cb.onClick(() => { + plugin.gitManager.setGitInstance(); + }); + }); + new import_obsidian8.Setting(containerEl).setName("Custom base path (Git repository path)").setDesc( + ` + Sets the relative path to the vault from which the Git binary should be executed. + Mostly used to set the path to the Git repository, which is only required if the Git repository is below the vault root directory. Use "\\" instead of "/" on Windows. + ` + ).addText((cb) => { + cb.setValue(plugin.settings.basePath); + cb.setPlaceholder("directory/directory-with-git-repo"); + cb.onChange((value) => { + plugin.settings.basePath = value; + plugin.saveSettings(); + plugin.gitManager.updateBasePath(value || ""); + }); + }); + new import_obsidian8.Setting(containerEl).setName("Custom Git directory path (Instead of '.git')").setDesc( + `Requires restart of Obsidian to take effect. Use "\\" instead of "/" on Windows.` + ).addText((cb) => { + cb.setValue(plugin.settings.gitDir); + cb.setPlaceholder(".git"); + cb.onChange((value) => { + plugin.settings.gitDir = value; + plugin.saveSettings(); + }); + }); + new import_obsidian8.Setting(containerEl).setName("Disable on this device").setDesc( + "Disables the plugin on this device. This setting is not synced." + ).addToggle( + (toggle) => toggle.setValue(plugin.localStorage.getPluginDisabled()).onChange((value) => { + plugin.localStorage.setPluginDisabled(value); + if (value) { + plugin.unloadPlugin(); + } else { + plugin.loadPlugin(); + } + new import_obsidian8.Notice( + "Obsidian must be restarted for the changes to take affect" + ); + }) + ); + new import_obsidian8.Setting(containerEl).setName("Donate").setDesc( + "If you like this Plugin, consider donating to support continued development." + ).addButton((bt) => { + bt.buttonEl.outerHTML = "Buy Me a Coffee at ko-fi.com"; + }); + const info = containerEl.createDiv(); + info.setAttr("align", "center"); + info.setText( + "Debugging and logging:\nYou can always see the logs of this and every other plugin by opening the console with" + ); + const keys = containerEl.createDiv(); + keys.setAttr("align", "center"); + keys.addClass("obsidian-git-shortcuts"); + if (import_obsidian8.Platform.isMacOS === true) { + keys.createEl("kbd", { text: "CMD (\u2318) + OPTION (\u2325) + I" }); + } else { + keys.createEl("kbd", { text: "CTRL + SHIFT + I" }); + } + } + configureLineAuthorShowStatus(show) { + this.settings.lineAuthor.show = show; + this.plugin.saveSettings(); + if (show) + this.plugin.lineAuthoringFeature.activateFeature(); + else + this.plugin.lineAuthoringFeature.deactivateFeature(); + } + /** + * Persists the setting {@link key} with value {@link value} and + * refreshes the line author info views. + */ + lineAuthorSettingHandler(key2, value) { + this.settings.lineAuthor[key2] = value; + this.plugin.saveSettings(); + this.plugin.lineAuthoringFeature.refreshLineAuthorViews(); + } + /** + * Ensure, that certain last shown values are persisten in the settings. + * + * Necessary for the line author info gutter context menus. + */ + beforeSaveSettings() { + const laSettings = this.settings.lineAuthor; + if (laSettings.authorDisplay !== "hide") { + laSettings.lastShownAuthorDisplay = laSettings.authorDisplay; + } + if (laSettings.dateTimeFormatOptions !== "hide") { + laSettings.lastShownDateTimeFormatOptions = laSettings.dateTimeFormatOptions; + } + } + addLineAuthorInfoSettings() { + const baseLineAuthorInfoSetting = new import_obsidian8.Setting(this.containerEl).setName( + "Show commit authoring information next to each line" + ); + if (!this.plugin.lineAuthoringFeature.isAvailableOnCurrentPlatform()) { + baseLineAuthorInfoSetting.setDesc("Only available on desktop currently.").setDisabled(true); + } + baseLineAuthorInfoSetting.descEl.innerHTML = ` + Feature guide and quick examples
+ The commit hash, author name and authoring date can all be individually toggled.
Hide everything, to only show the age-colored sidebar.`; + baseLineAuthorInfoSetting.addToggle( + (toggle) => toggle.setValue(this.settings.lineAuthor.show).onChange((value) => { + this.configureLineAuthorShowStatus(value); + this.display(); + }) + ); + if (this.settings.lineAuthor.show) { + const trackMovement = new import_obsidian8.Setting(this.containerEl).setName("Follow movement and copies across files and commits").setDesc("").addDropdown((dropdown) => { + dropdown.addOptions({ + inactive: "Do not follow (default)", + "same-commit": "Follow within same commit", + "all-commits": "Follow within all commits (maybe slow)" + }); + dropdown.setValue(this.settings.lineAuthor.followMovement); + dropdown.onChange( + (value) => this.lineAuthorSettingHandler("followMovement", value) + ); + }); + trackMovement.descEl.innerHTML = ` + By default (deactivated), each line only shows the newest commit where it was changed. +
+ With same commit, cut-copy-paste-ing of text is followed within the same commit and the original commit of authoring will be shown. +
+ With all commits, cut-copy-paste-ing text inbetween multiple commits will be detected. +
+ It uses git-blame and + for matches (at least ${GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH} characters) within the same (or all) commit(s), the originating commit's information is shown.`; + new import_obsidian8.Setting(this.containerEl).setName("Show commit hash").addToggle((tgl) => { + tgl.setValue(this.settings.lineAuthor.showCommitHash); + tgl.onChange( + async (value) => this.lineAuthorSettingHandler("showCommitHash", value) + ); + }); + new import_obsidian8.Setting(this.containerEl).setName("Author name display").setDesc("If and how the author is displayed").addDropdown((dropdown) => { + const options = { + hide: "Hide", + initials: "Initials (default)", + "first name": "First name", + "last name": "Last name", + full: "Full name" + }; + dropdown.addOptions(options); + dropdown.setValue(this.settings.lineAuthor.authorDisplay); + dropdown.onChange( + async (value) => this.lineAuthorSettingHandler("authorDisplay", value) + ); + }); + new import_obsidian8.Setting(this.containerEl).setName("Authoring date display").setDesc( + "If and how the date and time of authoring the line is displayed" + ).addDropdown((dropdown) => { + const options = { + hide: "Hide", + date: "Date (default)", + datetime: "Date and time", + "natural language": "Natural language", + custom: "Custom" + }; + dropdown.addOptions(options); + dropdown.setValue( + this.settings.lineAuthor.dateTimeFormatOptions + ); + dropdown.onChange( + async (value) => { + this.lineAuthorSettingHandler( + "dateTimeFormatOptions", + value + ); + this.display(); + } + ); + }); + if (this.settings.lineAuthor.dateTimeFormatOptions === "custom") { + const dateTimeFormatCustomStringSetting = new import_obsidian8.Setting( + this.containerEl + ); + dateTimeFormatCustomStringSetting.setName("Custom authoring date format").addText((cb) => { + cb.setValue( + this.settings.lineAuthor.dateTimeFormatCustomString + ); + cb.setPlaceholder("YYYY-MM-DD HH:mm"); + cb.onChange((value) => { + this.lineAuthorSettingHandler( + "dateTimeFormatCustomString", + value + ); + dateTimeFormatCustomStringSetting.descEl.innerHTML = this.previewCustomDateTimeDescriptionHtml( + value + ); + }); + }); + dateTimeFormatCustomStringSetting.descEl.innerHTML = this.previewCustomDateTimeDescriptionHtml( + this.settings.lineAuthor.dateTimeFormatCustomString + ); + } + new import_obsidian8.Setting(this.containerEl).setName("Authoring date display timezone").addDropdown((dropdown) => { + const options = { + "viewer-local": "My local (default)", + "author-local": "Author's local", + utc0000: "UTC+0000/Z" + }; + dropdown.addOptions(options); + dropdown.setValue( + this.settings.lineAuthor.dateTimeTimezone + ); + dropdown.onChange( + async (value) => this.lineAuthorSettingHandler("dateTimeTimezone", value) + ); + }).descEl.innerHTML = ` + The time-zone in which the authoring date should be shown. + Either your local time-zone (default), + the author's time-zone during commit creation or + UTC\xB100:00. + `; + const oldestAgeSetting = new import_obsidian8.Setting(this.containerEl).setName( + "Oldest age in coloring" + ); + oldestAgeSetting.descEl.innerHTML = this.previewOldestAgeDescriptionHtml( + this.settings.lineAuthor.coloringMaxAge + )[0]; + oldestAgeSetting.addText((text2) => { + text2.setPlaceholder("1y"); + text2.setValue(this.settings.lineAuthor.coloringMaxAge); + text2.onChange((value) => { + const [preview, valid] = this.previewOldestAgeDescriptionHtml(value); + oldestAgeSetting.descEl.innerHTML = preview; + if (valid) { + this.lineAuthorSettingHandler("coloringMaxAge", value); + this.refreshColorSettingsName("oldest"); + } + }); + }); + this.createColorSetting("newest"); + this.createColorSetting("oldest"); + new import_obsidian8.Setting(this.containerEl).setName("Text color").addText((field) => { + field.setValue(this.settings.lineAuthor.textColorCss); + field.onChange((value) => { + this.lineAuthorSettingHandler("textColorCss", value); + }); + }).descEl.innerHTML = ` + The CSS color of the gutter text.
+ + It is higly recommended to use + + CSS variables + defined by themes + (e.g.
var(--text-muted)
or +
var(--text-on-accent)
, + because they automatically adapt to theme changes.
+ + See: + List of available CSS variables in Obsidian + + `; + new import_obsidian8.Setting(this.containerEl).setName("Ignore whitespace and newlines in changes").addToggle((tgl) => { + tgl.setValue(this.settings.lineAuthor.ignoreWhitespace); + tgl.onChange( + (value) => this.lineAuthorSettingHandler("ignoreWhitespace", value) + ); + }).descEl.innerHTML = ` + Whitespace and newlines are interpreted as + part of the document and in changes + by default (hence not ignored). + This makes the last line being shown as 'changed' + when a new subsequent line is added, + even if the previously last line's text is the same. +
+ If you don't care about purely-whitespace changes + (e.g. list nesting / quote indentation changes), + then activating this will provide more meaningful change detection. + `; + } + } + createColorSetting(which) { + const setting = new import_obsidian8.Setting(this.containerEl).setName("").addText((text2) => { + const color = pickColor(which, this.settings.lineAuthor); + const defaultColor = pickColor( + which, + DEFAULT_SETTINGS.lineAuthor + ); + text2.setPlaceholder(rgbToString(defaultColor)); + text2.setValue(rgbToString(color)); + text2.onChange((colorNew) => { + const rgb = convertToRgb(colorNew); + if (rgb !== void 0) { + const key2 = which === "newest" ? "colorNew" : "colorOld"; + this.lineAuthorSettingHandler(key2, rgb); + } + this.refreshColorSettingsDesc(which, rgb); + }); + }); + this.lineAuthorColorSettings.set(which, setting); + this.refreshColorSettingsName(which); + this.refreshColorSettingsDesc( + which, + pickColor(which, this.settings.lineAuthor) + ); + } + refreshColorSettingsName(which) { + const settingsDom = this.lineAuthorColorSettings.get(which); + if (settingsDom) { + const whichDescriber = which === "oldest" ? `oldest (${this.settings.lineAuthor.coloringMaxAge} or older)` : "newest"; + settingsDom.nameEl.innerText = `Color for ${whichDescriber} commits`; + } + } + refreshColorSettingsDesc(which, rgb) { + const settingsDom = this.lineAuthorColorSettings.get(which); + if (settingsDom) { + settingsDom.descEl.innerHTML = this.colorSettingPreviewDescHtml( + which, + this.settings.lineAuthor, + rgb !== void 0 + ); + } + } + colorSettingPreviewDescHtml(which, laSettings, colorIsValid) { + const rgbStr = colorIsValid ? previewColor(which, laSettings) : `rgba(127,127,127,0.3)`; + const today = import_obsidian8.moment.unix(import_obsidian8.moment.now() / 1e3).format("YYYY-MM-DD"); + const text2 = colorIsValid ? `abcdef Author Name ${today}` : "invalid color"; + const preview = `
${text2}
`; + return `Supports 'rgb(r,g,b)', 'hsl(h,s,l)', hex (#) and + named colors (e.g. 'black', 'purple'). Color preview: ${preview}`; + } + previewCustomDateTimeDescriptionHtml(dateTimeFormatCustomString) { + const formattedDateTime = (0, import_obsidian8.moment)().format(dateTimeFormatCustomString); + return `
Format string to display the authoring date.
Currently: ${formattedDateTime}`; + } + previewOldestAgeDescriptionHtml(coloringMaxAge) { + const duration = parseColoringMaxAgeDuration(coloringMaxAge); + const durationString = duration !== void 0 ? `${duration.asDays()} days` : "invalid!"; + return [ + `The oldest age in the line author coloring. Everything older will have the same color. +
Smallest valid age is "1d". Currently: ${durationString}`, + duration + ]; + } +}; +function pickColor(which, las) { + return which === "oldest" ? las.colorOld : las.colorNew; +} +function parseColoringMaxAgeDuration(durationString) { + const duration = import_obsidian8.moment.duration("P" + durationString.toUpperCase()); + return duration.isValid() && duration.asDays() && duration.asDays() >= 1 ? duration : void 0; +} + +// src/lineAuthor/model.ts +function lineAuthoringId(head, objHash, path2) { + if (head === void 0 || objHash === void 0 || path2 === void 0) { + return void 0; + } + return `head${head}-obj${objHash}-path${path2}`; +} +var LineAuthoringContainerType = import_state.Annotation.define(); +function newComputationResultAsTransaction(key2, la, state) { + return state.update({ + annotations: LineAuthoringContainerType.of({ + key: key2, + la, + lineOffsetsFromUnsavedChanges: /* @__PURE__ */ new Map() + }) + }); +} +function getLineAuthorAnnotation(tr) { + return tr.annotation(LineAuthoringContainerType); +} +var lineAuthorState = import_state.StateField.define({ + create: (_state) => void 0, + /** + * The state can be updated from either an annotated transaction containing + * the newest line authoring (for the saved document) - or from + * unsaved changes of the document as the user is actively typing in the editor. + * + * In the first case, we take the new line authoring and discard anything we had remembered + * from unsaved changes. In the second case, we use the unsaved changes in {@link enrichUnsavedChanges} to pre-compute information to immediately update the + * line author gutter without needing to wait until the document is saved and the + * line authoring is properly computed. + */ + update: (previous, transaction) => { + var _a2; + return (_a2 = getLineAuthorAnnotation(transaction)) != null ? _a2 : enrichUnsavedChanges(transaction, previous); + }, + // compare cache keys. + // equality rate is >= 95% :) + // hence avoids recomputation of views + compare: (l, r) => (l == null ? void 0 : l.key) === (r == null ? void 0 : r.key) +}); +function laStateDigest(laState) { + var _a2; + const digest = import_js_sha256.sha256.create(); + if (!laState) + return digest; + const { la, key: key2, lineOffsetsFromUnsavedChanges } = laState; + digest.update(la === "untracked" ? "t" : "f"); + digest.update(key2); + for (const [k, v] of (_a2 = lineOffsetsFromUnsavedChanges.entries()) != null ? _a2 : []) + digest.update([k, v]); + return digest; +} +var latestSettings = { + get: void 0, + save: void 0 +}; +function provideSettingsAccess(settingsGetter, settingsSetter) { + latestSettings.get = settingsGetter; + latestSettings.save = settingsSetter; +} +function maxAgeInDaysFromSettings(settings) { + var _a2, _b; + return (_b = (_a2 = parseColoringMaxAgeDuration(settings.coloringMaxAge)) == null ? void 0 : _a2.asDays()) != null ? _b : parseColoringMaxAgeDuration( + DEFAULT_SETTINGS.lineAuthor.coloringMaxAge + ).asDays(); +} +function enrichUnsavedChanges(tr, prev) { + if (!prev) + return void 0; + if (!tr.changes.empty) { + tr.changes.iterChanges((fromA, toA, fromB, toB) => { + var _a2; + const oldDoc = tr.startState.doc; + const { newDoc } = tr; + const beforeFrom = oldDoc.lineAt(fromA).number; + const beforeTo = oldDoc.lineAt(toA).number; + const afterFrom = newDoc.lineAt(fromB).number; + const afterTo = newDoc.lineAt(toB).number; + const beforeLen = beforeTo - beforeFrom + 1; + const afterLen = afterTo - afterFrom + 1; + for (let afterI = afterFrom; afterI <= afterTo; afterI++) { + let offset = (_a2 = prev.lineOffsetsFromUnsavedChanges.get(afterI)) != null ? _a2 : 0; + const isLastLine = afterTo === afterI; + const changeInNumberOfLines = afterLen - beforeLen; + if (isLastLine) + offset += changeInNumberOfLines; + prev.lineOffsetsFromUnsavedChanges.set(afterI, offset); + } + }); + } + return prev; +} + +// src/lineAuthor/control.ts +var LineAuthoringSubscriber = class { + // remember path to detect and adapt to renames + constructor(state) { + this.state = state; + this.subscribeMe(); + } + async notifyLineAuthoring(id, la) { + if (this.view === void 0) { + console.warn( + `Git: View is not defined for editor cache key. Unforeseen situation. id: ${id}` + ); + return; + } + const state = this.view.state; + const transaction = newComputationResultAsTransaction(id, la, state); + this.view.dispatch(transaction); + } + updateToNewState(state) { + const filepathChanged = this.lastSeenPath && this.filepath != this.lastSeenPath; + this.state = state; + if (filepathChanged) { + this.unsubscribeMe(this.lastSeenPath); + this.subscribeMe(); + } + return this; + } + removeIfStale() { + if (this.view.destroyed) { + this.unsubscribeMe(this.lastSeenPath); + } + } + subscribeMe() { + if (this.filepath === void 0) + return; + eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers( + this.filepath, + (subs) => subs.add(this) + ); + this.lastSeenPath = this.filepath; + } + unsubscribeMe(oldFilepath) { + eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers( + oldFilepath, + (subs) => subs.delete(this) + ); + } + get filepath() { + var _a2, _b; + return (_b = (_a2 = this.state.field(import_obsidian9.editorViewField)) == null ? void 0 : _a2.file) == null ? void 0 : _b.path; + } + get view() { + return this.state.field(import_obsidian9.editorEditorField); + } +}; +var subscribeNewEditor = import_state2.StateField.define({ + create: (state) => new LineAuthoringSubscriber(state), + update: (v, transaction) => v.updateToNewState(transaction.state), + compare: (a, b) => a === b +}); + +// src/lineAuthor/view/cache.ts +init_polyfill_buffer(); +function clearViewCache() { + longestRenderedGutter = void 0; + renderedAgeInDaysForAdaptiveInitialColoring = []; + ageIdx = 0; + gutterInstances.clear(); + gutterMarkersRangeSet.clear(); + attachedGutterElements.clear(); +} +var longestRenderedGutter = void 0; +var getLongestRenderedGutter = () => longestRenderedGutter; +function conditionallyUpdateLongestRenderedGutter(gutter2, text2) { + var _a2; + const length = text2.length; + if (length < ((_a2 = longestRenderedGutter == null ? void 0 : longestRenderedGutter.length) != null ? _a2 : 0)) + return; + longestRenderedGutter = { gutter: gutter2, length, text: text2 }; + const settings = latestSettings.get(); + if (length !== settings.gutterSpacingFallbackLength) { + settings.gutterSpacingFallbackLength = length; + latestSettings.save(settings); + } +} +var renderedAgeInDaysForAdaptiveInitialColoring = []; +var ADAPTIVE_INITIAL_COLORING_AGE_CACHE_SIZE = 15; +var ageIdx = 0; +function recordRenderedAgeInDays(age) { + renderedAgeInDaysForAdaptiveInitialColoring[ageIdx] = age; + ageIdx = (ageIdx + 1) % ADAPTIVE_INITIAL_COLORING_AGE_CACHE_SIZE; +} +function computeAdaptiveInitialColoringAgeInDays() { + return median(renderedAgeInDaysForAdaptiveInitialColoring); +} +var gutterInstances = /* @__PURE__ */ new Map(); +var gutterMarkersRangeSet = /* @__PURE__ */ new Map(); +var attachedGutterElements = /* @__PURE__ */ new Set(); + +// src/lineAuthor/view/view.ts +init_polyfill_buffer(); +var import_state3 = require("@codemirror/state"); +var import_view2 = require("@codemirror/view"); + +// src/lineAuthor/view/gutter/gutter.ts +init_polyfill_buffer(); +var import_view = require("@codemirror/view"); +var import_js_sha2562 = __toESM(require_sha256()); +var import_obsidian10 = require("obsidian"); + +// src/lineAuthor/view/contextMenu.ts +init_polyfill_buffer(); + +// src/lineAuthor/view/gutter/gutterElementSearch.ts +init_polyfill_buffer(); +var mouseXY = { x: -10, y: -10 }; +function prepareGutterSearchForContextMenuHandling() { + if (mouseXY.x === -10) { + window.addEventListener("mousedown", (e) => { + mouseXY.x = e.clientX; + mouseXY.y = e.clientY; + }); + } +} +function findGutterElementUnderMouse() { + for (const elt of attachedGutterElements) { + if (contains(elt, mouseXY)) + return elt; + } +} +function contains(elt, pt) { + const { x, y, width, height } = elt.getBoundingClientRect(); + return x <= pt.x && pt.x <= x + width && y <= pt.y && pt.y <= y + height; +} + +// src/pluginGlobalRef.ts +init_polyfill_buffer(); +var pluginRef = {}; + +// src/lineAuthor/view/contextMenu.ts +var COMMIT_ATTR = "data-commit"; +function handleContextMenu(menu, editor, _mdv) { + if (editor.hasFocus()) + return; + const gutterElement = findGutterElementUnderMouse(); + if (!gutterElement) + return; + const info = getCommitInfo(gutterElement); + if (!info) + return; + if (!info.isZeroCommit && !info.isWaitingGutter) { + addCopyHashMenuItem(info, menu); + } + addConfigurableLineAuthorSettings("showCommitHash", menu); + addConfigurableLineAuthorSettings("authorDisplay", menu); + addConfigurableLineAuthorSettings("dateTimeFormatOptions", menu); +} +function addCopyHashMenuItem(commit2, menu) { + menu.addItem( + (item) => item.setTitle("Copy commit hash").setIcon("copy").setSection("obs-git-line-author-copy").onClick((_e) => navigator.clipboard.writeText(commit2.hash)) + ); +} +function addConfigurableLineAuthorSettings(key2, menu) { + var _a2, _b; + let title; + let actionNewValue; + const settings = pluginRef.plugin.settings.lineAuthor; + const currentValue = settings[key2]; + const currentlyShown = typeof currentValue === "boolean" ? currentValue : currentValue !== "hide"; + const defaultValue = DEFAULT_SETTINGS.lineAuthor[key2]; + if (key2 === "showCommitHash") { + title = "Show commit hash"; + actionNewValue = !currentValue; + } else if (key2 === "authorDisplay") { + const showOption = (_a2 = settings.lastShownAuthorDisplay) != null ? _a2 : defaultValue; + title = "Show author " + (currentlyShown ? currentValue : showOption); + actionNewValue = currentlyShown ? "hide" : showOption; + } else if (key2 === "dateTimeFormatOptions") { + const showOption = (_b = settings.lastShownDateTimeFormatOptions) != null ? _b : defaultValue; + title = "Show " + (currentlyShown ? currentValue : showOption); + title += !title.contains("date") ? " date" : ""; + actionNewValue = currentlyShown ? "hide" : showOption; + } else { + impossibleBranch(key2); + } + menu.addItem( + (item) => item.setTitle(title).setSection("obs-git-line-author-configure").setChecked(currentlyShown).onClick( + (_e) => { + var _a3, _b2; + return (_b2 = (_a3 = pluginRef.plugin) == null ? void 0 : _a3.settingsTab) == null ? void 0 : _b2.lineAuthorSettingHandler( + key2, + actionNewValue + ); + } + ) + ); +} +function enrichCommitInfoForContextMenu(commit2, isWaitingGutter, elt) { + elt.setAttr( + COMMIT_ATTR, + JSON.stringify({ + hash: commit2.hash, + isZeroCommit: commit2.isZeroCommit, + isWaitingGutter + }) + ); +} +function getCommitInfo(elt) { + const commitInfoStr = elt.getAttr(COMMIT_ATTR); + return commitInfoStr ? JSON.parse(commitInfoStr) : void 0; +} + +// src/lineAuthor/view/gutter/coloring.ts +init_polyfill_buffer(); +function previewColor(which, settings) { + return which === "oldest" ? coloringBasedOnCommitAge(0, false, settings).color : coloringBasedOnCommitAge(void 0, true, settings).color; +} +function coloringBasedOnCommitAge(commitAuthorEpochSeonds, isZeroCommit, settings) { + const maxAgeInDays = maxAgeInDaysFromSettings(settings); + const epochSecondsNow = Date.now() / 1e3; + const authoringEpochSeconds = commitAuthorEpochSeonds != null ? commitAuthorEpochSeonds : 0; + const secondsSinceCommit = isZeroCommit ? 0 : epochSecondsNow - authoringEpochSeconds; + const daysSinceCommit = secondsSinceCommit / 60 / 60 / 24; + const x = Math.pow( + Math.clamp(daysSinceCommit / maxAgeInDays, 0, 1), + 1 / 2.3 + ); + const dark = isDarkMode(); + const color0 = settings.colorNew; + const color1 = settings.colorOld; + const scaling = dark ? 0.4 : 1; + const r = lin(color0.r, color1.r, x) * scaling; + const g = lin(color0.g, color1.g, x) * scaling; + const b = lin(color0.b, color1.b, x) * scaling; + const a = dark ? 0.75 : 0.25; + return { color: `rgba(${r},${g},${b},${a})`, daysSinceCommit }; +} +function lin(z0, z1, x) { + return z0 + (z1 - z0) * x; +} +function isDarkMode() { + const obsidian = window == null ? void 0 : window.app; + return (obsidian == null ? void 0 : obsidian.getTheme()) === "obsidian"; +} +function setTextColorCssBasedOnSetting(settings) { + document.body.style.setProperty( + "--obs-git-gutter-text", + settings.textColorCss + ); +} + +// src/lineAuthor/view/gutter/commitChoice.ts +init_polyfill_buffer(); +function chooseNewestCommit(lineAuthoring, startLine, endLine) { + let newest = void 0; + for (let line = startLine; line <= endLine; line++) { + const currentHash = lineAuthoring.hashPerLine[line]; + const currentCommit = lineAuthoring.commits.get(currentHash); + if (!newest || currentCommit.isZeroCommit || isNewerThan(currentCommit, newest)) { + newest = currentCommit; + } + } + return newest; +} +function isNewerThan(left, right) { + var _a2, _b, _c, _d; + const l = (_b = (_a2 = left.author) == null ? void 0 : _a2.epochSeconds) != null ? _b : 0; + const r = (_d = (_c = right.author) == null ? void 0 : _c.epochSeconds) != null ? _d : 0; + return l > r; +} + +// src/lineAuthor/view/gutter/gutter.ts +var VALUE_NOT_FOUND_FALLBACK = "-"; +var NEW_CHANGE_CHARACTER = "+"; +var NEW_CHANGE_NUMBER_OF_CHARACTERS = 3; +var DIFFERING_AUTHOR_COMMITTER_MARKER = "*"; +var NON_WHITESPACE_REGEXP = /\S/g; +var UNINTRUSIVE_CHARACTER_FOR_WAITING_RENDERING = "%"; +var TextGutter = class extends import_view.GutterMarker { + constructor(text2) { + super(); + this.text = text2; + } + eq(other) { + return this.text === (other == null ? void 0 : other.text); + } + toDOM() { + return document.createTextNode(this.text); + } + destroy(dom) { + if (!document.body.contains(dom)) + dom.remove(); + } +}; +var LineAuthoringGutter = class extends import_view.GutterMarker { + /** + * **This should only be called {@link lineAuthoringGutterMarker}!** + * + * We want to avoid creating the same instance multiple times for improved performance. + */ + constructor(lineAuthoring, startLine, endLine, key2, settings, options) { + super(); + this.lineAuthoring = lineAuthoring; + this.startLine = startLine; + this.endLine = endLine; + this.key = key2; + this.settings = settings; + this.options = options; + this.point = false; + this.elementClass = "obs-git-blame-gutter"; + } + // Equality used by CodeMirror for optimisations + eq(other) { + return this.key === (other == null ? void 0 : other.key) && this.startLine === (other == null ? void 0 : other.startLine) && this.endLine === (other == null ? void 0 : other.endLine) && (this == null ? void 0 : this.options) === (other == null ? void 0 : other.options); + } + /** + * Renders to a Html node. + * + * It choses the newest commit within the line-range, + * renders it, makes adjustments for fake-commits and finally warps + * it into HTML. + * + * The DOM is actually precomputed with {@link computeDom}, + * which provides a finaliser to run before the DOM is handed over to CodeMirror. + * This is done, because this method is called frequently. It is called, + * whenever a gutter gets into the viewport and needs to be rendered. + * + * The age in days is recorded via {@link recordRenderedAgeInDays} to enable adaptive coloring. + */ + toDOM() { + var _a2; + this.precomputedDomProvider = (_a2 = this.precomputedDomProvider) != null ? _a2 : this.computeDom(); + return this.precomputedDomProvider(); + } + destroy(dom) { + if (!document.body.contains(dom)) { + dom.remove(); + attachedGutterElements.delete(dom); + } + } + /** + * Prepares the DOM for this gutter. + */ + computeDom() { + const commit2 = chooseNewestCommit( + this.lineAuthoring, + this.startLine, + this.endLine + ); + let toBeRenderedText = commit2.isZeroCommit ? "" : this.renderNonZeroCommit(commit2); + const isTrueCommit = !commit2.isZeroCommit && this.options !== "waiting-for-result"; + if (isTrueCommit) { + conditionallyUpdateLongestRenderedGutter(this, toBeRenderedText); + } else { + toBeRenderedText = this.adaptTextForFakeCommit( + commit2, + toBeRenderedText, + this.options + ); + } + const domProvider = this.createHtmlNode( + commit2, + toBeRenderedText, + this.options === "waiting-for-result" + ); + return domProvider; + } + createHtmlNode(commit2, text2, isWaitingGutter) { + var _a2; + const templateElt = window.createDiv(); + templateElt.innerText = text2; + const { color, daysSinceCommit } = coloringBasedOnCommitAge( + (_a2 = commit2 == null ? void 0 : commit2.author) == null ? void 0 : _a2.epochSeconds, + commit2 == null ? void 0 : commit2.isZeroCommit, + this.settings + ); + templateElt.style.backgroundColor = color; + enrichCommitInfoForContextMenu(commit2, isWaitingGutter, templateElt); + function prepareForDomAttachment() { + const elt = templateElt.cloneNode(true); + attachedGutterElements.add(elt); + if (!isWaitingGutter) + recordRenderedAgeInDays(daysSinceCommit); + return elt; + } + return prepareForDomAttachment; + } + renderNonZeroCommit(commit2) { + const optionalShortHash = this.settings.showCommitHash ? this.renderHash(commit2) : ""; + const optionalAuthorName = this.settings.authorDisplay === "hide" ? "" : `${this.renderAuthorName( + commit2, + this.settings.authorDisplay + )}`; + const optionalAuthoringDate = this.settings.dateTimeFormatOptions === "hide" ? "" : `${this.renderAuthoringDate( + commit2, + this.settings.dateTimeFormatOptions, + this.settings.dateTimeFormatCustomString, + this.settings.dateTimeTimezone + )}`; + const parts = [ + optionalShortHash, + optionalAuthorName, + optionalAuthoringDate + ]; + return parts.filter((x) => x.length >= 1).join(" "); + } + renderHash(nonZeroCommit) { + return nonZeroCommit.hash.substring(0, 6); + } + renderAuthorName(nonZeroCommit, authorDisplay) { + var _a2, _b, _c, _d; + const name = (_b = (_a2 = nonZeroCommit == null ? void 0 : nonZeroCommit.author) == null ? void 0 : _a2.name) != null ? _b : ""; + const words = name.split(" ").filter((word) => word.length >= 1); + let rendered; + switch (authorDisplay) { + case "initials": + rendered = words.map((word) => word[0].toUpperCase()).join(""); + break; + case "first name": + rendered = (_c = words.first()) != null ? _c : VALUE_NOT_FOUND_FALLBACK; + break; + case "last name": + rendered = (_d = words.last()) != null ? _d : VALUE_NOT_FOUND_FALLBACK; + break; + case "full": + rendered = name; + break; + default: + return impossibleBranch(authorDisplay); + } + if (!strictDeepEqual(nonZeroCommit == null ? void 0 : nonZeroCommit.author, nonZeroCommit == null ? void 0 : nonZeroCommit.committer)) { + rendered = rendered + DIFFERING_AUTHOR_COMMITTER_MARKER; + } + return rendered; + } + renderAuthoringDate(nonZeroCommit, dateTimeFormatOptions, dateTimeFormatCustomString, dateTimeTimezone) { + var _a2; + const FALLBACK_COMMIT_DATE = "?"; + if (((_a2 = nonZeroCommit == null ? void 0 : nonZeroCommit.author) == null ? void 0 : _a2.epochSeconds) === void 0) + return FALLBACK_COMMIT_DATE; + let dateTimeFormatting; + switch (dateTimeFormatOptions) { + case "date": + dateTimeFormatting = DATE_FORMAT; + break; + case "datetime": + dateTimeFormatting = DATE_TIME_FORMAT_MINUTES; + break; + case "custom": + dateTimeFormatting = dateTimeFormatCustomString; + break; + case "natural language": + dateTimeFormatting = (time) => { + const diff3 = time.diff((0, import_obsidian10.moment)()); + const addFluentSuffix = true; + return import_obsidian10.moment.duration(diff3).humanize(addFluentSuffix); + }; + break; + default: + return impossibleBranch(dateTimeFormatOptions); + } + let authoringDate = import_obsidian10.moment.unix( + nonZeroCommit.author.epochSeconds + ); + switch (dateTimeTimezone) { + case "viewer-local": + break; + case "author-local": + authoringDate = authoringDate.utcOffset( + nonZeroCommit.author.tz + ); + dateTimeFormatting += " Z"; + break; + case "utc0000": + authoringDate = authoringDate.utc(); + dateTimeFormatting += "[Z]"; + break; + default: + return impossibleBranch(dateTimeTimezone); + } + if (typeof dateTimeFormatting === "string") { + return authoringDate.format(dateTimeFormatting); + } else { + return dateTimeFormatting(authoringDate); + } + } + adaptTextForFakeCommit(commit2, toBeRenderedText, options) { + var _a2, _b, _c, _d; + const original = (_b = (_a2 = getLongestRenderedGutter()) == null ? void 0 : _a2.text) != null ? _b : toBeRenderedText; + const fillCharacter = options !== "waiting-for-result" && commit2.isZeroCommit ? NEW_CHANGE_CHARACTER : UNINTRUSIVE_CHARACTER_FOR_WAITING_RENDERING; + toBeRenderedText = original.replace( + NON_WHITESPACE_REGEXP, + fillCharacter + ); + const desiredTextLength = (_d = (_c = latestSettings.get()) == null ? void 0 : _c.gutterSpacingFallbackLength) != null ? _d : toBeRenderedText.length; + toBeRenderedText = resizeToLength( + toBeRenderedText, + desiredTextLength, + fillCharacter + ); + if (options !== "waiting-for-result" && commit2.isZeroCommit) { + const numberOfLastCharactersToKeep = Math.min( + desiredTextLength, + NEW_CHANGE_NUMBER_OF_CHARACTERS + ); + toBeRenderedText = prefixOfLengthAsWhitespace( + toBeRenderedText, + desiredTextLength - numberOfLastCharactersToKeep + ); + } + return toBeRenderedText; + } +}; +function lineAuthoringGutterMarker(la, startLine, endLine, key2, settings, options) { + const digest = import_js_sha2562.sha256.create(); + digest.update(Object.values(settings).join(",")); + digest.update(`s${startLine}-e${endLine}-k${key2}-o${options}`); + const cacheKey = digest.hex(); + const cached = gutterInstances.get(cacheKey); + if (cached) + return cached; + const result = new LineAuthoringGutter( + la, + startLine, + endLine, + key2, + settings, + options + ); + gutterInstances.set(cacheKey, result); + return result; +} + +// src/lineAuthor/view/gutter/initial.ts +init_polyfill_buffer(); +var import_obsidian11 = require("obsidian"); +function initialSpacingGutter() { + var _a2, _b; + const length = (_b = (_a2 = latestSettings.get()) == null ? void 0 : _a2.gutterSpacingFallbackLength) != null ? _b : DEFAULT_SETTINGS.lineAuthor.gutterSpacingFallbackLength; + return new TextGutter(Array(length).fill("-").join("")); +} +function initialLineAuthoringGutter(settings) { + const { lineAuthoring, ageForInitialRender } = adaptiveInitialColoredWaitingLineAuthoring(settings); + return lineAuthoringGutterMarker( + lineAuthoring, + 1, + 1, + "initialGutter" + ageForInitialRender, + // use a age coloring based cache key + settings, + "waiting-for-result" + ); +} +function adaptiveInitialColoredWaitingLineAuthoring(settings) { + var _a2; + const ageForInitialRender = (_a2 = computeAdaptiveInitialColoringAgeInDays()) != null ? _a2 : maxAgeInDaysFromSettings(settings) * 0.25; + const slightlyOlderAgeForInitialRender = (0, import_obsidian11.moment)().add( + -ageForInitialRender, + "days" + ); + const dummyAuthor = { + name: "", + epochSeconds: momentToEpochSeconds(slightlyOlderAgeForInitialRender), + tz: "+0000" + }; + const dummyCommit = { + hash: "waiting-for-result", + author: dummyAuthor, + committer: dummyAuthor, + isZeroCommit: false + }; + return { + lineAuthoring: { + hashPerLine: [void 0, "waiting-for-result"], + commits: /* @__PURE__ */ new Map([["waiting-for-result", dummyCommit]]) + }, + ageForInitialRender + }; +} + +// src/lineAuthor/view/gutter/untrackedFile.ts +init_polyfill_buffer(); +function newUntrackedFileGutter(key2, settings) { + const dummyLineAuthoring = { + hashPerLine: [void 0, "000000"], + commits: /* @__PURE__ */ new Map([["000000", zeroCommit]]) + }; + return lineAuthoringGutterMarker(dummyLineAuthoring, 1, 1, key2, settings); +} + +// src/lineAuthor/view/view.ts +var UNDISPLAYED = new TextGutter(""); +var lineAuthorGutter = (0, import_view2.gutter)({ + class: "line-author-gutter-container", + markers(view) { + const lineAuthoring = view.state.field(lineAuthorState, false); + return lineAuthoringGutterMarkersRangeSet(view, lineAuthoring); + }, + lineMarkerChange(update2) { + const newLineAuthoringId = laStateDigest( + update2.state.field(lineAuthorState) + ); + const oldLineAuthoringId = laStateDigest( + update2.startState.field(lineAuthorState) + ); + return oldLineAuthoringId !== newLineAuthoringId; + }, + renderEmptyElements: true, + initialSpacer: (view) => { + temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(view); + return initialSpacingGutter(); + }, + updateSpacer: (_sp, update2) => { + var _a2, _b; + temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(update2.view); + return (_b = (_a2 = getLongestRenderedGutter()) == null ? void 0 : _a2.gutter) != null ? _b : initialSpacingGutter(); + } +}); +function lineAuthoringGutterMarkersRangeSet(view, optLA) { + const digest = laStateDigest(optLA); + const doc = view.state.doc; + const lineBlockEndPos = /* @__PURE__ */ new Map(); + for (let line = 1; line <= doc.lines; line++) { + const from = doc.line(line).from; + const to = view.lineBlockAt(from).to; + lineBlockEndPos.set(line, [from, to]); + digest.update([from, to, 0]); + } + const laSettings = latestSettings.get(); + digest.update("s" + Object.values(latestSettings).join(",")); + const cacheKey = digest.hex(); + const cached = gutterMarkersRangeSet.get(cacheKey); + if (cached) + return cached; + const { result, allowCache } = computeLineAuthoringGutterMarkersRangeSet( + doc, + lineBlockEndPos, + laSettings, + optLA + ); + if (allowCache) + gutterMarkersRangeSet.set(cacheKey, result); + return result; +} +function computeLineAuthoringGutterMarkersRangeSet(doc, blocksPerLine, settings, optLA) { + let allowCache = true; + const docLastLine = doc.lines; + const ranges = []; + function add2(from, to, gutter2) { + return ranges.push(gutter2.range(from, to)); + } + const lineFrom = computeLineMappingForUnsavedChanges(docLastLine, optLA); + const emptyDoc = doc.length === 0; + const lastLineIsEmpty = doc.iterLines(docLastLine, docLastLine + 1).next().value === ""; + for (let startLine = 1; startLine <= docLastLine; startLine++) { + const [from, to] = blocksPerLine.get(startLine); + const endLine = doc.lineAt(to).number; + if (emptyDoc) { + add2(from, to, UNDISPLAYED); + continue; + } + if (startLine === docLastLine && lastLineIsEmpty) { + add2(from, to, UNDISPLAYED); + continue; + } + if (optLA === void 0) { + add2(from, to, initialLineAuthoringGutter(settings)); + allowCache = false; + continue; + } + const { key: key2, la } = optLA; + if (la === "untracked") { + add2(from, to, newUntrackedFileGutter(la, settings)); + continue; + } + const lastAuthorLine = la.hashPerLine.length - 1; + const laStartLine = lineFrom[startLine]; + const laEndLine = lineFrom[endLine]; + if (laEndLine && laEndLine > lastAuthorLine) { + add2(from, to, UNDISPLAYED); + } + if (laStartLine !== void 0 && between(1, laStartLine, lastAuthorLine) && laEndLine !== void 0 && between(1, laEndLine, lastAuthorLine)) { + add2( + from, + to, + lineAuthoringGutterMarker( + la, + laStartLine, + laEndLine, + key2, + settings + ) + ); + continue; + } + if (lastAuthorLine < 1) { + add2(from, to, initialLineAuthoringGutter(settings)); + allowCache = false; + continue; + } + const start = Math.clamp(laStartLine != null ? laStartLine : startLine, 1, lastAuthorLine); + const end = Math.clamp(laEndLine != null ? laEndLine : endLine, 1, lastAuthorLine); + add2( + from, + to, + lineAuthoringGutterMarker( + la, + start, + end, + key2 + "computing", + settings, + "waiting-for-result" + ) + ); + } + return { result: import_state3.RangeSet.of( + ranges, + /* sort = */ + true + ), allowCache }; +} +function computeLineMappingForUnsavedChanges(docLastLine, optLA) { + if (!(optLA == null ? void 0 : optLA.lineOffsetsFromUnsavedChanges)) { + return Array.from(new Array(docLastLine + 1), (ln) => ln); + } + const lineFrom = [void 0]; + let cumulativeLineOffset = 0; + for (let ln = 1; ln <= docLastLine; ln++) { + const unsavedChanges = optLA.lineOffsetsFromUnsavedChanges.get(ln); + cumulativeLineOffset += unsavedChanges != null ? unsavedChanges : 0; + lineFrom[ln] = unsavedChanges === void 0 ? ln - cumulativeLineOffset : void 0; + } + return lineFrom; +} +function temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(view) { + const guttersContainers = view.dom.querySelectorAll( + ".cm-gutters" + ); + guttersContainers.forEach((cont) => { + if (!(cont == null ? void 0 : cont.style)) + return; + if (!cont.style.marginLeft) { + cont.style.marginLeft = "unset"; + } + }); +} + +// src/lineAuthor/lineAuthorProvider.ts +var LineAuthorProvider = class { + constructor(plugin) { + this.plugin = plugin; + /** + * Saves all computed line authoring results. + * + * See {@link LineAuthoringId} + */ + this.lineAuthorings = /* @__PURE__ */ new Map(); + } + async trackChanged(file) { + this.trackChangedHelper(file).catch((reason) => { + console.warn("Git: Error in trackChanged." + reason); + return Promise.reject(reason); + }); + } + async trackChangedHelper(file) { + if (!file) + return; + if (file.path === void 0) { + console.warn( + "Git: Attempted to track change of undefined filepath. Unforeseen situation." + ); + return; + } + this.computeLineAuthorInfo(file.path); + } + destroy() { + this.lineAuthorings.clear(); + eventsPerFilePathSingleton.clear(); + clearViewCache(); + } + async computeLineAuthorInfo(filepath) { + const gitManager = this.plugin.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager; + const headRevision = await gitManager.submoduleAwareHeadRevisonInContainingDirectory( + filepath + ); + const fileHash = await gitManager.hashObject(filepath); + const key2 = lineAuthoringId(headRevision, fileHash, filepath); + if (key2 === void 0) { + return; + } + if (this.lineAuthorings.has(key2)) { + } else { + const gitAuthorResult = await gitManager.blame( + filepath, + this.plugin.settings.lineAuthor.followMovement, + this.plugin.settings.lineAuthor.ignoreWhitespace + ); + this.lineAuthorings.set(key2, gitAuthorResult); + } + this.notifyComputationResultToSubscribers(filepath, key2); + } + notifyComputationResultToSubscribers(filepath, key2) { + eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers( + filepath, + async (subs) => subs.forEach( + (sub) => sub.notifyLineAuthoring(key2, this.lineAuthorings.get(key2)) + ) + ); + } +}; +var enabledLineAuthorInfoExtensions = import_state4.Prec.high([ + subscribeNewEditor, + lineAuthorState, + lineAuthorGutter +]); + +// src/lineAuthor/lineAuthorIntegration.ts +var LineAuthoringFeature = class { + constructor(plg) { + this.plg = plg; + this.codeMirrorExtensions = []; + this.handleWorkspaceLeaf = (leaf) => { + const obsView = leaf == null ? void 0 : leaf.view; + const file = obsView == null ? void 0 : obsView.file; + if (!this.lineAuthorInfoProvider) { + console.warn( + "Git: undefined lineAuthorInfoProvider. Unexpected situation." + ); + return; + } + if (file === void 0 || (obsView == null ? void 0 : obsView.allowNoFile) === true) + return; + this.lineAuthorInfoProvider.trackChanged(file); + }; + } + // ========================= INIT and DE-INIT ========================== + onLoadPlugin() { + this.plg.registerEditorExtension(this.codeMirrorExtensions); + provideSettingsAccess( + () => this.plg.settings.lineAuthor, + (laSettings) => { + this.plg.settings.lineAuthor = laSettings; + this.plg.saveSettings(); + } + ); + } + conditionallyActivateBySettings() { + if (this.plg.settings.lineAuthor.show) { + this.activateFeature(); + } + } + activateFeature() { + try { + if (!this.isAvailableOnCurrentPlatform().available) + return; + setTextColorCssBasedOnSetting(this.plg.settings.lineAuthor); + this.lineAuthorInfoProvider = new LineAuthorProvider(this.plg); + this.createEventHandlers(); + this.activateCodeMirrorExtensions(); + console.log(this.plg.manifest.name + ": Enabled line authoring."); + } catch (e) { + console.warn("Git: Error while loading line authoring feature.", e); + this.deactivateFeature(); + } + } + /** + * Deactivates the feature. This function is very defensive, as it is also + * called to cleanup, if a critical error in the line authoring has occurred. + */ + deactivateFeature() { + var _a2; + this.destroyEventHandlers(); + this.deactivateCodeMirrorExtensions(); + (_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.destroy(); + this.lineAuthorInfoProvider = void 0; + console.log(this.plg.manifest.name + ": Disabled line authoring."); + } + isAvailableOnCurrentPlatform() { + return { + available: this.plg.useSimpleGit && import_obsidian12.Platform.isDesktopApp, + gitManager: this.plg.gitManager instanceof SimpleGit ? this.plg.gitManager : void 0 + }; + } + // ========================= REFRESH ========================== + refreshLineAuthorViews() { + if (this.plg.settings.lineAuthor.show) { + this.deactivateFeature(); + this.activateFeature(); + } + } + // ========================= CODEMIRROR EXTENSIONS ========================== + activateCodeMirrorExtensions() { + this.codeMirrorExtensions.push(enabledLineAuthorInfoExtensions); + this.plg.app.workspace.updateOptions(); + this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf); + } + deactivateCodeMirrorExtensions() { + for (const ext of this.codeMirrorExtensions) { + this.codeMirrorExtensions.remove(ext); + } + this.plg.app.workspace.updateOptions(); + } + // ========================= HANDLERS ========================== + createEventHandlers() { + this.gutterContextMenuEvent = this.createGutterContextMenuHandler(); + this.fileOpenEvent = this.createFileOpenEvent(); + this.workspaceLeafChangeEvent = this.createWorkspaceLeafChangeEvent(); + this.fileModificationEvent = this.createVaultFileModificationHandler(); + this.refreshOnCssChangeEvent = this.createCssRefreshHandler(); + this.fileRenameEvent = this.createFileRenameEvent(); + prepareGutterSearchForContextMenuHandling(); + this.plg.registerEvent(this.gutterContextMenuEvent); + this.plg.registerEvent(this.refreshOnCssChangeEvent); + this.plg.registerEvent(this.fileOpenEvent); + this.plg.registerEvent(this.workspaceLeafChangeEvent); + this.plg.registerEvent(this.fileModificationEvent); + this.plg.registerEvent(this.fileRenameEvent); + } + destroyEventHandlers() { + this.plg.app.workspace.offref(this.refreshOnCssChangeEvent); + this.plg.app.workspace.offref(this.fileOpenEvent); + this.plg.app.workspace.offref(this.workspaceLeafChangeEvent); + this.plg.app.workspace.offref(this.refreshOnCssChangeEvent); + this.plg.app.vault.offref(this.fileRenameEvent); + this.plg.app.workspace.offref(this.gutterContextMenuEvent); + } + createFileOpenEvent() { + return this.plg.app.workspace.on( + "file-open", + (file) => { + var _a2; + return (_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(file); + } + ); + } + createWorkspaceLeafChangeEvent() { + return this.plg.app.workspace.on( + "active-leaf-change", + this.handleWorkspaceLeaf + ); + } + createFileRenameEvent() { + return this.plg.app.vault.on( + "rename", + (file, _old) => { + var _a2; + return file instanceof import_obsidian12.TFile && ((_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(file)); + } + ); + } + createVaultFileModificationHandler() { + return this.plg.app.vault.on( + "modify", + (anyPath) => { + var _a2; + return anyPath instanceof import_obsidian12.TFile && ((_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(anyPath)); + } + ); + } + createCssRefreshHandler() { + return this.plg.app.workspace.on( + "css-change", + () => this.refreshLineAuthorViews() + ); + } + createGutterContextMenuHandler() { + return this.plg.app.workspace.on("editor-menu", handleContextMenu); + } +}; + +// src/promiseQueue.ts +init_polyfill_buffer(); +var PromiseQueue = class { + constructor() { + this.tasks = []; + } + addTask(task) { + this.tasks.push(task); + if (this.tasks.length === 1) { + this.handleTask(); + } + } + async handleTask() { + if (this.tasks.length > 0) { + this.tasks[0]().finally(() => { + this.tasks.shift(); + this.handleTask(); + }); + } + } +}; + +// src/statusBar.ts +init_polyfill_buffer(); +var import_obsidian13 = require("obsidian"); +var StatusBar = class { + constructor(statusBarEl, plugin) { + this.statusBarEl = statusBarEl; + this.plugin = plugin; + this.messages = []; + this.base = "obsidian-git-statusbar-"; + this.statusBarEl.setAttribute("data-tooltip-position", "top"); + addEventListener("git-refresh", this.refreshCommitTimestamp.bind(this)); + } + displayMessage(message, timeout) { + this.messages.push({ + message: `Git: ${message.slice(0, 100)}`, + timeout + }); + this.display(); + } + display() { + if (this.messages.length > 0 && !this.currentMessage) { + this.currentMessage = this.messages.shift(); + this.statusBarEl.addClass(this.base + "message"); + this.statusBarEl.ariaLabel = ""; + this.statusBarEl.setText(this.currentMessage.message); + this.lastMessageTimestamp = Date.now(); + } else if (this.currentMessage) { + const messageAge = Date.now() - this.lastMessageTimestamp; + if (messageAge >= this.currentMessage.timeout) { + this.currentMessage = null; + this.lastMessageTimestamp = null; + } + } else { + this.displayState(); + } + } + displayState() { + if (this.statusBarEl.getText().length > 3 || !this.statusBarEl.hasChildNodes()) { + this.statusBarEl.empty(); + this.iconEl = this.statusBarEl.createDiv(); + this.textEl = this.statusBarEl.createDiv(); + this.textEl.style.float = "right"; + this.textEl.style.marginLeft = "5px"; + this.iconEl.style.float = "left"; + } + switch (this.plugin.state) { + case 0 /* idle */: + this.displayFromNow(); + break; + case 1 /* status */: + this.statusBarEl.ariaLabel = "Checking repository status..."; + (0, import_obsidian13.setIcon)(this.iconEl, "refresh-cw"); + this.statusBarEl.addClass(this.base + "status"); + break; + case 3 /* add */: + this.statusBarEl.ariaLabel = "Adding files..."; + (0, import_obsidian13.setIcon)(this.iconEl, "refresh-w"); + this.statusBarEl.addClass(this.base + "add"); + break; + case 4 /* commit */: + this.statusBarEl.ariaLabel = "Committing changes..."; + (0, import_obsidian13.setIcon)(this.iconEl, "git-commit"); + this.statusBarEl.addClass(this.base + "commit"); + break; + case 5 /* push */: + this.statusBarEl.ariaLabel = "Pushing changes..."; + (0, import_obsidian13.setIcon)(this.iconEl, "upload"); + this.statusBarEl.addClass(this.base + "push"); + break; + case 2 /* pull */: + this.statusBarEl.ariaLabel = "Pulling changes..."; + (0, import_obsidian13.setIcon)(this.iconEl, "download"); + this.statusBarEl.addClass(this.base + "pull"); + break; + case 6 /* conflicted */: + this.statusBarEl.ariaLabel = "You have conflict files..."; + (0, import_obsidian13.setIcon)(this.iconEl, "alert-circle"); + this.statusBarEl.addClass(this.base + "conflict"); + break; + default: + this.statusBarEl.ariaLabel = "Failed on initialization!"; + (0, import_obsidian13.setIcon)(this.iconEl, "alert-triangle"); + this.statusBarEl.addClass(this.base + "failed-init"); + break; + } + } + displayFromNow() { + var _a2; + const timestamp = this.lastCommitTimestamp; + if (timestamp) { + const moment6 = window.moment; + const fromNow = moment6(timestamp).fromNow(); + this.statusBarEl.ariaLabel = `${this.plugin.offlineMode ? "Offline: " : ""}Last Commit: ${fromNow}`; + if ((_a2 = this.unPushedCommits) != null ? _a2 : 0 > 0) { + this.statusBarEl.ariaLabel += ` +(${this.unPushedCommits} unpushed commits)`; + } + } else { + this.statusBarEl.ariaLabel = this.plugin.offlineMode ? "Git is offline" : "Git is ready"; + } + if (this.plugin.offlineMode) { + (0, import_obsidian13.setIcon)(this.iconEl, "globe"); + } else { + (0, import_obsidian13.setIcon)(this.iconEl, "check"); + } + if (this.plugin.settings.changedFilesInStatusBar && this.plugin.cachedStatus) { + this.textEl.setText( + this.plugin.cachedStatus.changed.length.toString() + ); + } + this.statusBarEl.addClass(this.base + "idle"); + } + async refreshCommitTimestamp() { + this.lastCommitTimestamp = await this.plugin.gitManager.getLastCommitTime(); + this.unPushedCommits = await this.plugin.gitManager.getUnpushedCommits(); + } +}; + +// src/ui/modals/changedFilesModal.ts +init_polyfill_buffer(); +var import_obsidian14 = require("obsidian"); +var ChangedFilesModal = class extends import_obsidian14.FuzzySuggestModal { + constructor(plugin, changedFiles) { + super(plugin.app); + this.plugin = plugin; + this.changedFiles = changedFiles; + this.setPlaceholder( + "Not supported files will be opened by default app!" + ); + } + getItems() { + return this.changedFiles; + } + getItemText(item) { + if (item.index == "U" && item.working_dir == "U") { + return `Untracked | ${item.vault_path}`; + } + let working_dir = ""; + let index2 = ""; + if (item.working_dir != " ") + working_dir = `Working Dir: ${item.working_dir} `; + if (item.index != " ") + index2 = `Index: ${item.index}`; + return `${working_dir}${index2} | ${item.vault_path}`; + } + onChooseItem(item, _) { + if (this.plugin.app.metadataCache.getFirstLinkpathDest( + item.vault_path, + "" + ) == null) { + this.app.openWithDefaultApp(item.vault_path); + } else { + this.plugin.app.workspace.openLinkText(item.vault_path, "/"); + } + } +}; + +// src/ui/modals/customMessageModal.ts +init_polyfill_buffer(); +var import_obsidian15 = require("obsidian"); +var CustomMessageModal = class extends import_obsidian15.SuggestModal { + constructor(plugin, fromAutoBackup) { + super(plugin.app); + this.fromAutoBackup = fromAutoBackup; + this.resolve = null; + this.plugin = plugin; + this.setPlaceholder( + "Type your message and select optional the version with the added date." + ); + } + open() { + super.open(); + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + onClose() { + if (this.resolve) + this.resolve(void 0); + } + selectSuggestion(value, evt) { + if (this.resolve) + this.resolve(value); + super.selectSuggestion(value, evt); + } + getSuggestions(query) { + const date = window.moment().format(this.plugin.settings.commitDateFormat); + if (query == "") + query = "..."; + return [query, `${date}: ${query}`, `${query}: ${date}`]; + } + renderSuggestion(value, el) { + el.innerText = value; + } + onChooseSuggestion(item, _) { + } +}; + +// src/openInGitHub.ts +init_polyfill_buffer(); +var import_obsidian16 = require("obsidian"); +async function openLineInGitHub(editor, file, manager) { + const data = await getData(manager); + if (data.result === "failure") { + new import_obsidian16.Notice(data.reason); + return; + } + const { isGitHub, branch: branch2, repo, user } = data; + if (isGitHub) { + const path2 = manager.getRelativeRepoPath(file.path); + const from = editor.getCursor("from").line + 1; + const to = editor.getCursor("to").line + 1; + if (from === to) { + window.open( + `https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}` + ); + } else { + window.open( + `https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}-L${to}` + ); + } + } else { + new import_obsidian16.Notice("It seems like you are not using GitHub"); + } +} +async function openHistoryInGitHub(file, manager) { + const data = await getData(manager); + if (data.result === "failure") { + new import_obsidian16.Notice(data.reason); + return; + } + const { isGitHub, branch: branch2, repo, user } = data; + const path2 = manager.getRelativeRepoPath(file.path); + if (isGitHub) { + window.open( + `https://github.com/${user}/${repo}/commits/${branch2}/${path2}` + ); + } else { + new import_obsidian16.Notice("It seems like you are not using GitHub"); + } +} +async function getData(manager) { + const branchInfo = await manager.branchInfo(); + const remoteBranch = branchInfo.tracking; + const branch2 = branchInfo.current; + if (remoteBranch == null) { + return { + result: "failure", + reason: "Remote branch is not configured" + }; + } + if (branch2 == null) { + return { + result: "failure", + reason: "Failed to get current branch name" + }; + } + const remote = remoteBranch.substring(0, remoteBranch.indexOf("/")); + const remoteUrl = await manager.getConfig( + `remote.${remote}.url` + ); + const [isGitHub, httpsUser, httpsRepo, sshUser, sshRepo] = remoteUrl.match( + /(?:^https:\/\/github\.com\/(.*)\/(.*)\.git$)|(?:^[a-zA-Z]+@github\.com:(.*)\/(.*)\.git$)/ + ); + return { + result: "success", + isGitHub: !!isGitHub, + repo: httpsRepo || sshRepo, + user: httpsUser || sshUser, + branch: branch2 + }; +} + +// src/setting/localStorageSettings.ts +init_polyfill_buffer(); +var LocalStorageSettings = class { + constructor(plugin) { + this.plugin = plugin; + this.prefix = this.plugin.manifest.id + ":"; + } + migrate() { + const keys = [ + "password", + "hostname", + "conflict", + "lastAutoPull", + "lastAutoBackup", + "lastAutoPush", + "gitPath", + "pluginDisabled" + ]; + for (const key2 of keys) { + const old = localStorage.getItem(this.prefix + key2); + if (app.loadLocalStorage(this.prefix + key2) == null && old != null) { + if (old != null) { + app.saveLocalStorage(this.prefix + key2, old); + localStorage.removeItem(this.prefix + key2); + } + } + } + } + getPassword() { + return app.loadLocalStorage(this.prefix + "password"); + } + setPassword(value) { + return app.saveLocalStorage(this.prefix + "password", value); + } + getUsername() { + return app.loadLocalStorage(this.prefix + "username"); + } + setUsername(value) { + return app.saveLocalStorage(this.prefix + "username", value); + } + getHostname() { + return app.loadLocalStorage(this.prefix + "hostname"); + } + setHostname(value) { + return app.saveLocalStorage(this.prefix + "hostname", value); + } + getConflict() { + return app.loadLocalStorage(this.prefix + "conflict") == "true"; + } + setConflict(value) { + return app.saveLocalStorage(this.prefix + "conflict", `${value}`); + } + getLastAutoPull() { + return app.loadLocalStorage(this.prefix + "lastAutoPull"); + } + setLastAutoPull(value) { + return app.saveLocalStorage(this.prefix + "lastAutoPull", value); + } + getLastAutoBackup() { + return app.loadLocalStorage(this.prefix + "lastAutoBackup"); + } + setLastAutoBackup(value) { + return app.saveLocalStorage(this.prefix + "lastAutoBackup", value); + } + getLastAutoPush() { + return app.loadLocalStorage(this.prefix + "lastAutoPush"); + } + setLastAutoPush(value) { + return app.saveLocalStorage(this.prefix + "lastAutoPush", value); + } + getGitPath() { + return app.loadLocalStorage(this.prefix + "gitPath"); + } + setGitPath(value) { + return app.saveLocalStorage(this.prefix + "gitPath", value); + } + getPATHPaths() { + var _a2, _b; + return (_b = (_a2 = app.loadLocalStorage(this.prefix + "PATHPaths")) == null ? void 0 : _a2.split(":")) != null ? _b : []; + } + setPATHPaths(value) { + return app.saveLocalStorage(this.prefix + "PATHPaths", value.join(":")); + } + getEnvVars() { + var _a2; + return JSON.parse( + (_a2 = app.loadLocalStorage(this.prefix + "envVars")) != null ? _a2 : "[]" + ); + } + setEnvVars(value) { + return app.saveLocalStorage( + this.prefix + "envVars", + JSON.stringify(value) + ); + } + getPluginDisabled() { + return app.loadLocalStorage(this.prefix + "pluginDisabled") == "true"; + } + setPluginDisabled(value) { + return app.saveLocalStorage(this.prefix + "pluginDisabled", `${value}`); + } +}; + +// src/ui/diff/diffView.ts +init_polyfill_buffer(); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/diff2html.js +init_polyfill_buffer(); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/diff-parser.js +init_polyfill_buffer(); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/types.js +init_polyfill_buffer(); +var LineType; +(function(LineType2) { + LineType2["INSERT"] = "insert"; + LineType2["DELETE"] = "delete"; + LineType2["CONTEXT"] = "context"; +})(LineType || (LineType = {})); +var OutputFormatType = { + LINE_BY_LINE: "line-by-line", + SIDE_BY_SIDE: "side-by-side" +}; +var LineMatchingType = { + LINES: "lines", + WORDS: "words", + NONE: "none" +}; +var DiffStyleType = { + WORD: "word", + CHAR: "char" +}; +var ColorSchemeType; +(function(ColorSchemeType2) { + ColorSchemeType2["AUTO"] = "auto"; + ColorSchemeType2["DARK"] = "dark"; + ColorSchemeType2["LIGHT"] = "light"; +})(ColorSchemeType || (ColorSchemeType = {})); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/utils.js +init_polyfill_buffer(); +var specials = [ + "-", + "[", + "]", + "/", + "{", + "}", + "(", + ")", + "*", + "+", + "?", + ".", + "\\", + "^", + "$", + "|" +]; +var regex = RegExp("[" + specials.join("\\") + "]", "g"); +function escapeForRegExp(str) { + return str.replace(regex, "\\$&"); +} +function unifyPath(path2) { + return path2 ? path2.replace(/\\/g, "/") : path2; +} +function hashCode(text2) { + let i, chr, len; + let hash2 = 0; + for (i = 0, len = text2.length; i < len; i++) { + chr = text2.charCodeAt(i); + hash2 = (hash2 << 5) - hash2 + chr; + hash2 |= 0; + } + return hash2; +} + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/diff-parser.js +function getExtension(filename, language) { + const filenameParts = filename.split("."); + return filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : language; +} +function startsWithAny(str, prefixes) { + return prefixes.reduce((startsWith, prefix) => startsWith || str.startsWith(prefix), false); +} +var baseDiffFilenamePrefixes = ["a/", "b/", "i/", "w/", "c/", "o/"]; +function getFilename(line, linePrefix, extraPrefix) { + const prefixes = extraPrefix !== void 0 ? [...baseDiffFilenamePrefixes, extraPrefix] : baseDiffFilenamePrefixes; + const FilenameRegExp = linePrefix ? new RegExp(`^${escapeForRegExp(linePrefix)} "?(.+?)"?$`) : new RegExp('^"?(.+?)"?$'); + const [, filename = ""] = FilenameRegExp.exec(line) || []; + const matchingPrefix = prefixes.find((p) => filename.indexOf(p) === 0); + const fnameWithoutPrefix = matchingPrefix ? filename.slice(matchingPrefix.length) : filename; + return fnameWithoutPrefix.replace(/\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4}.*$/, ""); +} +function getSrcFilename(line, srcPrefix) { + return getFilename(line, "---", srcPrefix); +} +function getDstFilename(line, dstPrefix) { + return getFilename(line, "+++", dstPrefix); +} +function parse(diffInput, config = {}) { + const files = []; + let currentFile = null; + let currentBlock = null; + let oldLine = null; + let oldLine2 = null; + let newLine = null; + let possibleOldName = null; + let possibleNewName = null; + const oldFileNameHeader = "--- "; + const newFileNameHeader = "+++ "; + const hunkHeaderPrefix = "@@"; + const oldMode = /^old mode (\d{6})/; + const newMode = /^new mode (\d{6})/; + const deletedFileMode = /^deleted file mode (\d{6})/; + const newFileMode = /^new file mode (\d{6})/; + const copyFrom = /^copy from "?(.+)"?/; + const copyTo = /^copy to "?(.+)"?/; + const renameFrom = /^rename from "?(.+)"?/; + const renameTo = /^rename to "?(.+)"?/; + const similarityIndex = /^similarity index (\d+)%/; + const dissimilarityIndex = /^dissimilarity index (\d+)%/; + const index2 = /^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/; + const binaryFiles = /^Binary files (.*) and (.*) differ/; + const binaryDiff = /^GIT binary patch/; + const combinedIndex = /^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/; + const combinedMode = /^mode (\d{6}),(\d{6})\.\.(\d{6})/; + const combinedNewFile = /^new file mode (\d{6})/; + const combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/; + const diffLines2 = diffInput.replace(/\\ No newline at end of file/g, "").replace(/\r\n?/g, "\n").split("\n"); + function saveBlock() { + if (currentBlock !== null && currentFile !== null) { + currentFile.blocks.push(currentBlock); + currentBlock = null; + } + } + function saveFile() { + if (currentFile !== null) { + if (!currentFile.oldName && possibleOldName !== null) { + currentFile.oldName = possibleOldName; + } + if (!currentFile.newName && possibleNewName !== null) { + currentFile.newName = possibleNewName; + } + if (currentFile.newName) { + files.push(currentFile); + currentFile = null; + } + } + possibleOldName = null; + possibleNewName = null; + } + function startFile() { + saveBlock(); + saveFile(); + currentFile = { + blocks: [], + deletedLines: 0, + addedLines: 0 + }; + } + function startBlock(line) { + saveBlock(); + let values; + if (currentFile !== null) { + if (values = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@.*/.exec(line)) { + currentFile.isCombined = false; + oldLine = parseInt(values[1], 10); + newLine = parseInt(values[2], 10); + } else if (values = /^@@@ -(\d+)(?:,\d+)? -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@@.*/.exec(line)) { + currentFile.isCombined = true; + oldLine = parseInt(values[1], 10); + oldLine2 = parseInt(values[2], 10); + newLine = parseInt(values[3], 10); + } else { + if (line.startsWith(hunkHeaderPrefix)) { + console.error("Failed to parse lines, starting in 0!"); + } + oldLine = 0; + newLine = 0; + currentFile.isCombined = false; + } + } + currentBlock = { + lines: [], + oldStartLine: oldLine, + oldStartLine2: oldLine2, + newStartLine: newLine, + header: line + }; + } + function createLine(line) { + if (currentFile === null || currentBlock === null || oldLine === null || newLine === null) + return; + const currentLine = { + content: line + }; + const addedPrefixes = currentFile.isCombined ? ["+ ", " +", "++"] : ["+"]; + const deletedPrefixes = currentFile.isCombined ? ["- ", " -", "--"] : ["-"]; + if (startsWithAny(line, addedPrefixes)) { + currentFile.addedLines++; + currentLine.type = LineType.INSERT; + currentLine.oldNumber = void 0; + currentLine.newNumber = newLine++; + } else if (startsWithAny(line, deletedPrefixes)) { + currentFile.deletedLines++; + currentLine.type = LineType.DELETE; + currentLine.oldNumber = oldLine++; + currentLine.newNumber = void 0; + } else { + currentLine.type = LineType.CONTEXT; + currentLine.oldNumber = oldLine++; + currentLine.newNumber = newLine++; + } + currentBlock.lines.push(currentLine); + } + function existHunkHeader(line, lineIdx) { + let idx = lineIdx; + while (idx < diffLines2.length - 3) { + if (line.startsWith("diff")) { + return false; + } + if (diffLines2[idx].startsWith(oldFileNameHeader) && diffLines2[idx + 1].startsWith(newFileNameHeader) && diffLines2[idx + 2].startsWith(hunkHeaderPrefix)) { + return true; + } + idx++; + } + return false; + } + diffLines2.forEach((line, lineIndex) => { + if (!line || line.startsWith("*")) { + return; + } + let values; + const prevLine = diffLines2[lineIndex - 1]; + const nxtLine = diffLines2[lineIndex + 1]; + const afterNxtLine = diffLines2[lineIndex + 2]; + if (line.startsWith("diff --git") || line.startsWith("diff --combined")) { + startFile(); + const gitDiffStart = /^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/; + if (values = gitDiffStart.exec(line)) { + possibleOldName = getFilename(values[1], void 0, config.dstPrefix); + possibleNewName = getFilename(values[2], void 0, config.srcPrefix); + } + if (currentFile === null) { + throw new Error("Where is my file !!!"); + } + currentFile.isGitDiff = true; + return; + } + if (line.startsWith("Binary files") && !(currentFile === null || currentFile === void 0 ? void 0 : currentFile.isGitDiff)) { + startFile(); + const unixDiffBinaryStart = /^Binary files "?([a-ciow]\/.+)"? and "?([a-ciow]\/.+)"? differ/; + if (values = unixDiffBinaryStart.exec(line)) { + possibleOldName = getFilename(values[1], void 0, config.dstPrefix); + possibleNewName = getFilename(values[2], void 0, config.srcPrefix); + } + if (currentFile === null) { + throw new Error("Where is my file !!!"); + } + currentFile.isBinary = true; + return; + } + if (!currentFile || !currentFile.isGitDiff && currentFile && line.startsWith(oldFileNameHeader) && nxtLine.startsWith(newFileNameHeader) && afterNxtLine.startsWith(hunkHeaderPrefix)) { + startFile(); + } + if (currentFile === null || currentFile === void 0 ? void 0 : currentFile.isTooBig) { + return; + } + if (currentFile && (typeof config.diffMaxChanges === "number" && currentFile.addedLines + currentFile.deletedLines > config.diffMaxChanges || typeof config.diffMaxLineLength === "number" && line.length > config.diffMaxLineLength)) { + currentFile.isTooBig = true; + currentFile.addedLines = 0; + currentFile.deletedLines = 0; + currentFile.blocks = []; + currentBlock = null; + const message = typeof config.diffTooBigMessage === "function" ? config.diffTooBigMessage(files.length) : "Diff too big to be displayed"; + startBlock(message); + return; + } + if (line.startsWith(oldFileNameHeader) && nxtLine.startsWith(newFileNameHeader) || line.startsWith(newFileNameHeader) && prevLine.startsWith(oldFileNameHeader)) { + if (currentFile && !currentFile.oldName && line.startsWith("--- ") && (values = getSrcFilename(line, config.srcPrefix))) { + currentFile.oldName = values; + currentFile.language = getExtension(currentFile.oldName, currentFile.language); + return; + } + if (currentFile && !currentFile.newName && line.startsWith("+++ ") && (values = getDstFilename(line, config.dstPrefix))) { + currentFile.newName = values; + currentFile.language = getExtension(currentFile.newName, currentFile.language); + return; + } + } + if (currentFile && (line.startsWith(hunkHeaderPrefix) || currentFile.isGitDiff && currentFile.oldName && currentFile.newName && !currentBlock)) { + startBlock(line); + return; + } + if (currentBlock && (line.startsWith("+") || line.startsWith("-") || line.startsWith(" "))) { + createLine(line); + return; + } + const doesNotExistHunkHeader = !existHunkHeader(line, lineIndex); + if (currentFile === null) { + throw new Error("Where is my file !!!"); + } + if (values = oldMode.exec(line)) { + currentFile.oldMode = values[1]; + } else if (values = newMode.exec(line)) { + currentFile.newMode = values[1]; + } else if (values = deletedFileMode.exec(line)) { + currentFile.deletedFileMode = values[1]; + currentFile.isDeleted = true; + } else if (values = newFileMode.exec(line)) { + currentFile.newFileMode = values[1]; + currentFile.isNew = true; + } else if (values = copyFrom.exec(line)) { + if (doesNotExistHunkHeader) { + currentFile.oldName = values[1]; + } + currentFile.isCopy = true; + } else if (values = copyTo.exec(line)) { + if (doesNotExistHunkHeader) { + currentFile.newName = values[1]; + } + currentFile.isCopy = true; + } else if (values = renameFrom.exec(line)) { + if (doesNotExistHunkHeader) { + currentFile.oldName = values[1]; + } + currentFile.isRename = true; + } else if (values = renameTo.exec(line)) { + if (doesNotExistHunkHeader) { + currentFile.newName = values[1]; + } + currentFile.isRename = true; + } else if (values = binaryFiles.exec(line)) { + currentFile.isBinary = true; + currentFile.oldName = getFilename(values[1], void 0, config.srcPrefix); + currentFile.newName = getFilename(values[2], void 0, config.dstPrefix); + startBlock("Binary file"); + } else if (binaryDiff.test(line)) { + currentFile.isBinary = true; + startBlock(line); + } else if (values = similarityIndex.exec(line)) { + currentFile.unchangedPercentage = parseInt(values[1], 10); + } else if (values = dissimilarityIndex.exec(line)) { + currentFile.changedPercentage = parseInt(values[1], 10); + } else if (values = index2.exec(line)) { + currentFile.checksumBefore = values[1]; + currentFile.checksumAfter = values[2]; + values[3] && (currentFile.mode = values[3]); + } else if (values = combinedIndex.exec(line)) { + currentFile.checksumBefore = [values[2], values[3]]; + currentFile.checksumAfter = values[1]; + } else if (values = combinedMode.exec(line)) { + currentFile.oldMode = [values[2], values[3]]; + currentFile.newMode = values[1]; + } else if (values = combinedNewFile.exec(line)) { + currentFile.newFileMode = values[1]; + currentFile.isNew = true; + } else if (values = combinedDeletedFile.exec(line)) { + currentFile.deletedFileMode = values[1]; + currentFile.isDeleted = true; + } + }); + saveBlock(); + saveFile(); + return files; +} + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/file-list-renderer.js +init_polyfill_buffer(); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/render-utils.js +init_polyfill_buffer(); + +// node_modules/.pnpm/diff@5.1.0/node_modules/diff/lib/index.mjs +init_polyfill_buffer(); +function Diff2() { +} +Diff2.prototype = { + diff: function diff2(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + var callback = options.callback; + if (typeof options === "function") { + callback = options; + options = {}; + } + this.options = options; + var self2 = this; + function done(value) { + if (callback) { + setTimeout(function() { + callback(void 0, value); + }, 0); + return true; + } else { + return value; + } + } + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + if (options.maxEditLength) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + var bestPath = [{ + newPos: -1, + components: [] + }]; + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + return done([{ + value: this.join(newString), + count: newString.length + }]); + } + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + bestPath[diagonalPath - 1] = void 0; + } + var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self2.pushComponent(basePath.components, void 0, true); + } else { + basePath = addPath; + basePath.newPos++; + self2.pushComponent(basePath.components, true, void 0); + } + _oldPos = self2.extractCommon(basePath, newString, oldString, diagonalPath); + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues2(self2, basePath.components, newString, oldString, self2.useLongestToken)); + } else { + bestPath[diagonalPath] = basePath; + } + } + editLength++; + } + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength) { + return callback(); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last2 = components[components.length - 1]; + if (last2 && last2.added === added && last2.removed === removed) { + components[components.length - 1] = { + count: last2.count + 1, + added, + removed + }; + } else { + components.push({ + count: 1, + added, + removed + }); + } + }, + extractCommon: function extractCommon2(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals2(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty2(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }, + castInput: function castInput2(value) { + return value; + }, + tokenize: function tokenize2(value) { + return value.split(""); + }, + join: function join4(chars) { + return chars.join(""); + } +}; +function buildValues2(diff3, components, newString, oldString, useLongestToken) { + var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = diff3.join(value); + } else { + component.value = diff3.join(newString.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff3.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } + var lastComponent = components[componentLen - 1]; + if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff3.equals("", lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + return components; +} +function clonePath(path2) { + return { + newPos: path2.newPos, + components: path2.components.slice(0) + }; +} +var characterDiff2 = new Diff2(); +function diffChars(oldStr, newStr, options) { + return characterDiff2.diff(oldStr, newStr, options); +} +var extendedWordChars2 = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace2 = /\S/; +var wordDiff2 = new Diff2(); +wordDiff2.equals = function(left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left === right || this.options.ignoreWhitespace && !reWhitespace2.test(left) && !reWhitespace2.test(right); +}; +wordDiff2.tokenize = function(value) { + var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); + for (var i = 0; i < tokens.length - 1; i++) { + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars2.test(tokens[i]) && extendedWordChars2.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + return tokens; +}; +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff2.diff(oldStr, newStr, options); +} +var lineDiff2 = new Diff2(); +lineDiff2.tokenize = function(value) { + var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + retLines.push(line); + } + } + return retLines; +}; +var sentenceDiff2 = new Diff2(); +sentenceDiff2.tokenize = function(value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; +var cssDiff2 = new Diff2(); +cssDiff2.tokenize = function(value) { + return value.split(/([{}:;,]|\s+)/); +}; +function _typeof2(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof2 = function(obj2) { + return typeof obj2; + }; + } else { + _typeof2 = function(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; + } + return _typeof2(obj); +} +var objectPrototypeToString2 = Object.prototype.toString; +var jsonDiff2 = new Diff2(); +jsonDiff2.useLongestToken = true; +jsonDiff2.tokenize = lineDiff2.tokenize; +jsonDiff2.castInput = function(value) { + var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) { + return typeof v === "undefined" ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === "string" ? value : JSON.stringify(canonicalize2(value, null, null, stringifyReplacer), stringifyReplacer, " "); +}; +jsonDiff2.equals = function(left, right) { + return Diff2.prototype.equals.call(jsonDiff2, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1")); +}; +function canonicalize2(obj, stack, replacementStack, replacer, key2) { + stack = stack || []; + replacementStack = replacementStack || []; + if (replacer) { + obj = replacer(key2, obj); + } + var i; + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + var canonicalizedObj; + if ("[object Array]" === objectPrototypeToString2.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize2(obj[i], stack, replacementStack, replacer, key2); + } + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + if (_typeof2(obj) === "object" && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], _key; + for (_key in obj) { + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize2(obj[_key], stack, replacementStack, replacer, _key); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; +} +var arrayDiff2 = new Diff2(); +arrayDiff2.tokenize = function(value) { + return value.slice(); +}; +arrayDiff2.join = arrayDiff2.removeEmpty = function(value) { + return value; +}; + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/rematch.js +init_polyfill_buffer(); +function levenshtein(a, b) { + if (a.length === 0) { + return b.length; + } + if (b.length === 0) { + return a.length; + } + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + return matrix[b.length][a.length]; +} +function newDistanceFn(str) { + return (x, y) => { + const xValue = str(x).trim(); + const yValue = str(y).trim(); + const lev = levenshtein(xValue, yValue); + return lev / (xValue.length + yValue.length); + }; +} +function newMatcherFn(distance2) { + function findBestMatch(a, b, cache = /* @__PURE__ */ new Map()) { + let bestMatchDist = Infinity; + let bestMatch; + for (let i = 0; i < a.length; ++i) { + for (let j = 0; j < b.length; ++j) { + const cacheKey = JSON.stringify([a[i], b[j]]); + let md; + if (!(cache.has(cacheKey) && (md = cache.get(cacheKey)))) { + md = distance2(a[i], b[j]); + cache.set(cacheKey, md); + } + if (md < bestMatchDist) { + bestMatchDist = md; + bestMatch = { indexA: i, indexB: j, score: bestMatchDist }; + } + } + } + return bestMatch; + } + function group(a, b, level = 0, cache = /* @__PURE__ */ new Map()) { + const bm = findBestMatch(a, b, cache); + if (!bm || a.length + b.length < 3) { + return [[a, b]]; + } + const a1 = a.slice(0, bm.indexA); + const b1 = b.slice(0, bm.indexB); + const aMatch = [a[bm.indexA]]; + const bMatch = [b[bm.indexB]]; + const tailA = bm.indexA + 1; + const tailB = bm.indexB + 1; + const a2 = a.slice(tailA); + const b2 = b.slice(tailB); + const group1 = group(a1, b1, level + 1, cache); + const groupMatch = group(aMatch, bMatch, level + 1, cache); + const group2 = group(a2, b2, level + 1, cache); + let result = groupMatch; + if (bm.indexA > 0 || bm.indexB > 0) { + result = group1.concat(result); + } + if (a.length > tailA || b.length > tailB) { + result = result.concat(group2); + } + return result; + } + return group; +} + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/render-utils.js +var CSSLineClass = { + INSERTS: "d2h-ins", + DELETES: "d2h-del", + CONTEXT: "d2h-cntx", + INFO: "d2h-info", + INSERT_CHANGES: "d2h-ins d2h-change", + DELETE_CHANGES: "d2h-del d2h-change" +}; +var defaultRenderConfig = { + matching: LineMatchingType.NONE, + matchWordsThreshold: 0.25, + maxLineLengthHighlight: 1e4, + diffStyle: DiffStyleType.WORD, + colorScheme: ColorSchemeType.LIGHT +}; +var separator = "/"; +var distance = newDistanceFn((change) => change.value); +var matcher = newMatcherFn(distance); +function isDevNullName(name) { + return name.indexOf("dev/null") !== -1; +} +function removeInsElements(line) { + return line.replace(/(]*>((.|\n)*?)<\/ins>)/g, ""); +} +function removeDelElements(line) { + return line.replace(/(]*>((.|\n)*?)<\/del>)/g, ""); +} +function toCSSClass(lineType) { + switch (lineType) { + case LineType.CONTEXT: + return CSSLineClass.CONTEXT; + case LineType.INSERT: + return CSSLineClass.INSERTS; + case LineType.DELETE: + return CSSLineClass.DELETES; + } +} +function colorSchemeToCss(colorScheme) { + switch (colorScheme) { + case ColorSchemeType.DARK: + return "d2h-dark-color-scheme"; + case ColorSchemeType.AUTO: + return "d2h-auto-color-scheme"; + case ColorSchemeType.LIGHT: + default: + return "d2h-light-color-scheme"; + } +} +function prefixLength(isCombined) { + return isCombined ? 2 : 1; +} +function escapeForHtml(str) { + return str.slice(0).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/\//g, "/"); +} +function deconstructLine(line, isCombined, escape = true) { + const indexToSplit = prefixLength(isCombined); + return { + prefix: line.substring(0, indexToSplit), + content: escape ? escapeForHtml(line.substring(indexToSplit)) : line.substring(indexToSplit) + }; +} +function filenameDiff(file) { + const oldFilename = unifyPath(file.oldName); + const newFilename = unifyPath(file.newName); + if (oldFilename !== newFilename && !isDevNullName(oldFilename) && !isDevNullName(newFilename)) { + const prefixPaths = []; + const suffixPaths = []; + const oldFilenameParts = oldFilename.split(separator); + const newFilenameParts = newFilename.split(separator); + const oldFilenamePartsSize = oldFilenameParts.length; + const newFilenamePartsSize = newFilenameParts.length; + let i = 0; + let j = oldFilenamePartsSize - 1; + let k = newFilenamePartsSize - 1; + while (i < j && i < k) { + if (oldFilenameParts[i] === newFilenameParts[i]) { + prefixPaths.push(newFilenameParts[i]); + i += 1; + } else { + break; + } + } + while (j > i && k > i) { + if (oldFilenameParts[j] === newFilenameParts[k]) { + suffixPaths.unshift(newFilenameParts[k]); + j -= 1; + k -= 1; + } else { + break; + } + } + const finalPrefix = prefixPaths.join(separator); + const finalSuffix = suffixPaths.join(separator); + const oldRemainingPath = oldFilenameParts.slice(i, j + 1).join(separator); + const newRemainingPath = newFilenameParts.slice(i, k + 1).join(separator); + if (finalPrefix.length && finalSuffix.length) { + return finalPrefix + separator + "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}" + separator + finalSuffix; + } else if (finalPrefix.length) { + return finalPrefix + separator + "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}"; + } else if (finalSuffix.length) { + return "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}" + separator + finalSuffix; + } + return oldFilename + " \u2192 " + newFilename; + } else if (!isDevNullName(newFilename)) { + return newFilename; + } else { + return oldFilename; + } +} +function getHtmlId(file) { + return `d2h-${hashCode(filenameDiff(file)).toString().slice(-6)}`; +} +function getFileIcon(file) { + let templateName = "file-changed"; + if (file.isRename) { + templateName = "file-renamed"; + } else if (file.isCopy) { + templateName = "file-renamed"; + } else if (file.isNew) { + templateName = "file-added"; + } else if (file.isDeleted) { + templateName = "file-deleted"; + } else if (file.newName !== file.oldName) { + templateName = "file-renamed"; + } + return templateName; +} +function diffHighlight(diffLine1, diffLine2, isCombined, config = {}) { + const { matching, maxLineLengthHighlight, matchWordsThreshold, diffStyle } = Object.assign(Object.assign({}, defaultRenderConfig), config); + const line1 = deconstructLine(diffLine1, isCombined, false); + const line2 = deconstructLine(diffLine2, isCombined, false); + if (line1.content.length > maxLineLengthHighlight || line2.content.length > maxLineLengthHighlight) { + return { + oldLine: { + prefix: line1.prefix, + content: escapeForHtml(line1.content) + }, + newLine: { + prefix: line2.prefix, + content: escapeForHtml(line2.content) + } + }; + } + const diff3 = diffStyle === "char" ? diffChars(line1.content, line2.content) : diffWordsWithSpace(line1.content, line2.content); + const changedWords = []; + if (diffStyle === "word" && matching === "words") { + const removed = diff3.filter((element2) => element2.removed); + const added = diff3.filter((element2) => element2.added); + const chunks = matcher(added, removed); + chunks.forEach((chunk) => { + if (chunk[0].length === 1 && chunk[1].length === 1) { + const dist = distance(chunk[0][0], chunk[1][0]); + if (dist < matchWordsThreshold) { + changedWords.push(chunk[0][0]); + changedWords.push(chunk[1][0]); + } + } + }); + } + const highlightedLine = diff3.reduce((highlightedLine2, part) => { + const elemType = part.added ? "ins" : part.removed ? "del" : null; + const addClass = changedWords.indexOf(part) > -1 ? ' class="d2h-change"' : ""; + const escapedValue = escapeForHtml(part.value); + return elemType !== null ? `${highlightedLine2}<${elemType}${addClass}>${escapedValue}` : `${highlightedLine2}${escapedValue}`; + }, ""); + return { + oldLine: { + prefix: line1.prefix, + content: removeInsElements(highlightedLine) + }, + newLine: { + prefix: line2.prefix, + content: removeDelElements(highlightedLine) + } + }; +} + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/file-list-renderer.js +var baseTemplatesPath = "file-summary"; +var iconsBaseTemplatesPath = "icon"; +var defaultFileListRendererConfig = { + colorScheme: defaultRenderConfig.colorScheme +}; +var FileListRenderer = class { + constructor(hoganUtils, config = {}) { + this.hoganUtils = hoganUtils; + this.config = Object.assign(Object.assign({}, defaultFileListRendererConfig), config); + } + render(diffFiles) { + const files = diffFiles.map((file) => this.hoganUtils.render(baseTemplatesPath, "line", { + fileHtmlId: getHtmlId(file), + oldName: file.oldName, + newName: file.newName, + fileName: filenameDiff(file), + deletedLines: "-" + file.deletedLines, + addedLines: "+" + file.addedLines + }, { + fileIcon: this.hoganUtils.template(iconsBaseTemplatesPath, getFileIcon(file)) + })).join("\n"); + return this.hoganUtils.render(baseTemplatesPath, "wrapper", { + colorScheme: colorSchemeToCss(this.config.colorScheme), + filesNumber: diffFiles.length, + files + }); + } +}; + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/line-by-line-renderer.js +init_polyfill_buffer(); +var defaultLineByLineRendererConfig = Object.assign(Object.assign({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 }); +var genericTemplatesPath = "generic"; +var baseTemplatesPath2 = "line-by-line"; +var iconsBaseTemplatesPath2 = "icon"; +var tagsBaseTemplatesPath = "tag"; +var LineByLineRenderer = class { + constructor(hoganUtils, config = {}) { + this.hoganUtils = hoganUtils; + this.config = Object.assign(Object.assign({}, defaultLineByLineRendererConfig), config); + } + render(diffFiles) { + const diffsHtml = diffFiles.map((file) => { + let diffs; + if (file.blocks.length) { + diffs = this.generateFileHtml(file); + } else { + diffs = this.generateEmptyDiff(); + } + return this.makeFileDiffHtml(file, diffs); + }).join("\n"); + return this.hoganUtils.render(genericTemplatesPath, "wrapper", { + colorScheme: colorSchemeToCss(this.config.colorScheme), + content: diffsHtml + }); + } + makeFileDiffHtml(file, diffs) { + if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0) + return ""; + const fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath2, "file-diff"); + const filePathTemplate = this.hoganUtils.template(genericTemplatesPath, "file-path"); + const fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath2, "file"); + const fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath, getFileIcon(file)); + return fileDiffTemplate.render({ + file, + fileHtmlId: getHtmlId(file), + diffs, + filePath: filePathTemplate.render({ + fileDiffName: filenameDiff(file) + }, { + fileIcon: fileIconTemplate, + fileTag: fileTagTemplate + }) + }); + } + generateEmptyDiff() { + return this.hoganUtils.render(genericTemplatesPath, "empty-diff", { + contentClass: "d2h-code-line", + CSSLineClass + }); + } + generateFileHtml(file) { + const matcher2 = newMatcherFn(newDistanceFn((e) => deconstructLine(e.content, file.isCombined).content)); + return file.blocks.map((block) => { + let lines = this.hoganUtils.render(genericTemplatesPath, "block-header", { + CSSLineClass, + blockHeader: file.isTooBig ? block.header : escapeForHtml(block.header), + lineClass: "d2h-code-linenumber", + contentClass: "d2h-code-line" + }); + this.applyLineGroupping(block).forEach(([contextLines, oldLines, newLines]) => { + if (oldLines.length && newLines.length && !contextLines.length) { + this.applyRematchMatching(oldLines, newLines, matcher2).map(([oldLines2, newLines2]) => { + const { left, right } = this.processChangedLines(file, file.isCombined, oldLines2, newLines2); + lines += left; + lines += right; + }); + } else if (contextLines.length) { + contextLines.forEach((line) => { + const { prefix, content } = deconstructLine(line.content, file.isCombined); + lines += this.generateSingleLineHtml(file, { + type: CSSLineClass.CONTEXT, + prefix, + content, + oldNumber: line.oldNumber, + newNumber: line.newNumber + }); + }); + } else if (oldLines.length || newLines.length) { + const { left, right } = this.processChangedLines(file, file.isCombined, oldLines, newLines); + lines += left; + lines += right; + } else { + console.error("Unknown state reached while processing groups of lines", contextLines, oldLines, newLines); + } + }); + return lines; + }).join("\n"); + } + applyLineGroupping(block) { + const blockLinesGroups = []; + let oldLines = []; + let newLines = []; + for (let i = 0; i < block.lines.length; i++) { + const diffLine = block.lines[i]; + if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) { + blockLinesGroups.push([[], oldLines, newLines]); + oldLines = []; + newLines = []; + } + if (diffLine.type === LineType.CONTEXT) { + blockLinesGroups.push([[diffLine], [], []]); + } else if (diffLine.type === LineType.INSERT && oldLines.length === 0) { + blockLinesGroups.push([[], [], [diffLine]]); + } else if (diffLine.type === LineType.INSERT && oldLines.length > 0) { + newLines.push(diffLine); + } else if (diffLine.type === LineType.DELETE) { + oldLines.push(diffLine); + } + } + if (oldLines.length || newLines.length) { + blockLinesGroups.push([[], oldLines, newLines]); + oldLines = []; + newLines = []; + } + return blockLinesGroups; + } + applyRematchMatching(oldLines, newLines, matcher2) { + const comparisons = oldLines.length * newLines.length; + const maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map((elem) => elem.content.length))); + const doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words"); + return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]]; + } + processChangedLines(file, isCombined, oldLines, newLines) { + const fileHtml = { + right: "", + left: "" + }; + const maxLinesNumber = Math.max(oldLines.length, newLines.length); + for (let i = 0; i < maxLinesNumber; i++) { + const oldLine = oldLines[i]; + const newLine = newLines[i]; + const diff3 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0; + const preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? Object.assign(Object.assign({}, diff3 !== void 0 ? { + prefix: diff3.oldLine.prefix, + content: diff3.oldLine.content, + type: CSSLineClass.DELETE_CHANGES + } : Object.assign(Object.assign({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { oldNumber: oldLine.oldNumber, newNumber: oldLine.newNumber }) : void 0; + const preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? Object.assign(Object.assign({}, diff3 !== void 0 ? { + prefix: diff3.newLine.prefix, + content: diff3.newLine.content, + type: CSSLineClass.INSERT_CHANGES + } : Object.assign(Object.assign({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { oldNumber: newLine.oldNumber, newNumber: newLine.newNumber }) : void 0; + const { left, right } = this.generateLineHtml(file, preparedOldLine, preparedNewLine); + fileHtml.left += left; + fileHtml.right += right; + } + return fileHtml; + } + generateLineHtml(file, oldLine, newLine) { + return { + left: this.generateSingleLineHtml(file, oldLine), + right: this.generateSingleLineHtml(file, newLine) + }; + } + generateSingleLineHtml(file, line) { + if (line === void 0) + return ""; + const lineNumberHtml = this.hoganUtils.render(baseTemplatesPath2, "numbers", { + oldNumber: line.oldNumber || "", + newNumber: line.newNumber || "" + }); + return this.hoganUtils.render(genericTemplatesPath, "line", { + type: line.type, + lineClass: "d2h-code-linenumber", + contentClass: "d2h-code-line", + prefix: line.prefix === " " ? " " : line.prefix, + content: line.content, + lineNumber: lineNumberHtml, + line, + file + }); + } +}; + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/side-by-side-renderer.js +init_polyfill_buffer(); +var defaultSideBySideRendererConfig = Object.assign(Object.assign({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 }); +var genericTemplatesPath2 = "generic"; +var baseTemplatesPath3 = "side-by-side"; +var iconsBaseTemplatesPath3 = "icon"; +var tagsBaseTemplatesPath2 = "tag"; +var SideBySideRenderer = class { + constructor(hoganUtils, config = {}) { + this.hoganUtils = hoganUtils; + this.config = Object.assign(Object.assign({}, defaultSideBySideRendererConfig), config); + } + render(diffFiles) { + const diffsHtml = diffFiles.map((file) => { + let diffs; + if (file.blocks.length) { + diffs = this.generateFileHtml(file); + } else { + diffs = this.generateEmptyDiff(); + } + return this.makeFileDiffHtml(file, diffs); + }).join("\n"); + return this.hoganUtils.render(genericTemplatesPath2, "wrapper", { + colorScheme: colorSchemeToCss(this.config.colorScheme), + content: diffsHtml + }); + } + makeFileDiffHtml(file, diffs) { + if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0) + return ""; + const fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath3, "file-diff"); + const filePathTemplate = this.hoganUtils.template(genericTemplatesPath2, "file-path"); + const fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath3, "file"); + const fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath2, getFileIcon(file)); + return fileDiffTemplate.render({ + file, + fileHtmlId: getHtmlId(file), + diffs, + filePath: filePathTemplate.render({ + fileDiffName: filenameDiff(file) + }, { + fileIcon: fileIconTemplate, + fileTag: fileTagTemplate + }) + }); + } + generateEmptyDiff() { + return { + right: "", + left: this.hoganUtils.render(genericTemplatesPath2, "empty-diff", { + contentClass: "d2h-code-side-line", + CSSLineClass + }) + }; + } + generateFileHtml(file) { + const matcher2 = newMatcherFn(newDistanceFn((e) => deconstructLine(e.content, file.isCombined).content)); + return file.blocks.map((block) => { + const fileHtml = { + left: this.makeHeaderHtml(block.header, file), + right: this.makeHeaderHtml("") + }; + this.applyLineGroupping(block).forEach(([contextLines, oldLines, newLines]) => { + if (oldLines.length && newLines.length && !contextLines.length) { + this.applyRematchMatching(oldLines, newLines, matcher2).map(([oldLines2, newLines2]) => { + const { left, right } = this.processChangedLines(file.isCombined, oldLines2, newLines2); + fileHtml.left += left; + fileHtml.right += right; + }); + } else if (contextLines.length) { + contextLines.forEach((line) => { + const { prefix, content } = deconstructLine(line.content, file.isCombined); + const { left, right } = this.generateLineHtml({ + type: CSSLineClass.CONTEXT, + prefix, + content, + number: line.oldNumber + }, { + type: CSSLineClass.CONTEXT, + prefix, + content, + number: line.newNumber + }); + fileHtml.left += left; + fileHtml.right += right; + }); + } else if (oldLines.length || newLines.length) { + const { left, right } = this.processChangedLines(file.isCombined, oldLines, newLines); + fileHtml.left += left; + fileHtml.right += right; + } else { + console.error("Unknown state reached while processing groups of lines", contextLines, oldLines, newLines); + } + }); + return fileHtml; + }).reduce((accomulated, html2) => { + return { left: accomulated.left + html2.left, right: accomulated.right + html2.right }; + }, { left: "", right: "" }); + } + applyLineGroupping(block) { + const blockLinesGroups = []; + let oldLines = []; + let newLines = []; + for (let i = 0; i < block.lines.length; i++) { + const diffLine = block.lines[i]; + if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) { + blockLinesGroups.push([[], oldLines, newLines]); + oldLines = []; + newLines = []; + } + if (diffLine.type === LineType.CONTEXT) { + blockLinesGroups.push([[diffLine], [], []]); + } else if (diffLine.type === LineType.INSERT && oldLines.length === 0) { + blockLinesGroups.push([[], [], [diffLine]]); + } else if (diffLine.type === LineType.INSERT && oldLines.length > 0) { + newLines.push(diffLine); + } else if (diffLine.type === LineType.DELETE) { + oldLines.push(diffLine); + } + } + if (oldLines.length || newLines.length) { + blockLinesGroups.push([[], oldLines, newLines]); + oldLines = []; + newLines = []; + } + return blockLinesGroups; + } + applyRematchMatching(oldLines, newLines, matcher2) { + const comparisons = oldLines.length * newLines.length; + const maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map((elem) => elem.content.length))); + const doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words"); + return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]]; + } + makeHeaderHtml(blockHeader, file) { + return this.hoganUtils.render(genericTemplatesPath2, "block-header", { + CSSLineClass, + blockHeader: (file === null || file === void 0 ? void 0 : file.isTooBig) ? blockHeader : escapeForHtml(blockHeader), + lineClass: "d2h-code-side-linenumber", + contentClass: "d2h-code-side-line" + }); + } + processChangedLines(isCombined, oldLines, newLines) { + const fileHtml = { + right: "", + left: "" + }; + const maxLinesNumber = Math.max(oldLines.length, newLines.length); + for (let i = 0; i < maxLinesNumber; i++) { + const oldLine = oldLines[i]; + const newLine = newLines[i]; + const diff3 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0; + const preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? Object.assign(Object.assign({}, diff3 !== void 0 ? { + prefix: diff3.oldLine.prefix, + content: diff3.oldLine.content, + type: CSSLineClass.DELETE_CHANGES + } : Object.assign(Object.assign({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { number: oldLine.oldNumber }) : void 0; + const preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? Object.assign(Object.assign({}, diff3 !== void 0 ? { + prefix: diff3.newLine.prefix, + content: diff3.newLine.content, + type: CSSLineClass.INSERT_CHANGES + } : Object.assign(Object.assign({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { number: newLine.newNumber }) : void 0; + const { left, right } = this.generateLineHtml(preparedOldLine, preparedNewLine); + fileHtml.left += left; + fileHtml.right += right; + } + return fileHtml; + } + generateLineHtml(oldLine, newLine) { + return { + left: this.generateSingleHtml(oldLine), + right: this.generateSingleHtml(newLine) + }; + } + generateSingleHtml(line) { + const lineClass = "d2h-code-side-linenumber"; + const contentClass = "d2h-code-side-line"; + return this.hoganUtils.render(genericTemplatesPath2, "line", { + type: (line === null || line === void 0 ? void 0 : line.type) || `${CSSLineClass.CONTEXT} d2h-emptyplaceholder`, + lineClass: line !== void 0 ? lineClass : `${lineClass} d2h-code-side-emptyplaceholder`, + contentClass: line !== void 0 ? contentClass : `${contentClass} d2h-code-side-emptyplaceholder`, + prefix: (line === null || line === void 0 ? void 0 : line.prefix) === " " ? " " : line === null || line === void 0 ? void 0 : line.prefix, + content: line === null || line === void 0 ? void 0 : line.content, + lineNumber: line === null || line === void 0 ? void 0 : line.number + }); + } +}; + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/hoganjs-utils.js +init_polyfill_buffer(); +var Hogan3 = __toESM(require_hogan()); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/diff2html-templates.js +init_polyfill_buffer(); +var Hogan2 = __toESM(require_hogan()); +var defaultTemplates = {}; +defaultTemplates["file-summary-line"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('
  • '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(t.rp("'); + t.b(t.v(t.f("fileName", c, p, 0))); + t.b(""); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(' '); + t.b(t.v(t.f("addedLines", c, p, 0))); + t.b(""); + t.b("\n" + i); + t.b(' '); + t.b(t.v(t.f("deletedLines", c, p, 0))); + t.b(""); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b("
  • "); + return t.fl(); +}, partials: { "'); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(' Files changed ('); + t.b(t.v(t.f("filesNumber", c, p, 0))); + t.b(")"); + t.b("\n" + i); + t.b(' hide'); + t.b("\n" + i); + t.b(' show'); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b('
      '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("files", c, p, 0))); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b(""); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["generic-block-header"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b(""); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b('
    '); + if (t.s(t.f("blockHeader", c, p, 1), c, p, 0, 156, 173, "{{ }}")) { + t.rs(c, p, function(c2, p2, t2) { + t2.b(t2.t(t2.f("blockHeader", c2, p2, 0))); + }); + c.pop(); + } + if (!t.s(t.f("blockHeader", c, p, 1), c, p, 1, 0, 0, "")) { + t.b(" "); + } + ; + t.b("
    "); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b(""); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["generic-empty-diff"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b(""); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(" File without changes"); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b(""); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["generic-file-path"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b(''); + t.b("\n" + i); + t.b(t.rp("'); + t.b(t.v(t.f("fileDiffName", c, p, 0))); + t.b(""); + t.b("\n" + i); + t.b(t.rp(""); + t.b("\n" + i); + t.b('"); + return t.fl(); +}, partials: { ""); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("lineNumber", c, p, 0))); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + if (t.s(t.f("prefix", c, p, 1), c, p, 0, 162, 238, "{{ }}")) { + t.rs(c, p, function(c2, p2, t2) { + t2.b(' '); + t2.b(t2.t(t2.f("prefix", c2, p2, 0))); + t2.b(""); + t2.b("\n" + i); + }); + c.pop(); + } + if (!t.s(t.f("prefix", c, p, 1), c, p, 1, 0, 0, "")) { + t.b('  '); + t.b("\n" + i); + } + ; + if (t.s(t.f("content", c, p, 1), c, p, 0, 371, 445, "{{ }}")) { + t.rs(c, p, function(c2, p2, t2) { + t2.b(' '); + t2.b(t2.t(t2.f("content", c2, p2, 0))); + t2.b(""); + t2.b("\n" + i); + }); + c.pop(); + } + if (!t.s(t.f("content", c, p, 1), c, p, 1, 0, 0, "")) { + t.b('
    '); + t.b("\n" + i); + } + ; + t.b("
    "); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b(""); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["generic-wrapper"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('
    '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("content", c, p, 0))); + t.b("\n" + i); + t.b("
    "); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["icon-file-added"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('"); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["icon-file-changed"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('"); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["icon-file-deleted"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('"); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["icon-file-renamed"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('"); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["icon-file"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('"); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["line-by-line-file-diff"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("filePath", c, p, 0))); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("diffs", c, p, 0))); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["line-by-line-numbers"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('
    '); + t.b(t.v(t.f("oldNumber", c, p, 0))); + t.b("
    "); + t.b("\n" + i); + t.b('
    '); + t.b(t.v(t.f("newNumber", c, p, 0))); + t.b("
    "); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["side-by-side-file-diff"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.f("filePath", c, p, 0))); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.d("diffs.left", c, p, 0))); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b('
    '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(' '); + t.b("\n" + i); + t.b(" "); + t.b(t.t(t.d("diffs.right", c, p, 0))); + t.b("\n" + i); + t.b(" "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + t.b("\n" + i); + t.b("
    "); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["tag-file-added"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('ADDED'); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["tag-file-changed"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('CHANGED'); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["tag-file-deleted"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('DELETED'); + return t.fl(); +}, partials: {}, subs: {} }); +defaultTemplates["tag-file-renamed"] = new Hogan2.Template({ code: function(c, p, i) { + var t = this; + t.b(i = i || ""); + t.b('RENAMED'); + return t.fl(); +}, partials: {}, subs: {} }); + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/hoganjs-utils.js +var HoganJsUtils = class { + constructor({ compiledTemplates = {}, rawTemplates = {} }) { + const compiledRawTemplates = Object.entries(rawTemplates).reduce((previousTemplates, [name, templateString]) => { + const compiledTemplate = Hogan3.compile(templateString, { asString: false }); + return Object.assign(Object.assign({}, previousTemplates), { [name]: compiledTemplate }); + }, {}); + this.preCompiledTemplates = Object.assign(Object.assign(Object.assign({}, defaultTemplates), compiledTemplates), compiledRawTemplates); + } + static compile(templateString) { + return Hogan3.compile(templateString, { asString: false }); + } + render(namespace, view, params, partials, indent2) { + const templateKey = this.templateKey(namespace, view); + try { + const template = this.preCompiledTemplates[templateKey]; + return template.render(params, partials, indent2); + } catch (e) { + throw new Error(`Could not find template to render '${templateKey}'`); + } + } + template(namespace, view) { + return this.preCompiledTemplates[this.templateKey(namespace, view)]; + } + templateKey(namespace, view) { + return `${namespace}-${view}`; + } +}; + +// node_modules/.pnpm/diff2html@3.4.47/node_modules/diff2html/lib-esm/diff2html.js +var defaultDiff2HtmlConfig = Object.assign(Object.assign(Object.assign({}, defaultLineByLineRendererConfig), defaultSideBySideRendererConfig), { outputFormat: OutputFormatType.LINE_BY_LINE, drawFileList: true }); +function html(diffInput, configuration = {}) { + const config = Object.assign(Object.assign({}, defaultDiff2HtmlConfig), configuration); + const diffJson = typeof diffInput === "string" ? parse(diffInput, config) : diffInput; + const hoganUtils = new HoganJsUtils(config); + const { colorScheme } = config; + const fileListRendererConfig = { colorScheme }; + const fileList = config.drawFileList ? new FileListRenderer(hoganUtils, fileListRendererConfig).render(diffJson) : ""; + const diffOutput = config.outputFormat === "side-by-side" ? new SideBySideRenderer(hoganUtils, config).render(diffJson) : new LineByLineRenderer(hoganUtils, config).render(diffJson); + return fileList + diffOutput; +} + +// src/ui/diff/diffView.ts +var import_obsidian17 = require("obsidian"); +var DiffView = class extends import_obsidian17.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.plugin = plugin; + this.gettingDiff = false; + this.gitRefreshBind = this.refresh.bind(this); + this.gitViewRefreshBind = this.refresh.bind(this); + this.parser = new DOMParser(); + this.navigation = true; + addEventListener("git-refresh", this.gitRefreshBind); + addEventListener("git-view-refresh", this.gitViewRefreshBind); + } + getViewType() { + return DIFF_VIEW_CONFIG.type; + } + getDisplayText() { + var _a2; + if (((_a2 = this.state) == null ? void 0 : _a2.file) != null) { + let fileName = this.state.file.split("/").last(); + if (fileName == null ? void 0 : fileName.endsWith(".md")) + fileName = fileName.slice(0, -3); + return DIFF_VIEW_CONFIG.name + ` (${fileName})`; + } + return DIFF_VIEW_CONFIG.name; + } + getIcon() { + return DIFF_VIEW_CONFIG.icon; + } + async setState(state, result) { + this.state = state; + if (import_obsidian17.Platform.isMobile) { + this.leaf.view.titleEl.textContent = this.getDisplayText(); + } + await this.refresh(); + } + getState() { + return this.state; + } + onClose() { + removeEventListener("git-refresh", this.gitRefreshBind); + removeEventListener("git-view-refresh", this.gitViewRefreshBind); + return super.onClose(); + } + onOpen() { + this.refresh(); + return super.onOpen(); + } + async refresh() { + var _a2; + if (((_a2 = this.state) == null ? void 0 : _a2.file) && !this.gettingDiff && this.plugin.gitManager) { + this.gettingDiff = true; + try { + let diff3 = await this.plugin.gitManager.getDiffString( + this.state.file, + this.state.staged, + this.state.hash + ); + this.contentEl.empty(); + if (!diff3) { + if (this.plugin.gitManager instanceof SimpleGit && await this.plugin.gitManager.isTracked( + this.state.file + )) { + diff3 = [ + `--- ${this.state.file}`, + `+++ ${this.state.file}`, + "" + ].join("\n"); + } else { + const content = await this.app.vault.adapter.read( + this.plugin.gitManager.getRelativeVaultPath( + this.state.file + ) + ); + const header = `--- /dev/null ++++ ${this.state.file} +@@ -0,0 +1,${content.split("\n").length} @@`; + diff3 = [ + ...header.split("\n"), + ...content.split("\n").map((line) => `+${line}`) + ].join("\n"); + } + } + const diffEl = this.parser.parseFromString(html(diff3), "text/html").querySelector(".d2h-file-diff"); + this.contentEl.append(diffEl); + } finally { + this.gettingDiff = false; + } + } + } +}; + +// src/ui/history/historyView.ts +init_polyfill_buffer(); +var import_obsidian21 = require("obsidian"); + +// src/ui/history/historyView.svelte +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/index.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/animations.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/utils.js +init_polyfill_buffer(); +function noop() { +} +var identity = (x) => x; +function run(fn) { + return fn(); +} +function blank_object() { + return /* @__PURE__ */ 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; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/environment.js +init_polyfill_buffer(); +var is_client = typeof window !== "undefined"; +var now = is_client ? () => window.performance.now() : () => Date.now(); +var raf = is_client ? (cb) => requestAnimationFrame(cb) : noop; + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/loop.js +init_polyfill_buffer(); +var tasks = /* @__PURE__ */ new Set(); +function run_tasks(now2) { + tasks.forEach((task) => { + if (!task.c(now2)) { + tasks.delete(task); + task.f(); + } + }); + if (tasks.size !== 0) + raf(run_tasks); +} +function loop(callback) { + let task; + if (tasks.size === 0) + raf(run_tasks); + return { + promise: new Promise((fulfill) => { + tasks.add(task = { c: callback, f: fulfill }); + }), + abort() { + tasks.delete(task); + } + }; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/style_manager.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/dom.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/globals.js +init_polyfill_buffer(); +var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : ( + // @ts-ignore Node typings have this + global +); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js +var ResizeObserverSingleton = class _ResizeObserverSingleton { + /** @param {ResizeObserverOptions} options */ + constructor(options) { + /** + * @private + * @readonly + * @type {WeakMap} + */ + __publicField(this, "_listeners", "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0); + /** + * @private + * @type {ResizeObserver} + */ + __publicField(this, "_observer"); + /** @type {ResizeObserverOptions} */ + __publicField(this, "options"); + this.options = options; + } + /** + * @param {Element} element + * @param {import('./private.js').Listener} listener + * @returns {() => void} + */ + observe(element2, listener) { + this._listeners.set(element2, listener); + this._getObserver().observe(element2, this.options); + return () => { + this._listeners.delete(element2); + this._observer.unobserve(element2); + }; + } + /** + * @private + */ + _getObserver() { + var _a2; + return (_a2 = this._observer) != null ? _a2 : this._observer = new ResizeObserver((entries) => { + var _a3; + for (const entry of entries) { + _ResizeObserverSingleton.entries.set(entry.target, entry); + (_a3 = this._listeners.get(entry.target)) == null ? void 0 : _a3(entry); + } + }); + } +}; +ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0; + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/dom.js +var is_hydrating = false; +function start_hydrating() { + is_hydrating = true; +} +function end_hydrating() { + is_hydrating = false; +} +function append2(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 root2 = node.getRootNode ? node.getRootNode() : node.ownerDocument; + if (root2 && /** @type {ShadowRoot} */ + root2.host) { + return ( + /** @type {ShadowRoot} */ + root2 + ); + } + return node.ownerDocument; +} +function append_empty_stylesheet(node) { + const style_element = element("style"); + style_element.textContent = "/* empty */"; + append_stylesheet(get_root_for_style(node), style_element); + return style_element.sheet; +} +function append_stylesheet(node, style) { + append2( + /** @type {Document} */ + node.head || node, + style + ); + return style.sheet; +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].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 stop_propagation(fn) { + return function(event) { + event.stopPropagation(); + return fn.call(this, event); + }; +} +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.data === data) + return; + text2.data = /** @type {string} */ + data; +} +function set_input_value(input, value) { + input.value = value == null ? "" : value; +} +function set_style(node, key2, value, important) { + if (value == null) { + node.style.removeProperty(key2); + } else { + node.style.setProperty(key2, value, important ? "important" : ""); + } +} +function toggle_class(element2, name, toggle) { + element2.classList.toggle(name, !!toggle); +} +function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) { + return new CustomEvent(type, { detail, bubbles, cancelable }); +} +function get_custom_elements_slots(element2) { + const result = {}; + element2.childNodes.forEach( + /** @param {Element} node */ + (node) => { + result[node.slot || "default"] = true; + } + ); + return result; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/style_manager.js +var managed_styles = /* @__PURE__ */ new Map(); +var active = 0; +function hash(str) { + let hash2 = 5381; + let i = str.length; + while (i--) + hash2 = (hash2 << 5) - hash2 ^ str.charCodeAt(i); + return hash2 >>> 0; +} +function create_style_information(doc, node) { + const info = { stylesheet: append_empty_stylesheet(node), rules: {} }; + managed_styles.set(doc, info); + return info; +} +function create_rule(node, a, b, duration, delay2, ease, fn, uid = 0) { + const step = 16.666 / duration; + let keyframes = "{\n"; + for (let p = 0; p <= 1; p += step) { + const t = a + (b - a) * ease(p); + keyframes += p * 100 + `%{${fn(t, 1 - t)}} +`; + } + const rule = keyframes + `100% {${fn(b, 1 - b)}} +}`; + const name = `__svelte_${hash(rule)}_${uid}`; + const doc = get_root_for_style(node); + const { stylesheet, rules } = managed_styles.get(doc) || create_style_information(doc, node); + if (!rules[name]) { + rules[name] = true; + stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length); + } + const animation = node.style.animation || ""; + node.style.animation = `${animation ? `${animation}, ` : ""}${name} ${duration}ms linear ${delay2}ms 1 both`; + active += 1; + return name; +} +function delete_rule(node, name) { + const previous = (node.style.animation || "").split(", "); + const next = previous.filter( + name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1 + // remove all Svelte animations + ); + const deleted = previous.length - next.length; + if (deleted) { + node.style.animation = next.join(", "); + active -= deleted; + if (!active) + clear_rules(); + } +} +function clear_rules() { + raf(() => { + if (active) + return; + managed_styles.forEach((info) => { + const { ownerNode } = info.stylesheet; + if (ownerNode) + detach(ownerNode); + }); + managed_styles.clear(); + }); +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/await_block.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/transitions.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/scheduler.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/lifecycle.js +init_polyfill_buffer(); +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 onDestroy(fn) { + get_current_component().$$.on_destroy.push(fn); +} +function bubble(component, event) { + const callbacks = component.$$.callbacks[event.type]; + if (callbacks) { + callbacks.slice().forEach((fn) => fn.call(this, event)); + } +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/scheduler.js +var dirty_components = []; +var binding_callbacks = []; +var render_callbacks = []; +var flush_callbacks = []; +var resolved_promise = /* @__PURE__ */ 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 = /* @__PURE__ */ new Set(); +var flushidx = 0; +function flush() { + if (flushidx !== 0) { + return; + } + const saved_component = current_component; + do { + try { + while (flushidx < dirty_components.length) { + const component = dirty_components[flushidx]; + flushidx++; + set_current_component(component); + update(component.$$); + } + } catch (e) { + dirty_components.length = 0; + flushidx = 0; + throw e; + } + set_current_component(null); + dirty_components.length = 0; + flushidx = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + 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); + } +} +function flush_render_callbacks(fns) { + const filtered = []; + const targets = []; + render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c)); + targets.forEach((c) => c()); + render_callbacks = filtered; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/transitions.js +var promise; +function wait() { + if (!promise) { + promise = Promise.resolve(); + promise.then(() => { + promise = null; + }); + } + return promise; +} +function dispatch(node, direction, kind) { + node.dispatchEvent(custom_event(`${direction ? "intro" : "outro"}${kind}`)); +} +var outroing = /* @__PURE__ */ new Set(); +var outros; +function group_outros() { + outros = { + r: 0, + c: [], + p: outros + // parent group + }; +} +function check_outros() { + if (!outros.r) { + run_all(outros.c); + } + outros = outros.p; +} +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function transition_out(block, local, detach2, callback) { + if (block && block.o) { + if (outroing.has(block)) + return; + outroing.add(block); + outros.c.push(() => { + outroing.delete(block); + if (callback) { + if (detach2) + block.d(1); + callback(); + } + }); + block.o(local); + } else if (callback) { + callback(); + } +} +var null_transition = { duration: 0 }; +function create_bidirectional_transition(node, fn, params, intro) { + const options = { direction: "both" }; + let config = fn(node, params, options); + let t = intro ? 0 : 1; + let running_program = null; + let pending_program = null; + let animation_name = null; + let original_inert_value; + function clear_animation() { + if (animation_name) + delete_rule(node, animation_name); + } + function init3(program, duration) { + const d = ( + /** @type {Program['d']} */ + program.b - t + ); + duration *= Math.abs(d); + return { + a: t, + b: program.b, + d, + duration, + start: program.start, + end: program.start + duration, + group: program.group + }; + } + function go(b) { + const { + delay: delay2 = 0, + duration = 300, + easing = identity, + tick: tick2 = noop, + css + } = config || null_transition; + const program = { + start: now() + delay2, + b + }; + if (!b) { + program.group = outros; + outros.r += 1; + } + if ("inert" in node) { + if (b) { + if (original_inert_value !== void 0) { + node.inert = original_inert_value; + } + } else { + original_inert_value = /** @type {HTMLElement} */ + node.inert; + node.inert = true; + } + } + if (running_program || pending_program) { + pending_program = program; + } else { + if (css) { + clear_animation(); + animation_name = create_rule(node, t, b, duration, delay2, easing, css); + } + if (b) + tick2(0, 1); + running_program = init3(program, duration); + add_render_callback(() => dispatch(node, b, "start")); + loop((now2) => { + if (pending_program && now2 > pending_program.start) { + running_program = init3(pending_program, duration); + pending_program = null; + dispatch(node, running_program.b, "start"); + if (css) { + clear_animation(); + animation_name = create_rule( + node, + t, + running_program.b, + running_program.duration, + 0, + easing, + config.css + ); + } + } + if (running_program) { + if (now2 >= running_program.end) { + tick2(t = running_program.b, 1 - t); + dispatch(node, running_program.b, "end"); + if (!pending_program) { + if (running_program.b) { + clear_animation(); + } else { + if (!--running_program.group.r) + run_all(running_program.group.c); + } + } + running_program = null; + } else if (now2 >= running_program.start) { + const p = now2 - running_program.start; + t = running_program.a + running_program.d * easing(p / running_program.duration); + tick2(t, 1 - t); + } + } + return !!(running_program || pending_program); + }); + } + } + return { + run(b) { + if (is_function(config)) { + wait().then(() => { + const opts = { direction: b ? "in" : "out" }; + config = config(opts); + go(b); + }); + } else { + go(b); + } + }, + end() { + clear_animation(); + running_program = pending_program = null; + } + }; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/each.js +init_polyfill_buffer(); +function ensure_array_like(array_like_or_iterator) { + return (array_like_or_iterator == null ? void 0 : array_like_or_iterator.length) !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator); +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/spread.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/ssr.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/shared/boolean_attributes.js +init_polyfill_buffer(); +var _boolean_attributes = ( + /** @type {const} */ + [ + "allowfullscreen", + "allowpaymentrequest", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "defer", + "disabled", + "formnovalidate", + "hidden", + "inert", + "ismap", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "selected" + ] +); +var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/shared/utils/names.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/Component.js +init_polyfill_buffer(); +function create_component(block) { + block && block.c(); +} +function mount_component(component, target, anchor) { + const { fragment, after_update } = component.$$; + fragment && fragment.m(target, anchor); + add_render_callback(() => { + const new_on_destroy = component.$$.on_mount.map(run).filter(is_function); + if (component.$$.on_destroy) { + component.$$.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) { + flush_render_callbacks($$.after_update); + run_all($$.on_destroy); + $$.fragment && $$.fragment.d(detaching); + $$.on_destroy = $$.fragment = null; + $$.ctx = []; + } +} +function make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[i / 31 | 0] |= 1 << i % 31; +} +function init2(component, options, instance10, create_fragment10, not_equal, props, append_styles2 = null, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: [], + // state + props, + update: noop, + not_equal, + bound: blank_object(), + // lifecycle + on_mount: [], + on_destroy: [], + on_disconnect: [], + before_update: [], + after_update: [], + context: new Map(options.context || (parent_component ? parent_component.$$.context : [])), + // everything else + callbacks: blank_object(), + dirty, + skip_bound: false, + root: options.target || parent_component.$$.root + }; + append_styles2 && append_styles2($$.root); + let ready = false; + $$.ctx = instance10 ? instance10(component, options.props || {}, (i, ret, ...rest) => { + const value = rest.length ? rest[0] : ret; + if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { + if (!$$.skip_bound && $$.bound[i]) + $$.bound[i](value); + if (ready) + make_dirty(component, i); + } + return ret; + }) : []; + $$.update(); + ready = true; + run_all($$.before_update); + $$.fragment = create_fragment10 ? create_fragment10($$.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); + end_hydrating(); + flush(); + } + set_current_component(parent_component); +} +var SvelteElement; +if (typeof HTMLElement === "function") { + SvelteElement = class extends HTMLElement { + constructor($$componentCtor, $$slots, use_shadow_dom) { + super(); + /** The Svelte component constructor */ + __publicField(this, "$$ctor"); + /** Slots */ + __publicField(this, "$$s"); + /** The Svelte component instance */ + __publicField(this, "$$c"); + /** Whether or not the custom element is connected */ + __publicField(this, "$$cn", false); + /** Component props data */ + __publicField(this, "$$d", {}); + /** `true` if currently in the process of reflecting component props back to attributes */ + __publicField(this, "$$r", false); + /** @type {Record} Props definition (name, reflected, type etc) */ + __publicField(this, "$$p_d", {}); + /** @type {Record} Event listeners */ + __publicField(this, "$$l", {}); + /** @type {Map} Event listener unsubscribe functions */ + __publicField(this, "$$l_u", /* @__PURE__ */ new Map()); + this.$$ctor = $$componentCtor; + this.$$s = $$slots; + if (use_shadow_dom) { + this.attachShadow({ mode: "open" }); + } + } + addEventListener(type, listener, options) { + this.$$l[type] = this.$$l[type] || []; + this.$$l[type].push(listener); + if (this.$$c) { + const unsub = this.$$c.$on(type, listener); + this.$$l_u.set(listener, unsub); + } + super.addEventListener(type, listener, options); + } + removeEventListener(type, listener, options) { + super.removeEventListener(type, listener, options); + if (this.$$c) { + const unsub = this.$$l_u.get(listener); + if (unsub) { + unsub(); + this.$$l_u.delete(listener); + } + } + } + async connectedCallback() { + this.$$cn = true; + if (!this.$$c) { + let create_slot = function(name) { + return () => { + let node; + const obj = { + c: function create() { + node = element("slot"); + if (name !== "default") { + attr(node, "name", name); + } + }, + /** + * @param {HTMLElement} target + * @param {HTMLElement} [anchor] + */ + m: function mount(target, anchor) { + insert(target, node, anchor); + }, + d: function destroy(detaching) { + if (detaching) { + detach(node); + } + } + }; + return obj; + }; + }; + await Promise.resolve(); + if (!this.$$cn) { + return; + } + const $$slots = {}; + const existing_slots = get_custom_elements_slots(this); + for (const name of this.$$s) { + if (name in existing_slots) { + $$slots[name] = [create_slot(name)]; + } + } + for (const attribute of this.attributes) { + const name = this.$$g_p(attribute.name); + if (!(name in this.$$d)) { + this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp"); + } + } + for (const key2 in this.$$p_d) { + if (!(key2 in this.$$d) && this[key2] !== void 0) { + this.$$d[key2] = this[key2]; + delete this[key2]; + } + } + this.$$c = new this.$$ctor({ + target: this.shadowRoot || this, + props: { + ...this.$$d, + $$slots, + $$scope: { + ctx: [] + } + } + }); + const reflect_attributes = () => { + this.$$r = true; + for (const key2 in this.$$p_d) { + this.$$d[key2] = this.$$c.$$.ctx[this.$$c.$$.props[key2]]; + if (this.$$p_d[key2].reflect) { + const attribute_value = get_custom_element_value( + key2, + this.$$d[key2], + this.$$p_d, + "toAttribute" + ); + if (attribute_value == null) { + this.removeAttribute(this.$$p_d[key2].attribute || key2); + } else { + this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value); + } + } + } + this.$$r = false; + }; + this.$$c.$$.after_update.push(reflect_attributes); + reflect_attributes(); + for (const type in this.$$l) { + for (const listener of this.$$l[type]) { + const unsub = this.$$c.$on(type, listener); + this.$$l_u.set(listener, unsub); + } + } + this.$$l = {}; + } + } + // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte + // and setting attributes through setAttribute etc, this is helpful + attributeChangedCallback(attr2, _oldValue, newValue) { + var _a2; + if (this.$$r) + return; + attr2 = this.$$g_p(attr2); + this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp"); + (_a2 = this.$$c) == null ? void 0 : _a2.$set({ [attr2]: this.$$d[attr2] }); + } + disconnectedCallback() { + this.$$cn = false; + Promise.resolve().then(() => { + if (!this.$$cn) { + this.$$c.$destroy(); + this.$$c = void 0; + } + }); + } + $$g_p(attribute_name) { + return Object.keys(this.$$p_d).find( + (key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name + ) || attribute_name; + } + }; +} +function get_custom_element_value(prop, value, props_definition, transform) { + var _a2; + const type = (_a2 = props_definition[prop]) == null ? void 0 : _a2.type; + value = type === "Boolean" && typeof value !== "boolean" ? value != null : value; + if (!transform || !props_definition[prop]) { + return value; + } else if (transform === "toAttribute") { + switch (type) { + case "Object": + case "Array": + return value == null ? null : JSON.stringify(value); + case "Boolean": + return value ? "" : null; + case "Number": + return value == null ? null : value; + default: + return value; + } + } else { + switch (type) { + case "Object": + case "Array": + return value && JSON.parse(value); + case "Boolean": + return value; + case "Number": + return value != null ? +value : value; + default: + return value; + } + } +} +var SvelteComponent = class { + constructor() { + /** + * ### PRIVATE API + * + * Do not use, may change at any time + * + * @type {any} + */ + __publicField(this, "$$"); + /** + * ### PRIVATE API + * + * Do not use, may change at any time + * + * @type {any} + */ + __publicField(this, "$$set"); + } + /** @returns {void} */ + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + /** + * @template {Extract} K + * @param {K} type + * @param {((e: Events[K]) => void) | null | undefined} callback + * @returns {() => void} + */ + $on(type, callback) { + if (!is_function(callback)) { + return noop; + } + const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); + callbacks.push(callback); + return () => { + const index2 = callbacks.indexOf(callback); + if (index2 !== -1) + callbacks.splice(index2, 1); + }; + } + /** + * @param {Partial} props + * @returns {void} + */ + $set(props) { + if (this.$$set && !is_empty(props)) { + this.$$.skip_bound = true; + this.$$set(props); + this.$$.skip_bound = false; + } + } +}; + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/dev.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/shared/version.js +init_polyfill_buffer(); +var PUBLIC_VERSION = "4"; + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/internal/disclose-version/index.js +init_polyfill_buffer(); +if (typeof window !== "undefined") + (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION); + +// node_modules/.pnpm/tslib@2.6.2/node_modules/tslib/tslib.es6.mjs +init_polyfill_buffer(); +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +// src/ui/history/historyView.svelte +var import_obsidian20 = require("obsidian"); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/index.js +init_polyfill_buffer(); + +// src/ui/history/components/logComponent.svelte +init_polyfill_buffer(); +var import_obsidian19 = require("obsidian"); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/transition/index.js +init_polyfill_buffer(); + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/easing/index.js +init_polyfill_buffer(); +function cubicOut(t) { + const f = t - 1; + return f * f * f + 1; +} + +// node_modules/.pnpm/svelte@4.2.10/node_modules/svelte/src/runtime/transition/index.js +function slide(node, { delay: delay2 = 0, duration = 400, easing = cubicOut, axis = "y" } = {}) { + const style = getComputedStyle(node); + const opacity = +style.opacity; + const primary_property = axis === "y" ? "height" : "width"; + const primary_property_value = parseFloat(style[primary_property]); + const secondary_properties = axis === "y" ? ["top", "bottom"] : ["left", "right"]; + const capitalized_secondary_properties = secondary_properties.map( + (e) => `${e[0].toUpperCase()}${e.slice(1)}` + ); + const padding_start_value = parseFloat(style[`padding${capitalized_secondary_properties[0]}`]); + const padding_end_value = parseFloat(style[`padding${capitalized_secondary_properties[1]}`]); + const margin_start_value = parseFloat(style[`margin${capitalized_secondary_properties[0]}`]); + const margin_end_value = parseFloat(style[`margin${capitalized_secondary_properties[1]}`]); + const border_width_start_value = parseFloat( + style[`border${capitalized_secondary_properties[0]}Width`] + ); + const border_width_end_value = parseFloat( + style[`border${capitalized_secondary_properties[1]}Width`] + ); + return { + delay: delay2, + duration, + easing, + css: (t) => `overflow: hidden;opacity: ${Math.min(t * 20, 1) * opacity};${primary_property}: ${t * primary_property_value}px;padding-${secondary_properties[0]}: ${t * padding_start_value}px;padding-${secondary_properties[1]}: ${t * padding_end_value}px;margin-${secondary_properties[0]}: ${t * margin_start_value}px;margin-${secondary_properties[1]}: ${t * margin_end_value}px;border-${secondary_properties[0]}-width: ${t * border_width_start_value}px;border-${secondary_properties[1]}-width: ${t * border_width_end_value}px;` + }; +} + +// src/ui/history/components/logFileComponent.svelte +init_polyfill_buffer(); +var import_obsidian18 = require("obsidian"); +function add_css(target) { + append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}"); +} +function create_if_block(ctx) { + let div; + let mounted; + let dispose; + return { + c() { + div = element("div"); + attr(div, "data-icon", "go-to-file"); + attr(div, "aria-label", "Open File"); + attr(div, "class", "clickable-icon"); + }, + m(target, anchor) { + insert(target, div, anchor); + ctx[7](div); + if (!mounted) { + dispose = [ + listen(div, "auxclick", stop_propagation( + /*open*/ + ctx[4] + )), + listen(div, "click", stop_propagation( + /*open*/ + ctx[4] + )) + ]; + mounted = true; + } + }, + p: noop, + d(detaching) { + if (detaching) { + detach(div); + } + ctx[7](null); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment(ctx) { + let main; + let div3; + let div0; + let t0_value = getDisplayPath( + /*diff*/ + ctx[0].vault_path + ) + ""; + let t0; + let t1; + let div2; + let div1; + let show_if = ( + /*view*/ + ctx[1].app.vault.getAbstractFileByPath( + /*diff*/ + ctx[0].vault_path + ) + ); + let t2; + let span; + let t3_value = ( + /*diff*/ + ctx[0].status + "" + ); + let t3; + let span_data_type_value; + let div3_data_path_value; + let div3_aria_label_value; + let mounted; + let dispose; + let if_block = show_if && create_if_block(ctx); + return { + c() { + var _a2, _b; + main = element("main"); + div3 = element("div"); + div0 = element("div"); + t0 = text(t0_value); + t1 = space(); + div2 = element("div"); + div1 = element("div"); + if (if_block) + if_block.c(); + t2 = space(); + span = element("span"); + t3 = text(t3_value); + attr(div0, "class", "tree-item-inner nav-file-title-content"); + attr(div1, "class", "buttons"); + attr(span, "class", "type"); + attr(span, "data-type", span_data_type_value = /*diff*/ + ctx[0].status); + attr(div2, "class", "git-tools"); + attr(div3, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp"); + attr(div3, "data-path", div3_data_path_value = /*diff*/ + ctx[0].vault_path); + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx[3] + ); + attr(div3, "aria-label", div3_aria_label_value = /*diff*/ + ctx[0].vault_path); + toggle_class( + div3, + "is-active", + /*view*/ + ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*diff*/ + ctx[0].vault_path && /*view*/ + ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) + ); + attr(main, "class", "tree-item nav-file svelte-1wbh8tp"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div3); + append2(div3, div0); + append2(div0, t0); + append2(div3, t1); + append2(div3, div2); + append2(div2, div1); + if (if_block) + if_block.m(div1, null); + append2(div2, t2); + append2(div2, span); + append2(span, t3); + if (!mounted) { + dispose = [ + listen(main, "click", stop_propagation( + /*showDiff*/ + ctx[5] + )), + listen(main, "auxclick", stop_propagation( + /*showDiff*/ + ctx[5] + )), + listen( + main, + "focus", + /*focus_handler*/ + ctx[6] + ) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a2, _b; + if (dirty & /*diff*/ + 1 && t0_value !== (t0_value = getDisplayPath( + /*diff*/ + ctx2[0].vault_path + ) + "")) + set_data(t0, t0_value); + if (dirty & /*view, diff*/ + 3) + show_if = /*view*/ + ctx2[1].app.vault.getAbstractFileByPath( + /*diff*/ + ctx2[0].vault_path + ); + if (show_if) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block(ctx2); + if_block.c(); + if_block.m(div1, null); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty & /*diff*/ + 1 && t3_value !== (t3_value = /*diff*/ + ctx2[0].status + "")) + set_data(t3, t3_value); + if (dirty & /*diff*/ + 1 && span_data_type_value !== (span_data_type_value = /*diff*/ + ctx2[0].status)) { + attr(span, "data-type", span_data_type_value); + } + if (dirty & /*diff*/ + 1 && div3_data_path_value !== (div3_data_path_value = /*diff*/ + ctx2[0].vault_path)) { + attr(div3, "data-path", div3_data_path_value); + } + if (dirty & /*side*/ + 8) { + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx2[3] + ); + } + if (dirty & /*diff*/ + 1 && div3_aria_label_value !== (div3_aria_label_value = /*diff*/ + ctx2[0].vault_path)) { + attr(div3, "aria-label", div3_aria_label_value); + } + if (dirty & /*view, diff*/ + 3) { + toggle_class( + div3, + "is-active", + /*view*/ + ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*diff*/ + ctx2[0].vault_path && /*view*/ + ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(main); + } + if (if_block) + if_block.d(); + mounted = false; + run_all(dispose); + } + }; +} +function instance($$self, $$props, $$invalidate) { + let side; + let { diff: diff3 } = $$props; + let { view } = $$props; + let buttons = []; + window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian18.setIcon)(b, b.getAttr("data-icon"))), 0); + function open(event) { + var _a2; + const file = view.app.vault.getAbstractFileByPath(diff3.vault_path); + if (file instanceof import_obsidian18.TFile) { + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file); + } + } + function showDiff(event) { + var _a2; + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.setViewState({ + type: DIFF_VIEW_CONFIG.type, + active: true, + state: { + file: diff3.path, + staged: false, + hash: diff3.hash + } + }); + } + function focus_handler(event) { + bubble.call(this, $$self, event); + } + function div_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[0] = $$value; + $$invalidate(2, buttons); + }); + } + $$self.$$set = ($$props2) => { + if ("diff" in $$props2) + $$invalidate(0, diff3 = $$props2.diff); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 2) { + $: + $$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [diff3, view, buttons, side, open, showDiff, focus_handler, div_binding]; +} +var LogFileComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance, create_fragment, safe_not_equal, { diff: 0, view: 1 }, add_css); + } +}; +var logFileComponent_default = LogFileComponent; + +// src/ui/history/components/logTreeComponent.svelte +init_polyfill_buffer(); +function add_css2(target) { + append_styles(target, "svelte-1lnl15d", "main.svelte-1lnl15d .nav-folder-title-content.svelte-1lnl15d{display:flex;align-items:center}"); +} +function get_each_context(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[8] = list[i]; + return child_ctx; +} +function create_else_block(ctx) { + let div4; + let div3; + let div0; + let t0; + let div1; + let t1; + let div2; + let t2_value = ( + /*entity*/ + ctx[8].title + "" + ); + let t2; + let div3_aria_label_value; + let t3; + let t4; + let current; + let mounted; + let dispose; + function click_handler() { + return ( + /*click_handler*/ + ctx[7]( + /*entity*/ + ctx[8] + ) + ); + } + let if_block = !/*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ] && create_if_block_1(ctx); + return { + c() { + div4 = element("div"); + div3 = element("div"); + div0 = element("div"); + t0 = space(); + div1 = element("div"); + div1.innerHTML = ``; + t1 = space(); + div2 = element("div"); + t2 = text(t2_value); + t3 = space(); + if (if_block) + if_block.c(); + t4 = space(); + attr(div0, "data-icon", "folder"); + set_style(div0, "padding-right", "5px"); + set_style(div0, "display", "flex"); + attr(div1, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + toggle_class( + div1, + "is-collapsed", + /*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ] + ); + attr(div2, "class", "tree-item-inner nav-folder-title-content svelte-1lnl15d"); + attr(div3, "class", "tree-item-self is-clickable nav-folder-title"); + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx[5] + ); + attr(div3, "aria-label", div3_aria_label_value = /*entity*/ + ctx[8].vaultPath); + attr(div4, "class", "tree-item nav-folder"); + toggle_class( + div4, + "is-collapsed", + /*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ] + ); + }, + m(target, anchor) { + insert(target, div4, anchor); + append2(div4, div3); + append2(div3, div0); + append2(div3, t0); + append2(div3, div1); + append2(div3, t1); + append2(div3, div2); + append2(div2, t2); + append2(div4, t3); + if (if_block) + if_block.m(div4, null); + append2(div4, t4); + current = true; + if (!mounted) { + dispose = listen(div3, "click", click_handler); + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty & /*closed, hierarchy*/ + 17) { + toggle_class( + div1, + "is-collapsed", + /*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ] + ); + } + if ((!current || dirty & /*hierarchy*/ + 1) && t2_value !== (t2_value = /*entity*/ + ctx[8].title + "")) + set_data(t2, t2_value); + if (!current || dirty & /*side*/ + 32) { + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx[5] + ); + } + if (!current || dirty & /*hierarchy*/ + 1 && div3_aria_label_value !== (div3_aria_label_value = /*entity*/ + ctx[8].vaultPath)) { + attr(div3, "aria-label", div3_aria_label_value); + } + if (!/*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ]) { + if (if_block) { + if_block.p(ctx, dirty); + if (dirty & /*closed, hierarchy*/ + 17) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block_1(ctx); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div4, t4); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + if (!current || dirty & /*closed, hierarchy*/ + 17) { + toggle_class( + div4, + "is-collapsed", + /*closed*/ + ctx[4][ + /*entity*/ + ctx[8].title + ] + ); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div4); + } + if (if_block) + if_block.d(); + mounted = false; + dispose(); + } + }; +} +function create_if_block2(ctx) { + let div; + let logfilecomponent; + let t; + let current; + logfilecomponent = new logFileComponent_default({ + props: { + diff: ( + /*entity*/ + ctx[8].data + ), + view: ( + /*view*/ + ctx[2] + ) + } + }); + return { + c() { + div = element("div"); + create_component(logfilecomponent.$$.fragment); + t = space(); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(logfilecomponent, div, null); + append2(div, t); + current = true; + }, + p(ctx2, dirty) { + const logfilecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + logfilecomponent_changes.diff = /*entity*/ + ctx2[8].data; + if (dirty & /*view*/ + 4) + logfilecomponent_changes.view = /*view*/ + ctx2[2]; + logfilecomponent.$set(logfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(logfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(logfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(logfilecomponent); + } + }; +} +function create_if_block_1(ctx) { + let div; + let logtreecomponent; + let div_transition; + let current; + logtreecomponent = new LogTreeComponent({ + props: { + hierarchy: ( + /*entity*/ + ctx[8] + ), + plugin: ( + /*plugin*/ + ctx[1] + ), + view: ( + /*view*/ + ctx[2] + ) + } + }); + return { + c() { + div = element("div"); + create_component(logtreecomponent.$$.fragment); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(logtreecomponent, div, null); + current = true; + }, + p(ctx2, dirty) { + const logtreecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + logtreecomponent_changes.hierarchy = /*entity*/ + ctx2[8]; + if (dirty & /*plugin*/ + 2) + logtreecomponent_changes.plugin = /*plugin*/ + ctx2[1]; + if (dirty & /*view*/ + 4) + logtreecomponent_changes.view = /*view*/ + ctx2[2]; + logtreecomponent.$set(logtreecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(logtreecomponent.$$.fragment, local); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(logtreecomponent.$$.fragment, local); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(logtreecomponent); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_each_block(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block2, create_else_block]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*entity*/ + ctx2[8].data + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_blocks[current_block_type_index].d(detaching); + } + }; +} +function create_fragment2(ctx) { + let main; + let current; + let each_value = ensure_array_like( + /*hierarchy*/ + ctx[0].children + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + main = element("main"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(main, "class", "svelte-1lnl15d"); + toggle_class( + main, + "topLevel", + /*topLevel*/ + ctx[3] + ); + }, + m(target, anchor) { + insert(target, main, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(main, null); + } + } + current = true; + }, + p(ctx2, [dirty]) { + if (dirty & /*hierarchy, view, closed, plugin, side, fold*/ + 119) { + each_value = ensure_array_like( + /*hierarchy*/ + ctx2[0].children + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(main, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + if (!current || dirty & /*topLevel*/ + 8) { + toggle_class( + main, + "topLevel", + /*topLevel*/ + ctx2[3] + ); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(main); + } + destroy_each(each_blocks, detaching); + } + }; +} +function instance2($$self, $$props, $$invalidate) { + let side; + let { hierarchy } = $$props; + let { plugin } = $$props; + let { view } = $$props; + let { topLevel = false } = $$props; + const closed = {}; + function fold(item) { + $$invalidate(4, closed[item.title] = !closed[item.title], closed); + } + const click_handler = (entity) => fold(entity); + $$self.$$set = ($$props2) => { + if ("hierarchy" in $$props2) + $$invalidate(0, hierarchy = $$props2.hierarchy); + if ("plugin" in $$props2) + $$invalidate(1, plugin = $$props2.plugin); + if ("view" in $$props2) + $$invalidate(2, view = $$props2.view); + if ("topLevel" in $$props2) + $$invalidate(3, topLevel = $$props2.topLevel); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 4) { + $: + $$invalidate(5, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [hierarchy, plugin, view, topLevel, closed, side, fold, click_handler]; +} +var LogTreeComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2( + this, + options, + instance2, + create_fragment2, + safe_not_equal, + { + hierarchy: 0, + plugin: 1, + view: 2, + topLevel: 3 + }, + add_css2 + ); + } +}; +var logTreeComponent_default = LogTreeComponent; + +// src/ui/history/components/logComponent.svelte +function get_each_context2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[9] = list[i]; + return child_ctx; +} +function create_if_block_4(ctx) { + let div; + let t_value = ( + /*log*/ + ctx[0].refs.join(", ") + "" + ); + let t; + return { + c() { + div = element("div"); + t = text(t_value); + attr(div, "class", "git-ref"); + }, + m(target, anchor) { + insert(target, div, anchor); + append2(div, t); + }, + p(ctx2, dirty) { + if (dirty & /*log*/ + 1 && t_value !== (t_value = /*log*/ + ctx2[0].refs.join(", ") + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(div); + } + } + }; +} +function create_if_block_3(ctx) { + let div; + let t_value = ( + /*authorToString*/ + ctx[7]( + /*log*/ + ctx[0] + ) + "" + ); + let t; + return { + c() { + div = element("div"); + t = text(t_value); + attr(div, "class", "git-author"); + }, + m(target, anchor) { + insert(target, div, anchor); + append2(div, t); + }, + p(ctx2, dirty) { + if (dirty & /*log*/ + 1 && t_value !== (t_value = /*authorToString*/ + ctx2[7]( + /*log*/ + ctx2[0] + ) + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(div); + } + } + }; +} +function create_if_block_2(ctx) { + let div; + let t_value = (0, import_obsidian19.moment)( + /*log*/ + ctx[0].date + ).format( + /*plugin*/ + ctx[3].settings.commitDateFormat + ) + ""; + let t; + return { + c() { + div = element("div"); + t = text(t_value); + attr(div, "class", "git-date"); + }, + m(target, anchor) { + insert(target, div, anchor); + append2(div, t); + }, + p(ctx2, dirty) { + if (dirty & /*log, plugin*/ + 9 && t_value !== (t_value = (0, import_obsidian19.moment)( + /*log*/ + ctx2[0].date + ).format( + /*plugin*/ + ctx2[3].settings.commitDateFormat + ) + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(div); + } + } + }; +} +function create_if_block3(ctx) { + let div; + let current_block_type_index; + let if_block; + let div_transition; + let current; + const if_block_creators = [create_if_block_12, create_else_block2]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*showTree*/ + ctx2[2] + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + if_block.c(); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(if_block); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if_blocks[current_block_type_index].d(); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_else_block2(ctx) { + let each_1_anchor; + let current; + let each_value = ensure_array_like( + /*log*/ + ctx[0].diff.files + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty & /*view, log*/ + 3) { + each_value = ensure_array_like( + /*log*/ + ctx2[0].diff.files + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context2(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_if_block_12(ctx) { + let logtreecomponent; + let current; + logtreecomponent = new logTreeComponent_default({ + props: { + hierarchy: ( + /*logsHierarchy*/ + ctx[6] + ), + plugin: ( + /*plugin*/ + ctx[3] + ), + view: ( + /*view*/ + ctx[1] + ), + topLevel: true + } + }); + return { + c() { + create_component(logtreecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(logtreecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const logtreecomponent_changes = {}; + if (dirty & /*logsHierarchy*/ + 64) + logtreecomponent_changes.hierarchy = /*logsHierarchy*/ + ctx2[6]; + if (dirty & /*plugin*/ + 8) + logtreecomponent_changes.plugin = /*plugin*/ + ctx2[3]; + if (dirty & /*view*/ + 2) + logtreecomponent_changes.view = /*view*/ + ctx2[1]; + logtreecomponent.$set(logtreecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(logtreecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(logtreecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(logtreecomponent, detaching); + } + }; +} +function create_each_block2(ctx) { + let logfilecomponent; + let current; + logfilecomponent = new logFileComponent_default({ + props: { + view: ( + /*view*/ + ctx[1] + ), + diff: ( + /*file*/ + ctx[9] + ) + } + }); + return { + c() { + create_component(logfilecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(logfilecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const logfilecomponent_changes = {}; + if (dirty & /*view*/ + 2) + logfilecomponent_changes.view = /*view*/ + ctx2[1]; + if (dirty & /*log*/ + 1) + logfilecomponent_changes.diff = /*file*/ + ctx2[9]; + logfilecomponent.$set(logfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(logfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(logfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(logfilecomponent, detaching); + } + }; +} +function create_fragment3(ctx) { + var _a2; + let main; + let div4; + let div3; + let div0; + let t0; + let div2; + let t1; + let t2; + let t3; + let div1; + let t4_value = ( + /*log*/ + ctx[0].message + "" + ); + let t4; + let div3_aria_label_value; + let t5; + let current; + let mounted; + let dispose; + let if_block0 = ( + /*log*/ + ctx[0].refs.length > 0 && create_if_block_4(ctx) + ); + let if_block1 = ( + /*plugin*/ + ctx[3].settings.authorInHistoryView != "hide" && /*log*/ + ((_a2 = ctx[0].author) == null ? void 0 : _a2.name) && create_if_block_3(ctx) + ); + let if_block2 = ( + /*plugin*/ + ctx[3].settings.dateInHistoryView && create_if_block_2(ctx) + ); + let if_block3 = !/*isCollapsed*/ + ctx[4] && create_if_block3(ctx); + return { + c() { + var _a3; + main = element("main"); + div4 = element("div"); + div3 = element("div"); + div0 = element("div"); + div0.innerHTML = ``; + t0 = space(); + div2 = element("div"); + if (if_block0) + if_block0.c(); + t1 = space(); + if (if_block1) + if_block1.c(); + t2 = space(); + if (if_block2) + if_block2.c(); + t3 = space(); + div1 = element("div"); + t4 = text(t4_value); + t5 = space(); + if (if_block3) + if_block3.c(); + attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + toggle_class( + div0, + "is-collapsed", + /*isCollapsed*/ + ctx[4] + ); + attr(div1, "class", "tree-item-inner nav-folder-title-content"); + attr(div3, "class", "tree-item-self is-clickable nav-folder-title"); + attr(div3, "aria-label", div3_aria_label_value = `${/*log*/ + ctx[0].refs.length > 0 ? ( + /*log*/ + ctx[0].refs.join(", ") + "\n" + ) : ""}${/*log*/ + (_a3 = ctx[0].author) == null ? void 0 : _a3.name} +${(0, import_obsidian19.moment)( + /*log*/ + ctx[0].date + ).format( + /*plugin*/ + ctx[3].settings.commitDateFormat + )} +${/*log*/ + ctx[0].message}`); + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx[5] + ); + attr(div4, "class", "tree-item nav-folder"); + toggle_class( + div4, + "is-collapsed", + /*isCollapsed*/ + ctx[4] + ); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div4); + append2(div4, div3); + append2(div3, div0); + append2(div3, t0); + append2(div3, div2); + if (if_block0) + if_block0.m(div2, null); + append2(div2, t1); + if (if_block1) + if_block1.m(div2, null); + append2(div2, t2); + if (if_block2) + if_block2.m(div2, null); + append2(div2, t3); + append2(div2, div1); + append2(div1, t4); + append2(div4, t5); + if (if_block3) + if_block3.m(div4, null); + current = true; + if (!mounted) { + dispose = listen( + div3, + "click", + /*click_handler*/ + ctx[8] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a3, _b; + if (!current || dirty & /*isCollapsed*/ + 16) { + toggle_class( + div0, + "is-collapsed", + /*isCollapsed*/ + ctx2[4] + ); + } + if ( + /*log*/ + ctx2[0].refs.length > 0 + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + } else { + if_block0 = create_if_block_4(ctx2); + if_block0.c(); + if_block0.m(div2, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + if ( + /*plugin*/ + ctx2[3].settings.authorInHistoryView != "hide" && /*log*/ + ((_a3 = ctx2[0].author) == null ? void 0 : _a3.name) + ) { + if (if_block1) { + if_block1.p(ctx2, dirty); + } else { + if_block1 = create_if_block_3(ctx2); + if_block1.c(); + if_block1.m(div2, t2); + } + } else if (if_block1) { + if_block1.d(1); + if_block1 = null; + } + if ( + /*plugin*/ + ctx2[3].settings.dateInHistoryView + ) { + if (if_block2) { + if_block2.p(ctx2, dirty); + } else { + if_block2 = create_if_block_2(ctx2); + if_block2.c(); + if_block2.m(div2, t3); + } + } else if (if_block2) { + if_block2.d(1); + if_block2 = null; + } + if ((!current || dirty & /*log*/ + 1) && t4_value !== (t4_value = /*log*/ + ctx2[0].message + "")) + set_data(t4, t4_value); + if (!current || dirty & /*log, plugin*/ + 9 && div3_aria_label_value !== (div3_aria_label_value = `${/*log*/ + ctx2[0].refs.length > 0 ? ( + /*log*/ + ctx2[0].refs.join(", ") + "\n" + ) : ""}${/*log*/ + (_b = ctx2[0].author) == null ? void 0 : _b.name} +${(0, import_obsidian19.moment)( + /*log*/ + ctx2[0].date + ).format( + /*plugin*/ + ctx2[3].settings.commitDateFormat + )} +${/*log*/ + ctx2[0].message}`)) { + attr(div3, "aria-label", div3_aria_label_value); + } + if (!current || dirty & /*side*/ + 32) { + attr( + div3, + "data-tooltip-position", + /*side*/ + ctx2[5] + ); + } + if (!/*isCollapsed*/ + ctx2[4]) { + if (if_block3) { + if_block3.p(ctx2, dirty); + if (dirty & /*isCollapsed*/ + 16) { + transition_in(if_block3, 1); + } + } else { + if_block3 = create_if_block3(ctx2); + if_block3.c(); + transition_in(if_block3, 1); + if_block3.m(div4, null); + } + } else if (if_block3) { + group_outros(); + transition_out(if_block3, 1, 1, () => { + if_block3 = null; + }); + check_outros(); + } + if (!current || dirty & /*isCollapsed*/ + 16) { + toggle_class( + div4, + "is-collapsed", + /*isCollapsed*/ + ctx2[4] + ); + } + }, + i(local) { + if (current) + return; + transition_in(if_block3); + current = true; + }, + o(local) { + transition_out(if_block3); + current = false; + }, + d(detaching) { + if (detaching) { + detach(main); + } + if (if_block0) + if_block0.d(); + if (if_block1) + if_block1.d(); + if (if_block2) + if_block2.d(); + if (if_block3) + if_block3.d(); + mounted = false; + dispose(); + } + }; +} +function instance3($$self, $$props, $$invalidate) { + let logsHierarchy; + let side; + let { log: log2 } = $$props; + let { view } = $$props; + let { showTree } = $$props; + let { plugin } = $$props; + let isCollapsed = true; + function authorToString(log3) { + const name = log3.author.name; + if (plugin.settings.authorInHistoryView == "full") { + return name; + } else if (plugin.settings.authorInHistoryView == "initials") { + const words = name.split(" ").filter((word) => word.length > 0); + return words.map((word) => word[0].toUpperCase()).join(""); + } + } + const click_handler = () => $$invalidate(4, isCollapsed = !isCollapsed); + $$self.$$set = ($$props2) => { + if ("log" in $$props2) + $$invalidate(0, log2 = $$props2.log); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + if ("showTree" in $$props2) + $$invalidate(2, showTree = $$props2.showTree); + if ("plugin" in $$props2) + $$invalidate(3, plugin = $$props2.plugin); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*plugin, log*/ + 9) { + $: + $$invalidate(6, logsHierarchy = { + title: "", + path: "", + vaultPath: "", + children: plugin.gitManager.getTreeStructure(log2.diff.files) + }); + } + if ($$self.$$.dirty & /*view*/ + 2) { + $: + $$invalidate(5, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [ + log2, + view, + showTree, + plugin, + isCollapsed, + side, + logsHierarchy, + authorToString, + click_handler + ]; +} +var LogComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance3, create_fragment3, safe_not_equal, { log: 0, view: 1, showTree: 2, plugin: 3 }); + } +}; +var logComponent_default = LogComponent; + +// src/ui/history/historyView.svelte +function get_each_context3(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[11] = list[i]; + return child_ctx; +} +function create_if_block4(ctx) { + let div1; + let div0; + let current; + let each_value = ensure_array_like( + /*logs*/ + ctx[6] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block3(get_each_context3(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div1 = element("div"); + div0 = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div0, "class", "tree-item-children nav-folder-children"); + attr(div1, "class", "tree-item nav-folder mod-root"); + }, + m(target, anchor) { + insert(target, div1, anchor); + append2(div1, div0); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(div0, null); + } + } + current = true; + }, + p(ctx2, dirty) { + if (dirty & /*view, showTree, logs, plugin*/ + 71) { + each_value = ensure_array_like( + /*logs*/ + ctx2[6] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context3(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block3(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div0, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div1); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_each_block3(ctx) { + let logcomponent; + let current; + logcomponent = new logComponent_default({ + props: { + view: ( + /*view*/ + ctx[1] + ), + showTree: ( + /*showTree*/ + ctx[2] + ), + log: ( + /*log*/ + ctx[11] + ), + plugin: ( + /*plugin*/ + ctx[0] + ) + } + }); + return { + c() { + create_component(logcomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(logcomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const logcomponent_changes = {}; + if (dirty & /*view*/ + 2) + logcomponent_changes.view = /*view*/ + ctx2[1]; + if (dirty & /*showTree*/ + 4) + logcomponent_changes.showTree = /*showTree*/ + ctx2[2]; + if (dirty & /*logs*/ + 64) + logcomponent_changes.log = /*log*/ + ctx2[11]; + if (dirty & /*plugin*/ + 1) + logcomponent_changes.plugin = /*plugin*/ + ctx2[0]; + logcomponent.$set(logcomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(logcomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(logcomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(logcomponent, detaching); + } + }; +} +function create_fragment4(ctx) { + let main; + let div3; + let div2; + let div0; + let t0; + let div1; + let t1; + let div4; + let current; + let mounted; + let dispose; + let if_block = ( + /*logs*/ + ctx[6] && create_if_block4(ctx) + ); + return { + c() { + main = element("main"); + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + t0 = space(); + div1 = element("div"); + t1 = space(); + div4 = element("div"); + if (if_block) + if_block.c(); + attr(div0, "id", "layoutChange"); + attr(div0, "class", "clickable-icon nav-action-button"); + attr(div0, "aria-label", "Change Layout"); + attr(div1, "id", "refresh"); + attr(div1, "class", "clickable-icon nav-action-button"); + attr(div1, "data-icon", "refresh-cw"); + attr(div1, "aria-label", "Refresh"); + set_style(div1, "margin", "1px"); + toggle_class( + div1, + "loading", + /*loading*/ + ctx[4] + ); + attr(div2, "class", "nav-buttons-container"); + attr(div3, "class", "nav-header"); + attr(div4, "class", "nav-files-container"); + set_style(div4, "position", "relative"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div3); + append2(div3, div2); + append2(div2, div0); + ctx[7](div0); + append2(div2, t0); + append2(div2, div1); + ctx[9](div1); + append2(main, t1); + append2(main, div4); + if (if_block) + if_block.m(div4, null); + current = true; + if (!mounted) { + dispose = [ + listen( + div0, + "click", + /*click_handler*/ + ctx[8] + ), + listen(div1, "click", triggerRefresh) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (!current || dirty & /*loading*/ + 16) { + toggle_class( + div1, + "loading", + /*loading*/ + ctx2[4] + ); + } + if ( + /*logs*/ + ctx2[6] + ) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & /*logs*/ + 64) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block4(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div4, null); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(main); + } + ctx[7](null); + ctx[9](null); + if (if_block) + if_block.d(); + mounted = false; + run_all(dispose); + } + }; +} +function triggerRefresh() { + dispatchEvent(new CustomEvent("git-refresh")); +} +function instance4($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { view } = $$props; + let loading; + let buttons = []; + let logs; + let showTree = plugin.settings.treeStructure; + let layoutBtn; + addEventListener("git-view-refresh", refresh); + plugin.app.workspace.onLayoutReady(() => { + window.setTimeout( + () => { + buttons.forEach((btn) => (0, import_obsidian20.setIcon)(btn, btn.getAttr("data-icon"))); + (0, import_obsidian20.setIcon)(layoutBtn, showTree ? "list" : "folder"); + }, + 0 + ); + }); + onDestroy(() => { + removeEventListener("git-view-refresh", refresh); + }); + function refresh() { + return __awaiter(this, void 0, void 0, function* () { + $$invalidate(4, loading = true); + const isSimpleGit = plugin.gitManager instanceof SimpleGit; + $$invalidate(6, logs = yield plugin.gitManager.log(void 0, false, isSimpleGit ? 50 : 10)); + $$invalidate(4, loading = false); + }); + } + function div0_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + layoutBtn = $$value; + $$invalidate(3, layoutBtn); + }); + } + const click_handler = () => { + $$invalidate(2, showTree = !showTree); + $$invalidate(0, plugin.settings.treeStructure = showTree, plugin); + plugin.saveSettings(); + }; + function div1_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[6] = $$value; + $$invalidate(5, buttons); + }); + } + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*layoutBtn, showTree*/ + 12) { + $: { + if (layoutBtn) { + layoutBtn.empty(); + (0, import_obsidian20.setIcon)(layoutBtn, showTree ? "list" : "folder"); + } + } + } + }; + return [ + plugin, + view, + showTree, + layoutBtn, + loading, + buttons, + logs, + div0_binding, + click_handler, + div1_binding + ]; +} +var HistoryView = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance4, create_fragment4, safe_not_equal, { plugin: 0, view: 1 }); + } +}; +var historyView_default = HistoryView; + +// src/ui/history/historyView.ts +var HistoryView2 = class extends import_obsidian21.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.plugin = plugin; + this.hoverPopover = null; + } + getViewType() { + return HISTORY_VIEW_CONFIG.type; + } + getDisplayText() { + return HISTORY_VIEW_CONFIG.name; + } + getIcon() { + return HISTORY_VIEW_CONFIG.icon; + } + onClose() { + return super.onClose(); + } + onOpen() { + this._view = new historyView_default({ + target: this.contentEl, + props: { + plugin: this.plugin, + view: this + } + }); + return super.onOpen(); + } +}; + +// src/ui/modals/branchModal.ts +init_polyfill_buffer(); +var import_obsidian22 = require("obsidian"); +var BranchModal = class extends import_obsidian22.FuzzySuggestModal { + constructor(branches) { + super(app); + this.branches = branches; + this.setPlaceholder("Select branch to checkout"); + } + getItems() { + return this.branches; + } + getItemText(item) { + return item; + } + onChooseItem(item, evt) { + this.resolve(item); + } + open() { + super.open(); + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + async onClose() { + await new Promise((resolve) => setTimeout(resolve, 10)); + if (this.resolve) + this.resolve(void 0); + } +}; + +// src/ui/modals/ignoreModal.ts +init_polyfill_buffer(); +var import_obsidian23 = require("obsidian"); +var IgnoreModal = class extends import_obsidian23.Modal { + constructor(app2, content) { + super(app2); + this.content = content; + this.resolve = null; + } + open() { + super.open(); + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + onOpen() { + const { contentEl, titleEl } = this; + titleEl.setText("Edit .gitignore"); + const div = contentEl.createDiv(); + const text2 = div.createEl("textarea", { + text: this.content, + cls: ["obsidian-git-textarea"], + attr: { rows: 10, cols: 30, wrap: "off" } + }); + div.createEl("button", { + cls: ["mod-cta", "obsidian-git-center-button"], + text: "Save" + }).addEventListener("click", async () => { + this.resolve(text2.value); + this.close(); + }); + } + onClose() { + const { contentEl } = this; + this.resolve(void 0); + contentEl.empty(); + } +}; + +// src/ui/sourceControl/sourceControl.ts +init_polyfill_buffer(); +var import_obsidian30 = require("obsidian"); + +// src/ui/sourceControl/sourceControl.svelte +init_polyfill_buffer(); +var import_obsidian29 = require("obsidian"); + +// src/ui/modals/discardModal.ts +init_polyfill_buffer(); +var import_obsidian24 = require("obsidian"); +var DiscardModal = class extends import_obsidian24.Modal { + constructor(app2, deletion, filename) { + super(app2); + this.deletion = deletion; + this.filename = filename; + this.resolve = null; + } + myOpen() { + this.open(); + return new Promise((resolve) => { + this.resolve = resolve; + }); + } + onOpen() { + const { contentEl, titleEl } = this; + titleEl.setText(`${this.deletion ? "Delete" : "Discard"} this file?`); + contentEl.createEl("p").setText( + `Do you really want to ${this.deletion ? "delete" : "discard the changes of"} "${this.filename}"` + ); + const div = contentEl.createDiv({ cls: "modal-button-container" }); + const discard = div.createEl("button", { + cls: "mod-warning", + text: this.deletion ? "Delete" : "Discard" + }); + discard.addEventListener("click", async () => { + if (this.resolve) + this.resolve(true); + this.close(); + }); + discard.addEventListener("keypress", async () => { + if (this.resolve) + this.resolve(true); + this.close(); + }); + const close = div.createEl("button", { + text: "Cancel" + }); + close.addEventListener("click", () => { + if (this.resolve) + this.resolve(false); + return this.close(); + }); + close.addEventListener("keypress", () => { + if (this.resolve) + this.resolve(false); + return this.close(); + }); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +}; + +// src/ui/sourceControl/components/fileComponent.svelte +init_polyfill_buffer(); +var import_obsidian26 = require("obsidian"); + +// node_modules/.pnpm/obsidian-community-lib@https+++codeload.github.com+Vinzent03+obsidian-community-lib+tar.gz+e6_dmashd4lm54vdqd2gnfngnqe2m/node_modules/obsidian-community-lib/dist/index.js +init_polyfill_buffer(); + +// node_modules/.pnpm/obsidian-community-lib@https+++codeload.github.com+Vinzent03+obsidian-community-lib+tar.gz+e6_dmashd4lm54vdqd2gnfngnqe2m/node_modules/obsidian-community-lib/dist/utils.js +init_polyfill_buffer(); +var feather = __toESM(require_feather()); +var import_obsidian25 = require("obsidian"); +function hoverPreview(event, view, to) { + const targetEl = event.target; + app.workspace.trigger("hover-link", { + event, + source: view.getViewType(), + hoverParent: view, + targetEl, + linktext: to + }); +} + +// src/ui/sourceControl/components/fileComponent.svelte +function add_css3(target) { + append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}"); +} +function create_if_block5(ctx) { + let div; + let mounted; + let dispose; + return { + c() { + div = element("div"); + attr(div, "data-icon", "go-to-file"); + attr(div, "aria-label", "Open File"); + attr(div, "class", "clickable-icon"); + }, + m(target, anchor) { + insert(target, div, anchor); + ctx[11](div); + if (!mounted) { + dispose = [ + listen(div, "auxclick", stop_propagation( + /*open*/ + ctx[5] + )), + listen(div, "click", stop_propagation( + /*open*/ + ctx[5] + )) + ]; + mounted = true; + } + }, + p: noop, + d(detaching) { + if (detaching) { + detach(div); + } + ctx[11](null); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment5(ctx) { + let main; + let div6; + let div0; + let t0_value = getDisplayPath( + /*change*/ + ctx[0].vault_path + ) + ""; + let t0; + let t1; + let div5; + let div3; + let show_if = ( + /*view*/ + ctx[1].app.vault.getAbstractFileByPath( + /*change*/ + ctx[0].vault_path + ) + ); + let t2; + let div1; + let t3; + let div2; + let t4; + let div4; + let t5_value = ( + /*change*/ + ctx[0].working_dir + "" + ); + let t5; + let div4_data_type_value; + let div6_data_path_value; + let div6_aria_label_value; + let mounted; + let dispose; + let if_block = show_if && create_if_block5(ctx); + return { + c() { + var _a2, _b, _c; + main = element("main"); + div6 = element("div"); + div0 = element("div"); + t0 = text(t0_value); + t1 = space(); + div5 = element("div"); + div3 = element("div"); + if (if_block) + if_block.c(); + t2 = space(); + div1 = element("div"); + t3 = space(); + div2 = element("div"); + t4 = space(); + div4 = element("div"); + t5 = text(t5_value); + attr(div0, "class", "tree-item-inner nav-file-title-content"); + attr(div1, "data-icon", "undo"); + attr(div1, "aria-label", "Discard"); + attr(div1, "class", "clickable-icon"); + attr(div2, "data-icon", "plus"); + attr(div2, "aria-label", "Stage"); + attr(div2, "class", "clickable-icon"); + attr(div3, "class", "buttons"); + attr(div4, "class", "type"); + attr(div4, "data-type", div4_data_type_value = /*change*/ + ctx[0].working_dir); + attr(div5, "class", "git-tools"); + attr(div6, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp"); + attr(div6, "data-path", div6_data_path_value = /*change*/ + ctx[0].vault_path); + attr( + div6, + "data-tooltip-position", + /*side*/ + ctx[3] + ); + attr(div6, "aria-label", div6_aria_label_value = /*change*/ + ctx[0].vault_path); + toggle_class( + div6, + "is-active", + /*view*/ + ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/ + ctx[0].vault_path && !/*view*/ + ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && !/*view*/ + ((_c = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged) + ); + attr(main, "class", "tree-item nav-file svelte-1wbh8tp"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div6); + append2(div6, div0); + append2(div0, t0); + append2(div6, t1); + append2(div6, div5); + append2(div5, div3); + if (if_block) + if_block.m(div3, null); + append2(div3, t2); + append2(div3, div1); + ctx[12](div1); + append2(div3, t3); + append2(div3, div2); + ctx[13](div2); + append2(div5, t4); + append2(div5, div4); + append2(div4, t5); + if (!mounted) { + dispose = [ + listen(div1, "click", stop_propagation( + /*discard*/ + ctx[8] + )), + listen(div2, "click", stop_propagation( + /*stage*/ + ctx[6] + )), + listen( + main, + "mouseover", + /*hover*/ + ctx[4] + ), + listen(main, "click", stop_propagation( + /*showDiff*/ + ctx[7] + )), + listen(main, "auxclick", stop_propagation( + /*showDiff*/ + ctx[7] + )), + listen( + main, + "focus", + /*focus_handler*/ + ctx[10] + ) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a2, _b, _c; + if (dirty & /*change*/ + 1 && t0_value !== (t0_value = getDisplayPath( + /*change*/ + ctx2[0].vault_path + ) + "")) + set_data(t0, t0_value); + if (dirty & /*view, change*/ + 3) + show_if = /*view*/ + ctx2[1].app.vault.getAbstractFileByPath( + /*change*/ + ctx2[0].vault_path + ); + if (show_if) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block5(ctx2); + if_block.c(); + if_block.m(div3, t2); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty & /*change*/ + 1 && t5_value !== (t5_value = /*change*/ + ctx2[0].working_dir + "")) + set_data(t5, t5_value); + if (dirty & /*change*/ + 1 && div4_data_type_value !== (div4_data_type_value = /*change*/ + ctx2[0].working_dir)) { + attr(div4, "data-type", div4_data_type_value); + } + if (dirty & /*change*/ + 1 && div6_data_path_value !== (div6_data_path_value = /*change*/ + ctx2[0].vault_path)) { + attr(div6, "data-path", div6_data_path_value); + } + if (dirty & /*side*/ + 8) { + attr( + div6, + "data-tooltip-position", + /*side*/ + ctx2[3] + ); + } + if (dirty & /*change*/ + 1 && div6_aria_label_value !== (div6_aria_label_value = /*change*/ + ctx2[0].vault_path)) { + attr(div6, "aria-label", div6_aria_label_value); + } + if (dirty & /*view, change*/ + 3) { + toggle_class( + div6, + "is-active", + /*view*/ + ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/ + ctx2[0].vault_path && !/*view*/ + ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && !/*view*/ + ((_c = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged) + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(main); + } + if (if_block) + if_block.d(); + ctx[12](null); + ctx[13](null); + mounted = false; + run_all(dispose); + } + }; +} +function instance5($$self, $$props, $$invalidate) { + let side; + let { change } = $$props; + let { view } = $$props; + let { manager } = $$props; + let buttons = []; + window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian26.setIcon)(b, b.getAttr("data-icon"))), 0); + function hover(event) { + if (app.vault.getAbstractFileByPath(change.vault_path)) { + hoverPreview(event, view, change.vault_path); + } + } + function open(event) { + var _a2; + const file = view.app.vault.getAbstractFileByPath(change.vault_path); + console.log(event); + if (file instanceof import_obsidian26.TFile) { + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file); + } + } + function stage() { + manager.stage(change.path, false).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + function showDiff(event) { + var _a2; + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.setViewState({ + type: DIFF_VIEW_CONFIG.type, + active: true, + state: { file: change.path, staged: false } + }); + } + function discard() { + const deleteFile = change.working_dir == "U"; + new DiscardModal(view.app, deleteFile, change.vault_path).myOpen().then((shouldDiscard) => { + if (shouldDiscard === true) { + if (deleteFile) { + view.app.vault.adapter.remove(change.vault_path).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } else { + manager.discard(change.path).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + } + }); + } + function focus_handler(event) { + bubble.call(this, $$self, event); + } + function div_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[1] = $$value; + $$invalidate(2, buttons); + }); + } + function div1_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[0] = $$value; + $$invalidate(2, buttons); + }); + } + function div2_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[2] = $$value; + $$invalidate(2, buttons); + }); + } + $$self.$$set = ($$props2) => { + if ("change" in $$props2) + $$invalidate(0, change = $$props2.change); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + if ("manager" in $$props2) + $$invalidate(9, manager = $$props2.manager); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 2) { + $: + $$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [ + change, + view, + buttons, + side, + hover, + open, + stage, + showDiff, + discard, + manager, + focus_handler, + div_binding, + div1_binding, + div2_binding + ]; +} +var FileComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance5, create_fragment5, safe_not_equal, { change: 0, view: 1, manager: 9 }, add_css3); + } +}; +var fileComponent_default = FileComponent; + +// src/ui/sourceControl/components/pulledFileComponent.svelte +init_polyfill_buffer(); +var import_obsidian27 = require("obsidian"); +function add_css4(target) { + append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}"); +} +function create_fragment6(ctx) { + let main; + let div2; + let div0; + let t0_value = getDisplayPath( + /*change*/ + ctx[0].vault_path + ) + ""; + let t0; + let t1; + let div1; + let span; + let t2_value = ( + /*change*/ + ctx[0].working_dir + "" + ); + let t2; + let span_data_type_value; + let div2_data_path_value; + let div2_aria_label_value; + let mounted; + let dispose; + return { + c() { + main = element("main"); + div2 = element("div"); + div0 = element("div"); + t0 = text(t0_value); + t1 = space(); + div1 = element("div"); + span = element("span"); + t2 = text(t2_value); + attr(div0, "class", "tree-item-inner nav-file-title-content"); + attr(span, "class", "type"); + attr(span, "data-type", span_data_type_value = /*change*/ + ctx[0].working_dir); + attr(div1, "class", "git-tools"); + attr(div2, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp"); + attr(div2, "data-path", div2_data_path_value = /*change*/ + ctx[0].vault_path); + attr( + div2, + "data-tooltip-position", + /*side*/ + ctx[1] + ); + attr(div2, "aria-label", div2_aria_label_value = /*change*/ + ctx[0].vault_path); + attr(main, "class", "tree-item nav-file svelte-1wbh8tp"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div2); + append2(div2, div0); + append2(div0, t0); + append2(div2, t1); + append2(div2, div1); + append2(div1, span); + append2(span, t2); + if (!mounted) { + dispose = [ + listen( + main, + "mouseover", + /*hover*/ + ctx[2] + ), + listen(main, "click", stop_propagation( + /*open*/ + ctx[3] + )), + listen(main, "auxclick", stop_propagation( + /*open*/ + ctx[3] + )), + listen( + main, + "focus", + /*focus_handler*/ + ctx[5] + ) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & /*change*/ + 1 && t0_value !== (t0_value = getDisplayPath( + /*change*/ + ctx2[0].vault_path + ) + "")) + set_data(t0, t0_value); + if (dirty & /*change*/ + 1 && t2_value !== (t2_value = /*change*/ + ctx2[0].working_dir + "")) + set_data(t2, t2_value); + if (dirty & /*change*/ + 1 && span_data_type_value !== (span_data_type_value = /*change*/ + ctx2[0].working_dir)) { + attr(span, "data-type", span_data_type_value); + } + if (dirty & /*change*/ + 1 && div2_data_path_value !== (div2_data_path_value = /*change*/ + ctx2[0].vault_path)) { + attr(div2, "data-path", div2_data_path_value); + } + if (dirty & /*side*/ + 2) { + attr( + div2, + "data-tooltip-position", + /*side*/ + ctx2[1] + ); + } + if (dirty & /*change*/ + 1 && div2_aria_label_value !== (div2_aria_label_value = /*change*/ + ctx2[0].vault_path)) { + attr(div2, "aria-label", div2_aria_label_value); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(main); + } + mounted = false; + run_all(dispose); + } + }; +} +function instance6($$self, $$props, $$invalidate) { + let side; + let { change } = $$props; + let { view } = $$props; + function hover(event) { + if (app.vault.getAbstractFileByPath(change.vault_path)) { + hoverPreview(event, view, change.vault_path); + } + } + function open(event) { + var _a2; + const file = view.app.vault.getAbstractFileByPath(change.vault_path); + if (file instanceof import_obsidian27.TFile) { + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file); + } + } + function focus_handler(event) { + bubble.call(this, $$self, event); + } + $$self.$$set = ($$props2) => { + if ("change" in $$props2) + $$invalidate(0, change = $$props2.change); + if ("view" in $$props2) + $$invalidate(4, view = $$props2.view); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 16) { + $: + $$invalidate(1, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [change, side, hover, open, view, focus_handler]; +} +var PulledFileComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance6, create_fragment6, safe_not_equal, { change: 0, view: 4 }, add_css4); + } +}; +var pulledFileComponent_default = PulledFileComponent; + +// src/ui/sourceControl/components/stagedFileComponent.svelte +init_polyfill_buffer(); +var import_obsidian28 = require("obsidian"); +function add_css5(target) { + append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}"); +} +function create_if_block6(ctx) { + let div; + let mounted; + let dispose; + return { + c() { + div = element("div"); + attr(div, "data-icon", "go-to-file"); + attr(div, "aria-label", "Open File"); + attr(div, "class", "clickable-icon"); + }, + m(target, anchor) { + insert(target, div, anchor); + ctx[10](div); + if (!mounted) { + dispose = listen(div, "click", stop_propagation( + /*open*/ + ctx[5] + )); + mounted = true; + } + }, + p: noop, + d(detaching) { + if (detaching) { + detach(div); + } + ctx[10](null); + mounted = false; + dispose(); + } + }; +} +function create_fragment7(ctx) { + let main; + let div5; + let div0; + let t0_value = getDisplayPath( + /*change*/ + ctx[0].vault_path + ) + ""; + let t0; + let t1; + let div4; + let div2; + let show_if = ( + /*view*/ + ctx[1].app.vault.getAbstractFileByPath( + /*change*/ + ctx[0].vault_path + ) + ); + let t2; + let div1; + let t3; + let div3; + let t4_value = ( + /*change*/ + ctx[0].index + "" + ); + let t4; + let div3_data_type_value; + let div5_data_path_value; + let div5_aria_label_value; + let mounted; + let dispose; + let if_block = show_if && create_if_block6(ctx); + return { + c() { + var _a2, _b, _c; + main = element("main"); + div5 = element("div"); + div0 = element("div"); + t0 = text(t0_value); + t1 = space(); + div4 = element("div"); + div2 = element("div"); + if (if_block) + if_block.c(); + t2 = space(); + div1 = element("div"); + t3 = space(); + div3 = element("div"); + t4 = text(t4_value); + attr(div0, "class", "tree-item-inner nav-file-title-content"); + attr(div1, "data-icon", "minus"); + attr(div1, "aria-label", "Unstage"); + attr(div1, "class", "clickable-icon"); + attr(div2, "class", "buttons"); + attr(div3, "class", "type"); + attr(div3, "data-type", div3_data_type_value = /*change*/ + ctx[0].index); + attr(div4, "class", "git-tools"); + attr(div5, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp"); + attr(div5, "data-path", div5_data_path_value = /*change*/ + ctx[0].vault_path); + attr( + div5, + "data-tooltip-position", + /*side*/ + ctx[3] + ); + attr(div5, "aria-label", div5_aria_label_value = /*change*/ + ctx[0].vault_path); + toggle_class( + div5, + "is-active", + /*view*/ + ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/ + ctx[0].vault_path && !/*view*/ + ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && /*view*/ + ((_c = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged) + ); + attr(main, "class", "tree-item nav-file svelte-1wbh8tp"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div5); + append2(div5, div0); + append2(div0, t0); + append2(div5, t1); + append2(div5, div4); + append2(div4, div2); + if (if_block) + if_block.m(div2, null); + append2(div2, t2); + append2(div2, div1); + ctx[11](div1); + append2(div4, t3); + append2(div4, div3); + append2(div3, t4); + if (!mounted) { + dispose = [ + listen(div1, "click", stop_propagation( + /*unstage*/ + ctx[7] + )), + listen( + main, + "mouseover", + /*hover*/ + ctx[4] + ), + listen( + main, + "focus", + /*focus_handler*/ + ctx[9] + ), + listen(main, "click", stop_propagation( + /*showDiff*/ + ctx[6] + )), + listen(main, "auxclick", stop_propagation( + /*showDiff*/ + ctx[6] + )) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a2, _b, _c; + if (dirty & /*change*/ + 1 && t0_value !== (t0_value = getDisplayPath( + /*change*/ + ctx2[0].vault_path + ) + "")) + set_data(t0, t0_value); + if (dirty & /*view, change*/ + 3) + show_if = /*view*/ + ctx2[1].app.vault.getAbstractFileByPath( + /*change*/ + ctx2[0].vault_path + ); + if (show_if) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block6(ctx2); + if_block.c(); + if_block.m(div2, t2); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty & /*change*/ + 1 && t4_value !== (t4_value = /*change*/ + ctx2[0].index + "")) + set_data(t4, t4_value); + if (dirty & /*change*/ + 1 && div3_data_type_value !== (div3_data_type_value = /*change*/ + ctx2[0].index)) { + attr(div3, "data-type", div3_data_type_value); + } + if (dirty & /*change*/ + 1 && div5_data_path_value !== (div5_data_path_value = /*change*/ + ctx2[0].vault_path)) { + attr(div5, "data-path", div5_data_path_value); + } + if (dirty & /*side*/ + 8) { + attr( + div5, + "data-tooltip-position", + /*side*/ + ctx2[3] + ); + } + if (dirty & /*change*/ + 1 && div5_aria_label_value !== (div5_aria_label_value = /*change*/ + ctx2[0].vault_path)) { + attr(div5, "aria-label", div5_aria_label_value); + } + if (dirty & /*view, change*/ + 3) { + toggle_class( + div5, + "is-active", + /*view*/ + ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/ + ctx2[0].vault_path && !/*view*/ + ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && /*view*/ + ((_c = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged) + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(main); + } + if (if_block) + if_block.d(); + ctx[11](null); + mounted = false; + run_all(dispose); + } + }; +} +function instance7($$self, $$props, $$invalidate) { + let side; + let { change } = $$props; + let { view } = $$props; + let { manager } = $$props; + let buttons = []; + window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian28.setIcon)(b, b.getAttr("data-icon"))), 0); + function hover(event) { + if (app.vault.getAbstractFileByPath(change.vault_path)) { + hoverPreview(event, view, change.vault_path); + } + } + function open(event) { + var _a2; + const file = view.app.vault.getAbstractFileByPath(change.vault_path); + if (file instanceof import_obsidian28.TFile) { + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file); + } + } + function showDiff(event) { + var _a2; + (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.setViewState({ + type: DIFF_VIEW_CONFIG.type, + active: true, + state: { file: change.path, staged: true } + }); + } + function unstage() { + manager.unstage(change.path, false).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + function focus_handler(event) { + bubble.call(this, $$self, event); + } + function div_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[1] = $$value; + $$invalidate(2, buttons); + }); + } + function div1_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[0] = $$value; + $$invalidate(2, buttons); + }); + } + $$self.$$set = ($$props2) => { + if ("change" in $$props2) + $$invalidate(0, change = $$props2.change); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + if ("manager" in $$props2) + $$invalidate(8, manager = $$props2.manager); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 2) { + $: + $$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [ + change, + view, + buttons, + side, + hover, + open, + showDiff, + unstage, + manager, + focus_handler, + div_binding, + div1_binding + ]; +} +var StagedFileComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance7, create_fragment7, safe_not_equal, { change: 0, view: 1, manager: 8 }, add_css5); + } +}; +var stagedFileComponent_default = StagedFileComponent; + +// src/ui/sourceControl/components/treeComponent.svelte +init_polyfill_buffer(); +function add_css6(target) { + append_styles(target, "svelte-hup5mn", "main.svelte-hup5mn .nav-folder-title.svelte-hup5mn{align-items:center}"); +} +function get_each_context4(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[15] = list[i]; + return child_ctx; +} +function create_else_block3(ctx) { + let div7; + let div6; + let div0; + let t0; + let div1; + let t1; + let div2; + let t2_value = ( + /*entity*/ + ctx[15].title + "" + ); + let t2; + let t3; + let div5; + let div4; + let t4; + let div3; + let div6_aria_label_value; + let t5; + let t6; + let current; + let mounted; + let dispose; + function select_block_type_2(ctx2, dirty) { + if ( + /*fileType*/ + ctx2[3] == 0 /* staged */ + ) + return create_if_block_5; + return create_else_block_1; + } + let current_block_type = select_block_type_2(ctx, -1); + let if_block0 = current_block_type(ctx); + let if_block1 = !/*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ] && create_if_block_42(ctx); + function click_handler_3() { + return ( + /*click_handler_3*/ + ctx[14]( + /*entity*/ + ctx[15] + ) + ); + } + return { + c() { + div7 = element("div"); + div6 = element("div"); + div0 = element("div"); + t0 = space(); + div1 = element("div"); + div1.innerHTML = ``; + t1 = space(); + div2 = element("div"); + t2 = text(t2_value); + t3 = space(); + div5 = element("div"); + div4 = element("div"); + if_block0.c(); + t4 = space(); + div3 = element("div"); + t5 = space(); + if (if_block1) + if_block1.c(); + t6 = space(); + attr(div0, "data-icon", "folder"); + set_style(div0, "padding-right", "5px"); + set_style(div0, "display", "flex"); + attr(div1, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + toggle_class( + div1, + "is-collapsed", + /*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ] + ); + attr(div2, "class", "tree-item-inner nav-folder-title-content"); + set_style(div3, "width", "11px"); + attr(div4, "class", "buttons"); + attr(div5, "class", "git-tools"); + attr(div6, "class", "tree-item-self is-clickable nav-folder-title svelte-hup5mn"); + attr( + div6, + "data-tooltip-position", + /*side*/ + ctx[6] + ); + attr(div6, "aria-label", div6_aria_label_value = /*entity*/ + ctx[15].vaultPath); + attr(div7, "class", "tree-item nav-folder"); + toggle_class( + div7, + "is-collapsed", + /*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ] + ); + }, + m(target, anchor) { + insert(target, div7, anchor); + append2(div7, div6); + append2(div6, div0); + append2(div6, t0); + append2(div6, div1); + append2(div6, t1); + append2(div6, div2); + append2(div2, t2); + append2(div6, t3); + append2(div6, div5); + append2(div5, div4); + if_block0.m(div4, null); + append2(div4, t4); + append2(div4, div3); + append2(div7, t5); + if (if_block1) + if_block1.m(div7, null); + append2(div7, t6); + current = true; + if (!mounted) { + dispose = listen(div7, "click", stop_propagation(click_handler_3)); + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty & /*closed, hierarchy*/ + 33) { + toggle_class( + div1, + "is-collapsed", + /*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ] + ); + } + if ((!current || dirty & /*hierarchy*/ + 1) && t2_value !== (t2_value = /*entity*/ + ctx[15].title + "")) + set_data(t2, t2_value); + if (current_block_type === (current_block_type = select_block_type_2(ctx, dirty)) && if_block0) { + if_block0.p(ctx, dirty); + } else { + if_block0.d(1); + if_block0 = current_block_type(ctx); + if (if_block0) { + if_block0.c(); + if_block0.m(div4, t4); + } + } + if (!current || dirty & /*side*/ + 64) { + attr( + div6, + "data-tooltip-position", + /*side*/ + ctx[6] + ); + } + if (!current || dirty & /*hierarchy*/ + 1 && div6_aria_label_value !== (div6_aria_label_value = /*entity*/ + ctx[15].vaultPath)) { + attr(div6, "aria-label", div6_aria_label_value); + } + if (!/*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ]) { + if (if_block1) { + if_block1.p(ctx, dirty); + if (dirty & /*closed, hierarchy*/ + 33) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block_42(ctx); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(div7, t6); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + if (!current || dirty & /*closed, hierarchy*/ + 33) { + toggle_class( + div7, + "is-collapsed", + /*closed*/ + ctx[5][ + /*entity*/ + ctx[15].title + ] + ); + } + }, + i(local) { + if (current) + return; + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div7); + } + if_block0.d(); + if (if_block1) + if_block1.d(); + mounted = false; + dispose(); + } + }; +} +function create_if_block7(ctx) { + let div; + let current_block_type_index; + let if_block; + let t; + let current; + const if_block_creators = [create_if_block_13, create_if_block_22, create_if_block_32]; + const if_blocks = []; + function select_block_type_1(ctx2, dirty) { + if ( + /*fileType*/ + ctx2[3] == 0 /* staged */ + ) + return 0; + if ( + /*fileType*/ + ctx2[3] == 1 /* changed */ + ) + return 1; + if ( + /*fileType*/ + ctx2[3] == 2 /* pulled */ + ) + return 2; + return -1; + } + if (~(current_block_type_index = select_block_type_1(ctx, -1))) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + } + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + t = space(); + }, + m(target, anchor) { + insert(target, div, anchor); + if (~current_block_type_index) { + if_blocks[current_block_type_index].m(div, null); + } + append2(div, t); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type_1(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if (~current_block_type_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } + } else { + if (if_block) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + } + if (~current_block_type_index) { + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(div, t); + } else { + if_block = null; + } + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if (~current_block_type_index) { + if_blocks[current_block_type_index].d(); + } + } + }; +} +function create_else_block_1(ctx) { + let div0; + let t; + let div1; + let mounted; + let dispose; + function click_handler_1() { + return ( + /*click_handler_1*/ + ctx[12]( + /*entity*/ + ctx[15] + ) + ); + } + function click_handler_2() { + return ( + /*click_handler_2*/ + ctx[13]( + /*entity*/ + ctx[15] + ) + ); + } + return { + c() { + div0 = element("div"); + div0.innerHTML = ``; + t = space(); + div1 = element("div"); + div1.innerHTML = ``; + attr(div0, "data-icon", "undo"); + attr(div0, "aria-label", "Discard"); + attr(div0, "class", "clickable-icon"); + attr(div1, "data-icon", "plus"); + attr(div1, "aria-label", "Stage"); + attr(div1, "class", "clickable-icon"); + }, + m(target, anchor) { + insert(target, div0, anchor); + insert(target, t, anchor); + insert(target, div1, anchor); + if (!mounted) { + dispose = [ + listen(div0, "click", stop_propagation(click_handler_1)), + listen(div1, "click", stop_propagation(click_handler_2)) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + }, + d(detaching) { + if (detaching) { + detach(div0); + detach(t); + detach(div1); + } + mounted = false; + run_all(dispose); + } + }; +} +function create_if_block_5(ctx) { + let div; + let mounted; + let dispose; + function click_handler() { + return ( + /*click_handler*/ + ctx[11]( + /*entity*/ + ctx[15] + ) + ); + } + return { + c() { + div = element("div"); + div.innerHTML = ``; + attr(div, "data-icon", "minus"); + attr(div, "aria-label", "Unstage"); + attr(div, "class", "clickable-icon"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (!mounted) { + dispose = listen(div, "click", stop_propagation(click_handler)); + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + }, + d(detaching) { + if (detaching) { + detach(div); + } + mounted = false; + dispose(); + } + }; +} +function create_if_block_42(ctx) { + let div; + let treecomponent; + let div_transition; + let current; + treecomponent = new TreeComponent({ + props: { + hierarchy: ( + /*entity*/ + ctx[15] + ), + plugin: ( + /*plugin*/ + ctx[1] + ), + view: ( + /*view*/ + ctx[2] + ), + fileType: ( + /*fileType*/ + ctx[3] + ) + } + }); + return { + c() { + div = element("div"); + create_component(treecomponent.$$.fragment); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(treecomponent, div, null); + current = true; + }, + p(ctx2, dirty) { + const treecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + treecomponent_changes.hierarchy = /*entity*/ + ctx2[15]; + if (dirty & /*plugin*/ + 2) + treecomponent_changes.plugin = /*plugin*/ + ctx2[1]; + if (dirty & /*view*/ + 4) + treecomponent_changes.view = /*view*/ + ctx2[2]; + if (dirty & /*fileType*/ + 8) + treecomponent_changes.fileType = /*fileType*/ + ctx2[3]; + treecomponent.$set(treecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(treecomponent.$$.fragment, local); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(treecomponent.$$.fragment, local); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(treecomponent); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_if_block_32(ctx) { + let pulledfilecomponent; + let current; + pulledfilecomponent = new pulledFileComponent_default({ + props: { + change: ( + /*entity*/ + ctx[15].data + ), + view: ( + /*view*/ + ctx[2] + ) + } + }); + return { + c() { + create_component(pulledfilecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(pulledfilecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const pulledfilecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + pulledfilecomponent_changes.change = /*entity*/ + ctx2[15].data; + if (dirty & /*view*/ + 4) + pulledfilecomponent_changes.view = /*view*/ + ctx2[2]; + pulledfilecomponent.$set(pulledfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(pulledfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(pulledfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(pulledfilecomponent, detaching); + } + }; +} +function create_if_block_22(ctx) { + let filecomponent; + let current; + filecomponent = new fileComponent_default({ + props: { + change: ( + /*entity*/ + ctx[15].data + ), + manager: ( + /*plugin*/ + ctx[1].gitManager + ), + view: ( + /*view*/ + ctx[2] + ) + } + }); + return { + c() { + create_component(filecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(filecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const filecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + filecomponent_changes.change = /*entity*/ + ctx2[15].data; + if (dirty & /*plugin*/ + 2) + filecomponent_changes.manager = /*plugin*/ + ctx2[1].gitManager; + if (dirty & /*view*/ + 4) + filecomponent_changes.view = /*view*/ + ctx2[2]; + filecomponent.$set(filecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(filecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(filecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(filecomponent, detaching); + } + }; +} +function create_if_block_13(ctx) { + let stagedfilecomponent; + let current; + stagedfilecomponent = new stagedFileComponent_default({ + props: { + change: ( + /*entity*/ + ctx[15].data + ), + manager: ( + /*plugin*/ + ctx[1].gitManager + ), + view: ( + /*view*/ + ctx[2] + ) + } + }); + return { + c() { + create_component(stagedfilecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(stagedfilecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const stagedfilecomponent_changes = {}; + if (dirty & /*hierarchy*/ + 1) + stagedfilecomponent_changes.change = /*entity*/ + ctx2[15].data; + if (dirty & /*plugin*/ + 2) + stagedfilecomponent_changes.manager = /*plugin*/ + ctx2[1].gitManager; + if (dirty & /*view*/ + 4) + stagedfilecomponent_changes.view = /*view*/ + ctx2[2]; + stagedfilecomponent.$set(stagedfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(stagedfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(stagedfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(stagedfilecomponent, detaching); + } + }; +} +function create_each_block4(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block7, create_else_block3]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*entity*/ + ctx2[15].data + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_blocks[current_block_type_index].d(detaching); + } + }; +} +function create_fragment8(ctx) { + let main; + let current; + let each_value = ensure_array_like( + /*hierarchy*/ + ctx[0].children + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block4(get_each_context4(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + main = element("main"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(main, "class", "svelte-hup5mn"); + toggle_class( + main, + "topLevel", + /*topLevel*/ + ctx[4] + ); + }, + m(target, anchor) { + insert(target, main, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(main, null); + } + } + current = true; + }, + p(ctx2, [dirty]) { + if (dirty & /*hierarchy, plugin, view, fileType, closed, fold, side, unstage, stage, discard*/ + 2031) { + each_value = ensure_array_like( + /*hierarchy*/ + ctx2[0].children + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context4(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block4(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(main, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + if (!current || dirty & /*topLevel*/ + 16) { + toggle_class( + main, + "topLevel", + /*topLevel*/ + ctx2[4] + ); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(main); + } + destroy_each(each_blocks, detaching); + } + }; +} +function instance8($$self, $$props, $$invalidate) { + let side; + let { hierarchy } = $$props; + let { plugin } = $$props; + let { view } = $$props; + let { fileType } = $$props; + let { topLevel = false } = $$props; + const closed = {}; + function stage(path2) { + plugin.gitManager.stageAll({ dir: path2 }).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + function unstage(path2) { + plugin.gitManager.unstageAll({ dir: path2 }).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + function discard(item) { + new DiscardModal(view.app, false, item.vaultPath).myOpen().then((shouldDiscard) => { + if (shouldDiscard === true) { + plugin.gitManager.discardAll({ + dir: item.path, + status: plugin.cachedStatus + }).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + }); + } + }); + } + function fold(item) { + $$invalidate(5, closed[item.title] = !closed[item.title], closed); + } + const click_handler = (entity) => unstage(entity.path); + const click_handler_1 = (entity) => discard(entity); + const click_handler_2 = (entity) => stage(entity.path); + const click_handler_3 = (entity) => fold(entity); + $$self.$$set = ($$props2) => { + if ("hierarchy" in $$props2) + $$invalidate(0, hierarchy = $$props2.hierarchy); + if ("plugin" in $$props2) + $$invalidate(1, plugin = $$props2.plugin); + if ("view" in $$props2) + $$invalidate(2, view = $$props2.view); + if ("fileType" in $$props2) + $$invalidate(3, fileType = $$props2.fileType); + if ("topLevel" in $$props2) + $$invalidate(4, topLevel = $$props2.topLevel); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*view*/ + 4) { + $: + $$invalidate(6, side = view.leaf.getRoot().side == "left" ? "right" : "left"); + } + }; + return [ + hierarchy, + plugin, + view, + fileType, + topLevel, + closed, + side, + stage, + unstage, + discard, + fold, + click_handler, + click_handler_1, + click_handler_2, + click_handler_3 + ]; +} +var TreeComponent = class extends SvelteComponent { + constructor(options) { + super(); + init2( + this, + options, + instance8, + create_fragment8, + safe_not_equal, + { + hierarchy: 0, + plugin: 1, + view: 2, + fileType: 3, + topLevel: 4 + }, + add_css6 + ); + } +}; +var treeComponent_default = TreeComponent; + +// src/ui/sourceControl/sourceControl.svelte +function add_css7(target) { + append_styles(target, "svelte-11adhly", `.commit-msg-input.svelte-11adhly.svelte-11adhly{width:100%;overflow:hidden;resize:none;padding:7px 5px;background-color:var(--background-modifier-form-field)}.git-commit-msg.svelte-11adhly.svelte-11adhly{position:relative;padding:0;width:calc(100% - var(--size-4-8));margin:4px auto}main.svelte-11adhly .git-tools .files-count.svelte-11adhly{padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center}.nav-folder-title.svelte-11adhly.svelte-11adhly{align-items:center}.git-commit-msg-clear-button.svelte-11adhly.svelte-11adhly{position:absolute;background:transparent;border-radius:50%;color:var(--search-clear-button-color);cursor:var(--cursor);top:-4px;right:2px;bottom:0px;line-height:0;height:var(--input-height);width:28px;margin:auto;padding:0 0;text-align:center;display:flex;justify-content:center;align-items:center;transition:color 0.15s ease-in-out}.git-commit-msg-clear-button.svelte-11adhly.svelte-11adhly:after{content:"";height:var(--search-clear-button-size);width:var(--search-clear-button-size);display:block;background-color:currentColor;mask-image:url("data:image/svg+xml,");mask-repeat:no-repeat;-webkit-mask-image:url("data:image/svg+xml,");-webkit-mask-repeat:no-repeat}`); +} +function get_each_context5(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[40] = list[i]; + return child_ctx; +} +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[40] = list[i]; + return child_ctx; +} +function get_each_context_2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[45] = list[i]; + return child_ctx; +} +function create_if_block_8(ctx) { + let div; + let div_aria_label_value; + let mounted; + let dispose; + return { + c() { + div = element("div"); + attr(div, "class", "git-commit-msg-clear-button svelte-11adhly"); + attr(div, "aria-label", div_aria_label_value = "Clear"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (!mounted) { + dispose = listen( + div, + "click", + /*click_handler_1*/ + ctx[33] + ); + mounted = true; + } + }, + p: noop, + d(detaching) { + if (detaching) { + detach(div); + } + mounted = false; + dispose(); + } + }; +} +function create_if_block8(ctx) { + let div18; + let div17; + let div7; + let div6; + let div0; + let t0; + let div1; + let t2; + let div5; + let div3; + let div2; + let t3; + let div4; + let t4_value = ( + /*status*/ + ctx[6].staged.length + "" + ); + let t4; + let t5; + let t6; + let div16; + let div15; + let div8; + let t7; + let div9; + let t9; + let div14; + let div12; + let div10; + let t10; + let div11; + let t11; + let div13; + let t12_value = ( + /*status*/ + ctx[6].changed.length + "" + ); + let t12; + let t13; + let t14; + let current; + let mounted; + let dispose; + let if_block0 = ( + /*stagedOpen*/ + ctx[13] && create_if_block_6(ctx) + ); + let if_block1 = ( + /*changesOpen*/ + ctx[12] && create_if_block_43(ctx) + ); + let if_block2 = ( + /*lastPulledFiles*/ + ctx[7].length > 0 && create_if_block_14(ctx) + ); + return { + c() { + div18 = element("div"); + div17 = element("div"); + div7 = element("div"); + div6 = element("div"); + div0 = element("div"); + div0.innerHTML = ``; + t0 = space(); + div1 = element("div"); + div1.textContent = "Staged Changes"; + t2 = space(); + div5 = element("div"); + div3 = element("div"); + div2 = element("div"); + div2.innerHTML = ``; + t3 = space(); + div4 = element("div"); + t4 = text(t4_value); + t5 = space(); + if (if_block0) + if_block0.c(); + t6 = space(); + div16 = element("div"); + div15 = element("div"); + div8 = element("div"); + div8.innerHTML = ``; + t7 = space(); + div9 = element("div"); + div9.textContent = "Changes"; + t9 = space(); + div14 = element("div"); + div12 = element("div"); + div10 = element("div"); + div10.innerHTML = ``; + t10 = space(); + div11 = element("div"); + div11.innerHTML = ``; + t11 = space(); + div13 = element("div"); + t12 = text(t12_value); + t13 = space(); + if (if_block1) + if_block1.c(); + t14 = space(); + if (if_block2) + if_block2.c(); + attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + toggle_class(div0, "is-collapsed", !/*stagedOpen*/ + ctx[13]); + attr(div1, "class", "tree-item-inner nav-folder-title-content"); + attr(div2, "data-icon", "minus"); + attr(div2, "aria-label", "Unstage"); + attr(div2, "class", "clickable-icon"); + attr(div3, "class", "buttons"); + attr(div4, "class", "files-count svelte-11adhly"); + attr(div5, "class", "git-tools"); + attr(div6, "class", "tree-item-self is-clickable nav-folder-title svelte-11adhly"); + attr(div7, "class", "staged tree-item nav-folder"); + toggle_class(div7, "is-collapsed", !/*stagedOpen*/ + ctx[13]); + attr(div8, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + toggle_class(div8, "is-collapsed", !/*changesOpen*/ + ctx[12]); + attr(div9, "class", "tree-item-inner nav-folder-title-content"); + attr(div10, "data-icon", "undo"); + attr(div10, "aria-label", "Discard"); + attr(div10, "class", "clickable-icon"); + attr(div11, "data-icon", "plus"); + attr(div11, "aria-label", "Stage"); + attr(div11, "class", "clickable-icon"); + attr(div12, "class", "buttons"); + attr(div13, "class", "files-count svelte-11adhly"); + attr(div14, "class", "git-tools"); + attr(div15, "class", "tree-item-self is-clickable nav-folder-title svelte-11adhly"); + attr(div16, "class", "changes tree-item nav-folder"); + toggle_class(div16, "is-collapsed", !/*changesOpen*/ + ctx[12]); + attr(div17, "class", "tree-item-children nav-folder-children"); + attr(div18, "class", "tree-item nav-folder mod-root"); + }, + m(target, anchor) { + insert(target, div18, anchor); + append2(div18, div17); + append2(div17, div7); + append2(div7, div6); + append2(div6, div0); + append2(div6, t0); + append2(div6, div1); + append2(div6, t2); + append2(div6, div5); + append2(div5, div3); + append2(div3, div2); + ctx[34](div2); + append2(div5, t3); + append2(div5, div4); + append2(div4, t4); + append2(div7, t5); + if (if_block0) + if_block0.m(div7, null); + append2(div17, t6); + append2(div17, div16); + append2(div16, div15); + append2(div15, div8); + append2(div15, t7); + append2(div15, div9); + append2(div15, t9); + append2(div15, div14); + append2(div14, div12); + append2(div12, div10); + append2(div12, t10); + append2(div12, div11); + ctx[36](div11); + append2(div14, t11); + append2(div14, div13); + append2(div13, t12); + append2(div16, t13); + if (if_block1) + if_block1.m(div16, null); + append2(div17, t14); + if (if_block2) + if_block2.m(div17, null); + current = true; + if (!mounted) { + dispose = [ + listen(div2, "click", stop_propagation( + /*unstageAll*/ + ctx[19] + )), + listen( + div6, + "click", + /*click_handler_2*/ + ctx[35] + ), + listen(div10, "click", stop_propagation( + /*discard*/ + ctx[22] + )), + listen(div11, "click", stop_propagation( + /*stageAll*/ + ctx[18] + )), + listen( + div15, + "click", + /*click_handler_3*/ + ctx[37] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (!current || dirty[0] & /*stagedOpen*/ + 8192) { + toggle_class(div0, "is-collapsed", !/*stagedOpen*/ + ctx2[13]); + } + if ((!current || dirty[0] & /*status*/ + 64) && t4_value !== (t4_value = /*status*/ + ctx2[6].staged.length + "")) + set_data(t4, t4_value); + if ( + /*stagedOpen*/ + ctx2[13] + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + if (dirty[0] & /*stagedOpen*/ + 8192) { + transition_in(if_block0, 1); + } + } else { + if_block0 = create_if_block_6(ctx2); + if_block0.c(); + transition_in(if_block0, 1); + if_block0.m(div7, null); + } + } else if (if_block0) { + group_outros(); + transition_out(if_block0, 1, 1, () => { + if_block0 = null; + }); + check_outros(); + } + if (!current || dirty[0] & /*stagedOpen*/ + 8192) { + toggle_class(div7, "is-collapsed", !/*stagedOpen*/ + ctx2[13]); + } + if (!current || dirty[0] & /*changesOpen*/ + 4096) { + toggle_class(div8, "is-collapsed", !/*changesOpen*/ + ctx2[12]); + } + if ((!current || dirty[0] & /*status*/ + 64) && t12_value !== (t12_value = /*status*/ + ctx2[6].changed.length + "")) + set_data(t12, t12_value); + if ( + /*changesOpen*/ + ctx2[12] + ) { + if (if_block1) { + if_block1.p(ctx2, dirty); + if (dirty[0] & /*changesOpen*/ + 4096) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block_43(ctx2); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(div16, null); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + if (!current || dirty[0] & /*changesOpen*/ + 4096) { + toggle_class(div16, "is-collapsed", !/*changesOpen*/ + ctx2[12]); + } + if ( + /*lastPulledFiles*/ + ctx2[7].length > 0 + ) { + if (if_block2) { + if_block2.p(ctx2, dirty); + if (dirty[0] & /*lastPulledFiles*/ + 128) { + transition_in(if_block2, 1); + } + } else { + if_block2 = create_if_block_14(ctx2); + if_block2.c(); + transition_in(if_block2, 1); + if_block2.m(div17, null); + } + } else if (if_block2) { + group_outros(); + transition_out(if_block2, 1, 1, () => { + if_block2 = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block0); + transition_in(if_block1); + transition_in(if_block2); + current = true; + }, + o(local) { + transition_out(if_block0); + transition_out(if_block1); + transition_out(if_block2); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div18); + } + ctx[34](null); + if (if_block0) + if_block0.d(); + ctx[36](null); + if (if_block1) + if_block1.d(); + if (if_block2) + if_block2.d(); + mounted = false; + run_all(dispose); + } + }; +} +function create_if_block_6(ctx) { + let div; + let current_block_type_index; + let if_block; + let div_transition; + let current; + const if_block_creators = [create_if_block_7, create_else_block_2]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*showTree*/ + ctx2[3] + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, [-1, -1]); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + if_block.c(); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(if_block); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if_blocks[current_block_type_index].d(); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_else_block_2(ctx) { + let each_1_anchor; + let current; + let each_value_2 = ensure_array_like( + /*status*/ + ctx[6].staged + ); + let each_blocks = []; + for (let i = 0; i < each_value_2.length; i += 1) { + each_blocks[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty[0] & /*status, view, plugin*/ + 67) { + each_value_2 = ensure_array_like( + /*status*/ + ctx2[6].staged + ); + let i; + for (i = 0; i < each_value_2.length; i += 1) { + const child_ctx = get_each_context_2(ctx2, each_value_2, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block_2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value_2.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_2.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_if_block_7(ctx) { + let treecomponent; + let current; + treecomponent = new treeComponent_default({ + props: { + hierarchy: ( + /*stagedHierarchy*/ + ctx[10] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + view: ( + /*view*/ + ctx[1] + ), + fileType: 0 /* staged */, + topLevel: true + } + }); + return { + c() { + create_component(treecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(treecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const treecomponent_changes = {}; + if (dirty[0] & /*stagedHierarchy*/ + 1024) + treecomponent_changes.hierarchy = /*stagedHierarchy*/ + ctx2[10]; + if (dirty[0] & /*plugin*/ + 1) + treecomponent_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty[0] & /*view*/ + 2) + treecomponent_changes.view = /*view*/ + ctx2[1]; + treecomponent.$set(treecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(treecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(treecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(treecomponent, detaching); + } + }; +} +function create_each_block_2(ctx) { + let stagedfilecomponent; + let current; + stagedfilecomponent = new stagedFileComponent_default({ + props: { + change: ( + /*stagedFile*/ + ctx[45] + ), + view: ( + /*view*/ + ctx[1] + ), + manager: ( + /*plugin*/ + ctx[0].gitManager + ) + } + }); + return { + c() { + create_component(stagedfilecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(stagedfilecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const stagedfilecomponent_changes = {}; + if (dirty[0] & /*status*/ + 64) + stagedfilecomponent_changes.change = /*stagedFile*/ + ctx2[45]; + if (dirty[0] & /*view*/ + 2) + stagedfilecomponent_changes.view = /*view*/ + ctx2[1]; + if (dirty[0] & /*plugin*/ + 1) + stagedfilecomponent_changes.manager = /*plugin*/ + ctx2[0].gitManager; + stagedfilecomponent.$set(stagedfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(stagedfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(stagedfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(stagedfilecomponent, detaching); + } + }; +} +function create_if_block_43(ctx) { + let div; + let current_block_type_index; + let if_block; + let div_transition; + let current; + const if_block_creators = [create_if_block_52, create_else_block_12]; + const if_blocks = []; + function select_block_type_1(ctx2, dirty) { + if ( + /*showTree*/ + ctx2[3] + ) + return 0; + return 1; + } + current_block_type_index = select_block_type_1(ctx, [-1, -1]); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + if_block.c(); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type_1(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(if_block); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if_blocks[current_block_type_index].d(); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_else_block_12(ctx) { + let each_1_anchor; + let current; + let each_value_1 = ensure_array_like( + /*status*/ + ctx[6].changed + ); + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty[0] & /*status, view, plugin*/ + 67) { + each_value_1 = ensure_array_like( + /*status*/ + ctx2[6].changed + ); + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_1(ctx2, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block_1(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value_1.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_1.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_if_block_52(ctx) { + let treecomponent; + let current; + treecomponent = new treeComponent_default({ + props: { + hierarchy: ( + /*changeHierarchy*/ + ctx[9] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + view: ( + /*view*/ + ctx[1] + ), + fileType: 1 /* changed */, + topLevel: true + } + }); + return { + c() { + create_component(treecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(treecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const treecomponent_changes = {}; + if (dirty[0] & /*changeHierarchy*/ + 512) + treecomponent_changes.hierarchy = /*changeHierarchy*/ + ctx2[9]; + if (dirty[0] & /*plugin*/ + 1) + treecomponent_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty[0] & /*view*/ + 2) + treecomponent_changes.view = /*view*/ + ctx2[1]; + treecomponent.$set(treecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(treecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(treecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(treecomponent, detaching); + } + }; +} +function create_each_block_1(ctx) { + let filecomponent; + let current; + filecomponent = new fileComponent_default({ + props: { + change: ( + /*change*/ + ctx[40] + ), + view: ( + /*view*/ + ctx[1] + ), + manager: ( + /*plugin*/ + ctx[0].gitManager + ) + } + }); + filecomponent.$on("git-refresh", triggerRefresh2); + return { + c() { + create_component(filecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(filecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const filecomponent_changes = {}; + if (dirty[0] & /*status*/ + 64) + filecomponent_changes.change = /*change*/ + ctx2[40]; + if (dirty[0] & /*view*/ + 2) + filecomponent_changes.view = /*view*/ + ctx2[1]; + if (dirty[0] & /*plugin*/ + 1) + filecomponent_changes.manager = /*plugin*/ + ctx2[0].gitManager; + filecomponent.$set(filecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(filecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(filecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(filecomponent, detaching); + } + }; +} +function create_if_block_14(ctx) { + let div3; + let div2; + let div0; + let t0; + let div1; + let t2; + let span; + let t3_value = ( + /*lastPulledFiles*/ + ctx[7].length + "" + ); + let t3; + let t4; + let current; + let mounted; + let dispose; + let if_block = ( + /*lastPulledFilesOpen*/ + ctx[14] && create_if_block_23(ctx) + ); + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + div0.innerHTML = ``; + t0 = space(); + div1 = element("div"); + div1.textContent = "Recently Pulled Files"; + t2 = space(); + span = element("span"); + t3 = text(t3_value); + t4 = space(); + if (if_block) + if_block.c(); + attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon"); + attr(div1, "class", "tree-item-inner nav-folder-title-content"); + attr(span, "class", "tree-item-flair"); + attr(div2, "class", "tree-item-self is-clickable nav-folder-title svelte-11adhly"); + attr(div3, "class", "pulled nav-folder"); + toggle_class(div3, "is-collapsed", !/*lastPulledFilesOpen*/ + ctx[14]); + }, + m(target, anchor) { + insert(target, div3, anchor); + append2(div3, div2); + append2(div2, div0); + append2(div2, t0); + append2(div2, div1); + append2(div2, t2); + append2(div2, span); + append2(span, t3); + append2(div3, t4); + if (if_block) + if_block.m(div3, null); + current = true; + if (!mounted) { + dispose = listen( + div2, + "click", + /*click_handler_4*/ + ctx[38] + ); + mounted = true; + } + }, + p(ctx2, dirty) { + if ((!current || dirty[0] & /*lastPulledFiles*/ + 128) && t3_value !== (t3_value = /*lastPulledFiles*/ + ctx2[7].length + "")) + set_data(t3, t3_value); + if ( + /*lastPulledFilesOpen*/ + ctx2[14] + ) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty[0] & /*lastPulledFilesOpen*/ + 16384) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block_23(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div3, null); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + if (!current || dirty[0] & /*lastPulledFilesOpen*/ + 16384) { + toggle_class(div3, "is-collapsed", !/*lastPulledFilesOpen*/ + ctx2[14]); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div3); + } + if (if_block) + if_block.d(); + mounted = false; + dispose(); + } + }; +} +function create_if_block_23(ctx) { + let div; + let current_block_type_index; + let if_block; + let div_transition; + let current; + const if_block_creators = [create_if_block_33, create_else_block4]; + const if_blocks = []; + function select_block_type_2(ctx2, dirty) { + if ( + /*showTree*/ + ctx2[3] + ) + return 0; + return 1; + } + current_block_type_index = select_block_type_2(ctx, [-1, -1]); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + if_block.c(); + attr(div, "class", "tree-item-children nav-folder-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type_2(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block = if_blocks[current_block_type_index]; + if (!if_block) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + if (local) { + add_render_callback(() => { + if (!current) + return; + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true); + div_transition.run(1); + }); + } + current = true; + }, + o(local) { + transition_out(if_block); + if (local) { + if (!div_transition) + div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false); + div_transition.run(0); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if_blocks[current_block_type_index].d(); + if (detaching && div_transition) + div_transition.end(); + } + }; +} +function create_else_block4(ctx) { + let each_1_anchor; + let current; + let each_value = ensure_array_like( + /*lastPulledFiles*/ + ctx[7] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block5(get_each_context5(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty[0] & /*lastPulledFiles, view*/ + 130) { + each_value = ensure_array_like( + /*lastPulledFiles*/ + ctx2[7] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context5(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block5(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_if_block_33(ctx) { + let treecomponent; + let current; + treecomponent = new treeComponent_default({ + props: { + hierarchy: ( + /*lastPulledFilesHierarchy*/ + ctx[11] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + view: ( + /*view*/ + ctx[1] + ), + fileType: 2 /* pulled */, + topLevel: true + } + }); + return { + c() { + create_component(treecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(treecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const treecomponent_changes = {}; + if (dirty[0] & /*lastPulledFilesHierarchy*/ + 2048) + treecomponent_changes.hierarchy = /*lastPulledFilesHierarchy*/ + ctx2[11]; + if (dirty[0] & /*plugin*/ + 1) + treecomponent_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty[0] & /*view*/ + 2) + treecomponent_changes.view = /*view*/ + ctx2[1]; + treecomponent.$set(treecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(treecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(treecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(treecomponent, detaching); + } + }; +} +function create_each_block5(ctx) { + let pulledfilecomponent; + let current; + pulledfilecomponent = new pulledFileComponent_default({ + props: { + change: ( + /*change*/ + ctx[40] + ), + view: ( + /*view*/ + ctx[1] + ) + } + }); + pulledfilecomponent.$on("git-refresh", triggerRefresh2); + return { + c() { + create_component(pulledfilecomponent.$$.fragment); + }, + m(target, anchor) { + mount_component(pulledfilecomponent, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const pulledfilecomponent_changes = {}; + if (dirty[0] & /*lastPulledFiles*/ + 128) + pulledfilecomponent_changes.change = /*change*/ + ctx2[40]; + if (dirty[0] & /*view*/ + 2) + pulledfilecomponent_changes.view = /*view*/ + ctx2[1]; + pulledfilecomponent.$set(pulledfilecomponent_changes); + }, + i(local) { + if (current) + return; + transition_in(pulledfilecomponent.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(pulledfilecomponent.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(pulledfilecomponent, detaching); + } + }; +} +function create_fragment9(ctx) { + let main; + let div9; + let div8; + let div0; + let t0; + let div1; + let t1; + let div2; + let t2; + let div3; + let t3; + let div4; + let t4; + let div5; + let t5; + let div6; + let t6; + let div7; + let t7; + let div10; + let textarea; + let t8; + let t9; + let div11; + let main_data_type_value; + let current; + let mounted; + let dispose; + let if_block0 = ( + /*commitMessage*/ + ctx[2] && create_if_block_8(ctx) + ); + let if_block1 = ( + /*status*/ + ctx[6] && /*stagedHierarchy*/ + ctx[10] && /*changeHierarchy*/ + ctx[9] && create_if_block8(ctx) + ); + return { + c() { + main = element("main"); + div9 = element("div"); + div8 = element("div"); + div0 = element("div"); + t0 = space(); + div1 = element("div"); + t1 = space(); + div2 = element("div"); + t2 = space(); + div3 = element("div"); + t3 = space(); + div4 = element("div"); + t4 = space(); + div5 = element("div"); + t5 = space(); + div6 = element("div"); + t6 = space(); + div7 = element("div"); + t7 = space(); + div10 = element("div"); + textarea = element("textarea"); + t8 = space(); + if (if_block0) + if_block0.c(); + t9 = space(); + div11 = element("div"); + if (if_block1) + if_block1.c(); + attr(div0, "id", "backup-btn"); + attr(div0, "data-icon", "arrow-up-circle"); + attr(div0, "class", "clickable-icon nav-action-button"); + attr(div0, "aria-label", "Backup"); + attr(div1, "id", "commit-btn"); + attr(div1, "data-icon", "check"); + attr(div1, "class", "clickable-icon nav-action-button"); + attr(div1, "aria-label", "Commit"); + attr(div2, "id", "stage-all"); + attr(div2, "class", "clickable-icon nav-action-button"); + attr(div2, "data-icon", "plus-circle"); + attr(div2, "aria-label", "Stage all"); + attr(div3, "id", "unstage-all"); + attr(div3, "class", "clickable-icon nav-action-button"); + attr(div3, "data-icon", "minus-circle"); + attr(div3, "aria-label", "Unstage all"); + attr(div4, "id", "push"); + attr(div4, "class", "clickable-icon nav-action-button"); + attr(div4, "data-icon", "upload"); + attr(div4, "aria-label", "Push"); + attr(div5, "id", "pull"); + attr(div5, "class", "clickable-icon nav-action-button"); + attr(div5, "data-icon", "download"); + attr(div5, "aria-label", "Pull"); + attr(div6, "id", "layoutChange"); + attr(div6, "class", "clickable-icon nav-action-button"); + attr(div6, "aria-label", "Change Layout"); + attr(div7, "id", "refresh"); + attr(div7, "class", "clickable-icon nav-action-button"); + attr(div7, "data-icon", "refresh-cw"); + attr(div7, "aria-label", "Refresh"); + set_style(div7, "margin", "1px"); + toggle_class( + div7, + "loading", + /*loading*/ + ctx[5] + ); + attr(div8, "class", "nav-buttons-container"); + attr(div9, "class", "nav-header"); + attr( + textarea, + "rows", + /*rows*/ + ctx[15] + ); + attr(textarea, "class", "commit-msg-input svelte-11adhly"); + attr(textarea, "spellcheck", "true"); + attr(textarea, "placeholder", "Commit Message"); + attr(div10, "class", "git-commit-msg svelte-11adhly"); + attr(div11, "class", "nav-files-container"); + set_style(div11, "position", "relative"); + attr(main, "data-type", main_data_type_value = SOURCE_CONTROL_VIEW_CONFIG.type); + attr(main, "class", "svelte-11adhly"); + }, + m(target, anchor) { + insert(target, main, anchor); + append2(main, div9); + append2(div9, div8); + append2(div8, div0); + ctx[23](div0); + append2(div8, t0); + append2(div8, div1); + ctx[24](div1); + append2(div8, t1); + append2(div8, div2); + ctx[25](div2); + append2(div8, t2); + append2(div8, div3); + ctx[26](div3); + append2(div8, t3); + append2(div8, div4); + ctx[27](div4); + append2(div8, t4); + append2(div8, div5); + ctx[28](div5); + append2(div8, t5); + append2(div8, div6); + ctx[29](div6); + append2(div8, t6); + append2(div8, div7); + ctx[31](div7); + append2(main, t7); + append2(main, div10); + append2(div10, textarea); + set_input_value( + textarea, + /*commitMessage*/ + ctx[2] + ); + append2(div10, t8); + if (if_block0) + if_block0.m(div10, null); + append2(main, t9); + append2(main, div11); + if (if_block1) + if_block1.m(div11, null); + current = true; + if (!mounted) { + dispose = [ + listen( + div0, + "click", + /*backup*/ + ctx[17] + ), + listen( + div1, + "click", + /*commit*/ + ctx[16] + ), + listen( + div2, + "click", + /*stageAll*/ + ctx[18] + ), + listen( + div3, + "click", + /*unstageAll*/ + ctx[19] + ), + listen( + div4, + "click", + /*push*/ + ctx[20] + ), + listen( + div5, + "click", + /*pull*/ + ctx[21] + ), + listen( + div6, + "click", + /*click_handler*/ + ctx[30] + ), + listen(div7, "click", triggerRefresh2), + listen( + textarea, + "input", + /*textarea_input_handler*/ + ctx[32] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (!current || dirty[0] & /*loading*/ + 32) { + toggle_class( + div7, + "loading", + /*loading*/ + ctx2[5] + ); + } + if (!current || dirty[0] & /*rows*/ + 32768) { + attr( + textarea, + "rows", + /*rows*/ + ctx2[15] + ); + } + if (dirty[0] & /*commitMessage*/ + 4) { + set_input_value( + textarea, + /*commitMessage*/ + ctx2[2] + ); + } + if ( + /*commitMessage*/ + ctx2[2] + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + } else { + if_block0 = create_if_block_8(ctx2); + if_block0.c(); + if_block0.m(div10, null); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + if ( + /*status*/ + ctx2[6] && /*stagedHierarchy*/ + ctx2[10] && /*changeHierarchy*/ + ctx2[9] + ) { + if (if_block1) { + if_block1.p(ctx2, dirty); + if (dirty[0] & /*status, stagedHierarchy, changeHierarchy*/ + 1600) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block8(ctx2); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(div11, null); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(main); + } + ctx[23](null); + ctx[24](null); + ctx[25](null); + ctx[26](null); + ctx[27](null); + ctx[28](null); + ctx[29](null); + ctx[31](null); + if (if_block0) + if_block0.d(); + if (if_block1) + if_block1.d(); + mounted = false; + run_all(dispose); + } + }; +} +function triggerRefresh2() { + dispatchEvent(new CustomEvent("git-refresh")); +} +function instance9($$self, $$props, $$invalidate) { + let rows; + let { plugin } = $$props; + let { view } = $$props; + let loading; + let status2; + let lastPulledFiles = []; + let commitMessage = plugin.settings.commitMessage; + let buttons = []; + let changeHierarchy; + let stagedHierarchy; + let lastPulledFilesHierarchy; + let changesOpen = true; + let stagedOpen = true; + let lastPulledFilesOpen = true; + let showTree = plugin.settings.treeStructure; + let layoutBtn; + addEventListener("git-view-refresh", refresh); + plugin.app.workspace.onLayoutReady(() => { + window.setTimeout( + () => { + buttons.forEach((btn) => (0, import_obsidian29.setIcon)(btn, btn.getAttr("data-icon"))); + (0, import_obsidian29.setIcon)(layoutBtn, showTree ? "list" : "folder"); + }, + 0 + ); + }); + onDestroy(() => { + removeEventListener("git-view-refresh", refresh); + }); + function commit2() { + return __awaiter(this, void 0, void 0, function* () { + $$invalidate(5, loading = true); + if (status2) { + if (yield plugin.hasTooBigFiles(status2.staged)) { + plugin.setState(0 /* idle */); + return false; + } + plugin.promiseQueue.addTask(() => plugin.gitManager.commit({ message: commitMessage }).then(() => { + if (commitMessage !== plugin.settings.commitMessage) { + $$invalidate(2, commitMessage = ""); + } + plugin.setUpAutoBackup(); + }).finally(triggerRefresh2)); + } + }); + } + function backup() { + return __awaiter(this, void 0, void 0, function* () { + $$invalidate(5, loading = true); + if (status2) { + plugin.promiseQueue.addTask(() => plugin.createBackup(false, false, commitMessage).then(() => { + if (commitMessage !== plugin.settings.commitMessage) { + $$invalidate(2, commitMessage = ""); + } + }).finally(triggerRefresh2)); + } + }); + } + function refresh() { + return __awaiter(this, void 0, void 0, function* () { + if (!plugin.gitReady) { + $$invalidate(6, status2 = void 0); + return; + } + const unPushedCommits = yield plugin.gitManager.getUnpushedCommits(); + buttons.forEach((btn) => { + var _a2, _b; + if (import_obsidian29.Platform.isMobile) { + btn.removeClass("button-border"); + if (btn.id == "push" && unPushedCommits > 0) { + btn.addClass("button-border"); + } + } else { + (_a2 = btn.firstElementChild) === null || _a2 === void 0 ? void 0 : _a2.removeAttribute("color"); + if (btn.id == "push" && unPushedCommits > 0) { + (_b = btn.firstElementChild) === null || _b === void 0 ? void 0 : _b.setAttr("color", "var(--text-accent)"); + } + } + }); + $$invalidate(6, status2 = plugin.cachedStatus); + if (plugin.lastPulledFiles && plugin.lastPulledFiles != lastPulledFiles) { + $$invalidate(7, lastPulledFiles = plugin.lastPulledFiles); + $$invalidate(11, lastPulledFilesHierarchy = { + title: "", + path: "", + vaultPath: "", + children: plugin.gitManager.getTreeStructure(lastPulledFiles) + }); + } + if (status2) { + const sort = (a, b) => { + return a.vault_path.split("/").last().localeCompare(getDisplayPath(b.vault_path)); + }; + status2.changed.sort(sort); + status2.staged.sort(sort); + if (status2.changed.length + status2.staged.length > 500) { + $$invalidate(6, status2 = void 0); + if (!plugin.loading) { + plugin.displayError("Too many changes to display"); + } + } else { + $$invalidate(9, changeHierarchy = { + title: "", + path: "", + vaultPath: "", + children: plugin.gitManager.getTreeStructure(status2.changed) + }); + $$invalidate(10, stagedHierarchy = { + title: "", + path: "", + vaultPath: "", + children: plugin.gitManager.getTreeStructure(status2.staged) + }); + } + } else { + $$invalidate(9, changeHierarchy = void 0); + $$invalidate(10, stagedHierarchy = void 0); + } + $$invalidate(5, loading = plugin.loading); + }); + } + function stageAll() { + $$invalidate(5, loading = true); + plugin.promiseQueue.addTask(() => plugin.gitManager.stageAll({ status: status2 }).finally(triggerRefresh2)); + } + function unstageAll() { + $$invalidate(5, loading = true); + plugin.promiseQueue.addTask(() => plugin.gitManager.unstageAll({ status: status2 }).finally(triggerRefresh2)); + } + function push2() { + $$invalidate(5, loading = true); + plugin.promiseQueue.addTask(() => plugin.push().finally(triggerRefresh2)); + } + function pull2() { + $$invalidate(5, loading = true); + plugin.promiseQueue.addTask(() => plugin.pullChangesFromRemote().finally(triggerRefresh2)); + } + function discard() { + new DiscardModal(view.app, false, plugin.gitManager.getRelativeVaultPath("/")).myOpen().then((shouldDiscard) => { + if (shouldDiscard === true) { + plugin.promiseQueue.addTask(() => plugin.gitManager.discardAll({ status: plugin.cachedStatus }).finally(() => { + dispatchEvent(new CustomEvent("git-refresh")); + })); + } + }); + } + function div0_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[5] = $$value; + $$invalidate(8, buttons); + }); + } + function div1_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[0] = $$value; + $$invalidate(8, buttons); + }); + } + function div2_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[1] = $$value; + $$invalidate(8, buttons); + }); + } + function div3_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[2] = $$value; + $$invalidate(8, buttons); + }); + } + function div4_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[3] = $$value; + $$invalidate(8, buttons); + }); + } + function div5_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[4] = $$value; + $$invalidate(8, buttons); + }); + } + function div6_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + layoutBtn = $$value; + $$invalidate(4, layoutBtn); + }); + } + const click_handler = () => { + $$invalidate(3, showTree = !showTree); + $$invalidate(0, plugin.settings.treeStructure = showTree, plugin); + plugin.saveSettings(); + }; + function div7_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[6] = $$value; + $$invalidate(8, buttons); + }); + } + function textarea_input_handler() { + commitMessage = this.value; + $$invalidate(2, commitMessage); + } + const click_handler_1 = () => $$invalidate(2, commitMessage = ""); + function div2_binding_1($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[8] = $$value; + $$invalidate(8, buttons); + }); + } + const click_handler_2 = () => $$invalidate(13, stagedOpen = !stagedOpen); + function div11_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + buttons[9] = $$value; + $$invalidate(8, buttons); + }); + } + const click_handler_3 = () => $$invalidate(12, changesOpen = !changesOpen); + const click_handler_4 = () => $$invalidate(14, lastPulledFilesOpen = !lastPulledFilesOpen); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("view" in $$props2) + $$invalidate(1, view = $$props2.view); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty[0] & /*layoutBtn, showTree*/ + 24) { + $: { + if (layoutBtn) { + layoutBtn.empty(); + (0, import_obsidian29.setIcon)(layoutBtn, showTree ? "list" : "folder"); + } + } + } + if ($$self.$$.dirty[0] & /*commitMessage*/ + 4) { + $: + $$invalidate(15, rows = (commitMessage.match(/\n/g) || []).length + 1 || 1); + } + }; + return [ + plugin, + view, + commitMessage, + showTree, + layoutBtn, + loading, + status2, + lastPulledFiles, + buttons, + changeHierarchy, + stagedHierarchy, + lastPulledFilesHierarchy, + changesOpen, + stagedOpen, + lastPulledFilesOpen, + rows, + commit2, + backup, + stageAll, + unstageAll, + push2, + pull2, + discard, + div0_binding, + div1_binding, + div2_binding, + div3_binding, + div4_binding, + div5_binding, + div6_binding, + click_handler, + div7_binding, + textarea_input_handler, + click_handler_1, + div2_binding_1, + click_handler_2, + div11_binding, + click_handler_3, + click_handler_4 + ]; +} +var SourceControl = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance9, create_fragment9, safe_not_equal, { plugin: 0, view: 1 }, add_css7, [-1, -1]); + } +}; +var sourceControl_default = SourceControl; + +// src/ui/sourceControl/sourceControl.ts +var GitView = class extends import_obsidian30.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.plugin = plugin; + this.hoverPopover = null; + } + getViewType() { + return SOURCE_CONTROL_VIEW_CONFIG.type; + } + getDisplayText() { + return SOURCE_CONTROL_VIEW_CONFIG.name; + } + getIcon() { + return SOURCE_CONTROL_VIEW_CONFIG.icon; + } + onClose() { + return super.onClose(); + } + onOpen() { + this._view = new sourceControl_default({ + target: this.contentEl, + props: { + plugin: this.plugin, + view: this + } + }); + return super.onOpen(); + } +}; + +// src/ui/statusBar/branchStatusBar.ts +init_polyfill_buffer(); +var BranchStatusBar = class { + constructor(statusBarEl, plugin) { + this.statusBarEl = statusBarEl; + this.plugin = plugin; + this.statusBarEl.addClass("mod-clickable"); + this.statusBarEl.onClickEvent((e) => { + this.plugin.switchBranch(); + }); + } + async display() { + if (this.plugin.gitReady) { + const branchInfo = await this.plugin.gitManager.branchInfo(); + if (branchInfo.current != void 0) { + this.statusBarEl.setText(branchInfo.current); + } else { + this.statusBarEl.empty(); + } + } else { + this.statusBarEl.empty(); + } + } +}; + +// src/main.ts +var ObsidianGit = class extends import_obsidian31.Plugin { + constructor() { + super(...arguments); + this.gitReady = false; + this.promiseQueue = new PromiseQueue(); + this.conflictOutputFile = "conflict-files-obsidian-git.md"; + this.offlineMode = false; + this.loading = false; + this.lineAuthoringFeature = new LineAuthoringFeature(this); + } + setState(state) { + var _a2; + this.state = state; + (_a2 = this.statusBar) == null ? void 0 : _a2.display(); + } + async updateCachedStatus() { + this.cachedStatus = await this.gitManager.status(); + return this.cachedStatus; + } + async refresh() { + const gitView = this.app.workspace.getLeavesOfType( + SOURCE_CONTROL_VIEW_CONFIG.type + ); + const historyView = this.app.workspace.getLeavesOfType( + HISTORY_VIEW_CONFIG.type + ); + if (this.settings.changedFilesInStatusBar || gitView.length > 0 || historyView.length > 0) { + this.loading = true; + dispatchEvent(new CustomEvent("git-view-refresh")); + await this.updateCachedStatus(); + this.loading = false; + dispatchEvent(new CustomEvent("git-view-refresh")); + } + } + async refreshUpdatedHead() { + this.lineAuthoringFeature.refreshLineAuthorViews(); + } + async onload() { + console.log("loading " + this.manifest.name + " plugin"); + pluginRef.plugin = this; + this.localStorage = new LocalStorageSettings(this); + this.localStorage.migrate(); + await this.loadSettings(); + this.migrateSettings(); + this.settingsTab = new ObsidianGitSettingsTab(this.app, this); + this.addSettingTab(this.settingsTab); + if (!this.localStorage.getPluginDisabled()) { + this.loadPlugin(); + } + } + async loadPlugin() { + addEventListener("git-refresh", this.refresh.bind(this)); + addEventListener("git-head-update", this.refreshUpdatedHead.bind(this)); + this.registerView(SOURCE_CONTROL_VIEW_CONFIG.type, (leaf) => { + return new GitView(leaf, this); + }); + this.registerView(HISTORY_VIEW_CONFIG.type, (leaf) => { + return new HistoryView2(leaf, this); + }); + this.registerView(DIFF_VIEW_CONFIG.type, (leaf) => { + return new DiffView(leaf, this); + }); + this.lineAuthoringFeature.onLoadPlugin(); + this.app.workspace.registerHoverLinkSource( + SOURCE_CONTROL_VIEW_CONFIG.type, + { + display: "Git View", + defaultMod: true + } + ); + this.setRefreshDebouncer(); + this.addCommand({ + id: "edit-gitignore", + name: "Edit .gitignore", + callback: async () => { + const path2 = this.gitManager.getRelativeVaultPath(".gitignore"); + if (!await this.app.vault.adapter.exists(path2)) { + this.app.vault.adapter.write(path2, ""); + } + const content = await this.app.vault.adapter.read(path2); + const modal = new IgnoreModal(this.app, content); + const res = await modal.open(); + if (res !== void 0) { + await this.app.vault.adapter.write(path2, res); + this.refresh(); + } + } + }); + this.addCommand({ + id: "open-git-view", + name: "Open source control view", + callback: async () => { + const leafs = this.app.workspace.getLeavesOfType( + SOURCE_CONTROL_VIEW_CONFIG.type + ); + let leaf; + if (leafs.length === 0) { + leaf = this.app.workspace.getRightLeaf(false); + await leaf.setViewState({ + type: SOURCE_CONTROL_VIEW_CONFIG.type + }); + } else { + leaf = leafs.first(); + } + this.app.workspace.revealLeaf(leaf); + dispatchEvent(new CustomEvent("git-refresh")); + } + }); + this.addCommand({ + id: "open-history-view", + name: "Open history view", + callback: async () => { + const leafs = this.app.workspace.getLeavesOfType( + HISTORY_VIEW_CONFIG.type + ); + let leaf; + if (leafs.length === 0) { + leaf = this.app.workspace.getRightLeaf(false); + await leaf.setViewState({ + type: HISTORY_VIEW_CONFIG.type + }); + } else { + leaf = leafs.first(); + } + this.app.workspace.revealLeaf(leaf); + dispatchEvent(new CustomEvent("git-refresh")); + } + }); + this.addCommand({ + id: "open-diff-view", + name: "Open diff view", + checkCallback: (checking) => { + var _a2; + const file = this.app.workspace.getActiveFile(); + if (checking) { + return file !== null; + } else { + (_a2 = getNewLeaf()) == null ? void 0 : _a2.setViewState({ + type: DIFF_VIEW_CONFIG.type, + active: true, + state: { + staged: false, + file: this.gitManager.getRelativeRepoPath( + file.path, + true + ) + } + }); + } + } + }); + this.addCommand({ + id: "view-file-on-github", + name: "Open file on GitHub", + editorCallback: (editor, { file }) => { + if (file) + return openLineInGitHub(editor, file, this.gitManager); + } + }); + this.addCommand({ + id: "view-history-on-github", + name: "Open file history on GitHub", + editorCallback: (_, { file }) => { + if (file) + return openHistoryInGitHub(file, this.gitManager); + } + }); + this.addCommand({ + id: "pull", + name: "Pull", + callback: () => this.promiseQueue.addTask(() => this.pullChangesFromRemote()) + }); + this.addCommand({ + id: "fetch", + name: "fetch", + callback: () => this.promiseQueue.addTask(() => this.fetch()) + }); + this.addCommand({ + id: "switch-to-remote-branch", + name: "Switch to remote branch", + callback: () => this.promiseQueue.addTask(() => this.switchRemoteBranch()) + }); + this.addCommand({ + id: "add-to-gitignore", + name: "Add file to gitignore", + checkCallback: (checking) => { + const file = this.app.workspace.getActiveFile(); + if (checking) { + return file !== null; + } else { + this.app.vault.adapter.append( + this.gitManager.getRelativeVaultPath(".gitignore"), + "\n" + this.gitManager.getRelativeRepoPath( + file.path, + true + ) + ).then(() => { + this.refresh(); + }); + } + } + }); + this.addCommand({ + id: "push", + name: "Create backup", + callback: () => this.promiseQueue.addTask(() => this.createBackup(false)) + }); + this.addCommand({ + id: "backup-and-close", + name: "Create backup and close", + callback: () => this.promiseQueue.addTask(async () => { + await this.createBackup(false); + window.close(); + }) + }); + this.addCommand({ + id: "commit-push-specified-message", + name: "Create backup with specific message", + callback: () => this.promiseQueue.addTask(() => this.createBackup(false, true)) + }); + this.addCommand({ + id: "commit", + name: "Commit all changes", + callback: () => this.promiseQueue.addTask( + () => this.commit({ fromAutoBackup: false }) + ) + }); + this.addCommand({ + id: "commit-specified-message", + name: "Commit all changes with specific message", + callback: () => this.promiseQueue.addTask( + () => this.commit({ + fromAutoBackup: false, + requestCustomMessage: true + }) + ) + }); + this.addCommand({ + id: "commit-staged", + name: "Commit staged", + callback: () => this.promiseQueue.addTask( + () => this.commit({ + fromAutoBackup: false, + requestCustomMessage: false, + onlyStaged: true + }) + ) + }); + if (import_obsidian31.Platform.isDesktopApp) { + this.addCommand({ + id: "commit-amend-staged-specified-message", + name: "Commit Amend", + callback: () => this.promiseQueue.addTask( + () => this.commit({ + fromAutoBackup: false, + requestCustomMessage: true, + onlyStaged: true, + amend: true + }) + ) + }); + } + this.addCommand({ + id: "commit-staged-specified-message", + name: "Commit staged with specific message", + callback: () => this.promiseQueue.addTask( + () => this.commit({ + fromAutoBackup: false, + requestCustomMessage: true, + onlyStaged: true + }) + ) + }); + this.addCommand({ + id: "push2", + name: "Push", + callback: () => this.promiseQueue.addTask(() => this.push()) + }); + this.addCommand({ + id: "stage-current-file", + name: "Stage current file", + checkCallback: (checking) => { + const file = this.app.workspace.getActiveFile(); + if (checking) { + return file !== null; + } else { + this.promiseQueue.addTask(() => this.stageFile(file)); + } + } + }); + this.addCommand({ + id: "unstage-current-file", + name: "Unstage current file", + checkCallback: (checking) => { + const file = this.app.workspace.getActiveFile(); + if (checking) { + return file !== null; + } else { + this.promiseQueue.addTask(() => this.unstageFile(file)); + } + } + }); + this.addCommand({ + id: "edit-remotes", + name: "Edit remotes", + callback: async () => this.editRemotes() + }); + this.addCommand({ + id: "remove-remote", + name: "Remove remote", + callback: async () => this.removeRemote() + }); + this.addCommand({ + id: "set-upstream-branch", + name: "Set upstream branch", + callback: async () => this.setUpstreamBranch() + }); + this.addCommand({ + id: "delete-repo", + name: "CAUTION: Delete repository", + callback: async () => { + const repoExists = await this.app.vault.adapter.exists( + `${this.settings.basePath}/.git` + ); + if (repoExists) { + const modal = new GeneralModal({ + options: ["NO", "YES"], + placeholder: "Do you really want to delete the repository (.git directory)? This action cannot be undone.", + onlySelection: true + }); + const shouldDelete = await modal.open() === "YES"; + if (shouldDelete) { + await this.app.vault.adapter.rmdir( + `${this.settings.basePath}/.git`, + true + ); + new import_obsidian31.Notice( + "Successfully deleted repository. Reloading plugin..." + ); + this.unloadPlugin(); + this.init(); + } + } else { + new import_obsidian31.Notice("No repository found"); + } + } + }); + this.addCommand({ + id: "init-repo", + name: "Initialize a new repo", + callback: async () => this.createNewRepo() + }); + this.addCommand({ + id: "clone-repo", + name: "Clone an existing remote repo", + callback: async () => this.cloneNewRepo() + }); + this.addCommand({ + id: "list-changed-files", + name: "List changed files", + callback: async () => { + if (!await this.isAllInitialized()) + return; + const status2 = await this.gitManager.status(); + console.log(status2); + this.setState(0 /* idle */); + if (status2.changed.length + status2.staged.length > 500) { + this.displayError("Too many changes to display"); + return; + } + new ChangedFilesModal(this, status2.all).open(); + } + }); + this.addCommand({ + id: "switch-branch", + name: "Switch branch", + callback: () => { + this.switchBranch(); + } + }); + this.addCommand({ + id: "create-branch", + name: "Create new branch", + callback: () => { + this.createBranch(); + } + }); + this.addCommand({ + id: "delete-branch", + name: "Delete branch", + callback: () => { + this.deleteBranch(); + } + }); + this.addCommand({ + id: "discard-all", + name: "CAUTION: Discard all changes", + callback: async () => { + if (!await this.isAllInitialized()) + return false; + const modal = new GeneralModal({ + options: ["NO", "YES"], + placeholder: "Do you want to discard all changes to tracked files? This action cannot be undone.", + onlySelection: true + }); + const shouldDiscardAll = await modal.open() === "YES"; + if (shouldDiscardAll) { + this.promiseQueue.addTask(() => this.discardAll()); + } + } + }); + this.addCommand({ + id: "toggle-line-author-info", + name: "Toggle line author information", + callback: () => { + var _a2; + return (_a2 = this.settingsTab) == null ? void 0 : _a2.configureLineAuthorShowStatus( + !this.settings.lineAuthor.show + ); + } + }); + this.registerEvent( + this.app.workspace.on("file-menu", (menu, file, source) => { + this.handleFileMenu(menu, file, source); + }) + ); + if (this.settings.showStatusBar) { + const statusBarEl = this.addStatusBarItem(); + this.statusBar = new StatusBar(statusBarEl, this); + this.registerInterval( + window.setInterval(() => { + var _a2; + return (_a2 = this.statusBar) == null ? void 0 : _a2.display(); + }, 1e3) + ); + } + if (import_obsidian31.Platform.isDesktop && this.settings.showBranchStatusBar) { + const branchStatusBarEl = this.addStatusBarItem(); + this.branchBar = new BranchStatusBar(branchStatusBarEl, this); + this.registerInterval( + window.setInterval(() => { + var _a2; + return (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + }, 6e4) + ); + } + this.app.workspace.onLayoutReady(() => this.init()); + } + setRefreshDebouncer() { + var _a2; + (_a2 = this.debRefresh) == null ? void 0 : _a2.cancel(); + this.debRefresh = (0, import_obsidian31.debounce)( + () => { + if (this.settings.refreshSourceControl) { + this.refresh(); + } + }, + this.settings.refreshSourceControlTimer, + true + ); + } + async showNotices() { + const length = 1e4; + if (this.manifest.id === "obsidian-git" && import_obsidian31.Platform.isDesktopApp && !this.settings.showedMobileNotice) { + new import_obsidian31.Notice( + "Git is now available on mobile! Please read the plugin's README for more information.", + length + ); + this.settings.showedMobileNotice = true; + await this.saveSettings(); + } + if (this.manifest.id === "obsidian-git-isomorphic") { + new import_obsidian31.Notice( + "Git Mobile is now deprecated. Please uninstall it and install Git instead.", + length + ); + } + } + handleFileMenu(menu, file, source) { + if (!this.settings.showFileMenu) + return; + if (source !== "file-explorer-context-menu") { + return; + } + if (!file) { + return; + } + if (!this.gitReady) + return; + menu.addItem((item) => { + item.setTitle(`Git: Stage`).setIcon("plus-circle").setSection("action").onClick((_) => { + this.promiseQueue.addTask(async () => { + if (file instanceof import_obsidian31.TFile) { + await this.gitManager.stage(file.path, true); + } else { + await this.gitManager.stageAll({ + dir: this.gitManager.getRelativeRepoPath( + file.path, + true + ) + }); + } + this.displayMessage(`Staged ${file.path}`); + }); + }); + }); + menu.addItem((item) => { + item.setTitle(`Git: Unstage`).setIcon("minus-circle").setSection("action").onClick((_) => { + this.promiseQueue.addTask(async () => { + if (file instanceof import_obsidian31.TFile) { + await this.gitManager.unstage(file.path, true); + } else { + await this.gitManager.unstageAll({ + dir: this.gitManager.getRelativeRepoPath( + file.path, + true + ) + }); + } + this.displayMessage(`Unstaged ${file.path}`); + }); + }); + }); + } + async migrateSettings() { + if (this.settings.mergeOnPull != void 0) { + this.settings.syncMethod = this.settings.mergeOnPull ? "merge" : "rebase"; + this.settings.mergeOnPull = void 0; + await this.saveSettings(); + } + if (this.settings.autoCommitMessage === void 0) { + this.settings.autoCommitMessage = this.settings.commitMessage; + await this.saveSettings(); + } + if (this.settings.gitPath != void 0) { + this.localStorage.setGitPath(this.settings.gitPath); + this.settings.gitPath = void 0; + await this.saveSettings(); + } + if (this.settings.username != void 0) { + this.localStorage.setPassword(this.settings.username); + this.settings.username = void 0; + await this.saveSettings(); + } + } + unloadPlugin() { + this.gitReady = false; + dispatchEvent(new CustomEvent("git-refresh")); + this.lineAuthoringFeature.deactivateFeature(); + this.clearAutoPull(); + this.clearAutoPush(); + this.clearAutoBackup(); + removeEventListener("git-refresh", this.refresh.bind(this)); + removeEventListener( + "git-head-update", + this.refreshUpdatedHead.bind(this) + ); + this.app.workspace.offref(this.openEvent); + this.app.metadataCache.offref(this.modifyEvent); + this.app.metadataCache.offref(this.deleteEvent); + this.app.metadataCache.offref(this.createEvent); + this.app.metadataCache.offref(this.renameEvent); + this.debRefresh.cancel(); + } + async onunload() { + this.app.workspace.unregisterHoverLinkSource( + SOURCE_CONTROL_VIEW_CONFIG.type + ); + this.unloadPlugin(); + console.log("unloading " + this.manifest.name + " plugin"); + } + async loadSettings() { + let data = await this.loadData(); + if (data == void 0) { + data = { showedMobileNotice: true }; + } + this.settings = mergeSettingsByPriority(DEFAULT_SETTINGS, data); + } + async saveSettings() { + var _a2; + (_a2 = this.settingsTab) == null ? void 0 : _a2.beforeSaveSettings(); + await this.saveData(this.settings); + } + saveLastAuto(date, mode) { + if (mode === "backup") { + this.localStorage.setLastAutoBackup(date.toString()); + } else if (mode === "pull") { + this.localStorage.setLastAutoPull(date.toString()); + } else if (mode === "push") { + this.localStorage.setLastAutoPush(date.toString()); + } + } + loadLastAuto() { + var _a2, _b, _c; + return { + backup: new Date((_a2 = this.localStorage.getLastAutoBackup()) != null ? _a2 : ""), + pull: new Date((_b = this.localStorage.getLastAutoPull()) != null ? _b : ""), + push: new Date((_c = this.localStorage.getLastAutoPush()) != null ? _c : "") + }; + } + get useSimpleGit() { + return import_obsidian31.Platform.isDesktopApp; + } + async init() { + var _a2; + this.showNotices(); + try { + if (this.useSimpleGit) { + this.gitManager = new SimpleGit(this); + await this.gitManager.setGitInstance(); + } else { + this.gitManager = new IsomorphicGit(this); + } + const result = await this.gitManager.checkRequirements(); + switch (result) { + case "missing-git": + this.displayError("Cannot run git command"); + break; + case "missing-repo": + new import_obsidian31.Notice( + "Can't find a valid git repository. Please create one via the given command or clone an existing repo.", + 1e4 + ); + break; + case "valid": + this.gitReady = true; + this.setState(0 /* idle */); + this.openEvent = this.app.workspace.on( + "active-leaf-change", + (leaf) => this.handleViewActiveState(leaf) + ); + this.modifyEvent = this.app.vault.on("modify", () => { + this.debRefresh(); + }); + this.deleteEvent = this.app.vault.on("delete", () => { + this.debRefresh(); + }); + this.createEvent = this.app.vault.on("create", () => { + this.debRefresh(); + }); + this.renameEvent = this.app.vault.on("rename", () => { + this.debRefresh(); + }); + this.registerEvent(this.modifyEvent); + this.registerEvent(this.deleteEvent); + this.registerEvent(this.createEvent); + this.registerEvent(this.renameEvent); + (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + this.lineAuthoringFeature.conditionallyActivateBySettings(); + dispatchEvent(new CustomEvent("git-refresh")); + if (this.settings.autoPullOnBoot) { + this.promiseQueue.addTask( + () => this.pullChangesFromRemote() + ); + } + this.setUpAutos(); + break; + default: + console.log( + "Something weird happened. The 'checkRequirements' result is " + result + ); + } + } catch (error) { + this.displayError(error); + console.error(error); + } + } + async createNewRepo() { + await this.gitManager.init(); + new import_obsidian31.Notice("Initialized new repo"); + await this.init(); + } + async cloneNewRepo() { + const modal = new GeneralModal({ placeholder: "Enter remote URL" }); + const url = await modal.open(); + if (url) { + const confirmOption = "Vault Root"; + let dir = await new GeneralModal({ + options: this.gitManager instanceof IsomorphicGit ? [confirmOption] : [], + placeholder: "Enter directory for clone. It needs to be empty or not existent.", + allowEmpty: this.gitManager instanceof IsomorphicGit + }).open(); + if (dir !== void 0) { + if (dir === confirmOption) { + dir = "."; + } + dir = (0, import_obsidian31.normalizePath)(dir); + if (dir === "/") { + dir = "."; + } + if (dir === ".") { + const modal2 = new GeneralModal({ + options: ["NO", "YES"], + placeholder: `Does your remote repo contain a ${app.vault.configDir} directory at the root?`, + onlySelection: true + }); + const containsConflictDir = await modal2.open(); + if (containsConflictDir === void 0) { + new import_obsidian31.Notice("Aborted clone"); + return; + } else if (containsConflictDir === "YES") { + const confirmOption2 = "DELETE ALL YOUR LOCAL CONFIG AND PLUGINS"; + const modal3 = new GeneralModal({ + options: ["Abort clone", confirmOption2], + placeholder: `To avoid conflicts, the local ${app.vault.configDir} directory needs to be deleted.`, + onlySelection: true + }); + const shouldDelete = await modal3.open() === confirmOption2; + if (shouldDelete) { + await this.app.vault.adapter.rmdir( + app.vault.configDir, + true + ); + } else { + new import_obsidian31.Notice("Aborted clone"); + return; + } + } + } + const depth = await new GeneralModal({ + placeholder: "Specify depth of clone. Leave empty for full clone.", + allowEmpty: true + }).open(); + let depthInt = void 0; + if (depth !== "") { + depthInt = parseInt(depth); + if (isNaN(depthInt)) { + new import_obsidian31.Notice("Invalid depth. Aborting clone."); + return; + } + } + new import_obsidian31.Notice(`Cloning new repo into "${dir}"`); + const oldBase = this.settings.basePath; + const customDir = dir && dir !== "."; + if (customDir) { + this.settings.basePath = dir; + } + try { + await this.gitManager.clone(url, dir, depthInt); + } catch (error) { + this.settings.basePath = oldBase; + this.saveSettings(); + throw error; + } + new import_obsidian31.Notice("Cloned new repo."); + new import_obsidian31.Notice("Please restart Obsidian"); + if (customDir) { + this.saveSettings(); + } + } + } + } + /** + * Retries to call `this.init()` if necessary, otherwise returns directly + * @returns true if `this.gitManager` is ready to be used, false if not. + */ + async isAllInitialized() { + if (!this.gitReady) { + await this.init(); + } + return this.gitReady; + } + ///Used for command + async pullChangesFromRemote() { + if (!await this.isAllInitialized()) + return; + const filesUpdated = await this.pull(); + this.setUpAutoBackup(); + if (filesUpdated === false) { + return; + } + if (!filesUpdated) { + this.displayMessage("Everything is up-to-date"); + } + if (this.gitManager instanceof SimpleGit) { + const status2 = await this.gitManager.status(); + if (status2.conflicted.length > 0) { + this.displayError( + `You have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}` + ); + this.handleConflict(status2.conflicted); + } + } + dispatchEvent(new CustomEvent("git-refresh")); + this.setState(0 /* idle */); + } + async createBackup(fromAutoBackup, requestCustomMessage = false, commitMessage) { + if (!await this.isAllInitialized()) + return; + if (this.settings.syncMethod == "reset" && this.settings.pullBeforePush) { + await this.pull(); + } + if (!await this.commit({ + fromAutoBackup, + requestCustomMessage, + commitMessage + })) { + return; + } + if (!this.settings.disablePush) { + if (await this.remotesAreSet() && await this.gitManager.canPush()) { + if (this.settings.syncMethod != "reset" && this.settings.pullBeforePush) { + await this.pull(); + } + await this.push(); + } else { + this.displayMessage("No changes to push"); + } + } + this.setState(0 /* idle */); + } + // Returns true if commit was successfully + async commit({ + fromAutoBackup, + requestCustomMessage = false, + onlyStaged = false, + commitMessage, + amend = false + }) { + if (!await this.isAllInitialized()) + return false; + let hadConflict = this.localStorage.getConflict(); + let changedFiles; + let status2; + let unstagedFiles; + if (this.gitManager instanceof SimpleGit) { + this.mayDeleteConflictFile(); + status2 = await this.updateCachedStatus(); + if (status2.conflicted.length == 0) { + this.localStorage.setConflict(false); + hadConflict = false; + } + if (fromAutoBackup && status2.conflicted.length > 0) { + this.displayError( + `Did not commit, because you have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}. Please resolve them and commit per command.` + ); + this.handleConflict(status2.conflicted); + return false; + } + changedFiles = [...status2.changed, ...status2.staged]; + } else if (fromAutoBackup && hadConflict) { + this.setState(6 /* conflicted */); + this.displayError( + `Did not commit, because you have conflicts. Please resolve them and commit per command.` + ); + return false; + } else if (hadConflict) { + await this.mayDeleteConflictFile(); + status2 = await this.updateCachedStatus(); + changedFiles = [...status2.changed, ...status2.staged]; + } else { + if (onlyStaged) { + changedFiles = await this.gitManager.getStagedFiles(); + } else { + unstagedFiles = await this.gitManager.getUnstagedFiles(); + changedFiles = unstagedFiles.map(({ filepath }) => ({ + vault_path: this.gitManager.getRelativeVaultPath(filepath) + })); + } + } + if (await this.hasTooBigFiles(changedFiles)) { + this.setState(0 /* idle */); + return false; + } + if (changedFiles.length !== 0 || hadConflict) { + let cmtMessage = commitMessage != null ? commitMessage : commitMessage = fromAutoBackup ? this.settings.autoCommitMessage : this.settings.commitMessage; + if (fromAutoBackup && this.settings.customMessageOnAutoBackup || requestCustomMessage) { + if (!this.settings.disablePopups && fromAutoBackup) { + new import_obsidian31.Notice( + "Auto backup: Please enter a custom commit message. Leave empty to abort" + ); + } + const tempMessage = await new CustomMessageModal( + this, + true + ).open(); + if (tempMessage != void 0 && tempMessage != "" && tempMessage != "...") { + cmtMessage = tempMessage; + } else { + this.setState(0 /* idle */); + return false; + } + } + let committedFiles; + if (onlyStaged) { + committedFiles = await this.gitManager.commit({ + message: cmtMessage, + amend + }); + } else { + committedFiles = await this.gitManager.commitAll({ + message: cmtMessage, + status: status2, + unstagedFiles, + amend + }); + } + if (this.gitManager instanceof SimpleGit) { + if ((await this.updateCachedStatus()).conflicted.length == 0) { + this.localStorage.setConflict(false); + } + } + let roughly = false; + if (committedFiles === void 0) { + roughly = true; + committedFiles = changedFiles.length; + } + this.setUpAutoBackup(); + this.displayMessage( + `Committed${roughly ? " approx." : ""} ${committedFiles} ${committedFiles == 1 ? "file" : "files"}` + ); + } else { + this.displayMessage("No changes to commit"); + } + dispatchEvent(new CustomEvent("git-refresh")); + this.setState(0 /* idle */); + return true; + } + async hasTooBigFiles(files) { + const branchInfo = await this.gitManager.branchInfo(); + const remote = branchInfo.tracking ? splitRemoteBranch(branchInfo.tracking)[0] : null; + if (remote) { + const remoteUrl = await this.gitManager.getRemoteUrl(remote); + if (remoteUrl == null ? void 0 : remoteUrl.includes("github.com")) { + const tooBigFiles = files.filter((f) => { + const file = this.app.vault.getAbstractFileByPath( + f.vault_path + ); + if (file instanceof import_obsidian31.TFile) { + return file.stat.size >= 1e8; + } + return false; + }); + if (tooBigFiles.length > 0) { + this.displayError( + `Did not commit, because following files are too big: ${tooBigFiles.map( + (e) => e.vault_path + )}. Please remove them.` + ); + return true; + } + } + } + return false; + } + async push() { + if (!await this.isAllInitialized()) + return false; + if (!await this.remotesAreSet()) { + return false; + } + const hadConflict = this.localStorage.getConflict(); + if (this.gitManager instanceof SimpleGit) + await this.mayDeleteConflictFile(); + let status2; + if (this.gitManager instanceof SimpleGit && (status2 = await this.updateCachedStatus()).conflicted.length > 0) { + this.displayError( + `Cannot push. You have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}` + ); + this.handleConflict(status2.conflicted); + return false; + } else if (this.gitManager instanceof IsomorphicGit && hadConflict) { + this.displayError(`Cannot push. You have conflicts`); + this.setState(6 /* conflicted */); + return false; + } + console.log("Pushing...."); + const pushedFiles = await this.gitManager.push(); + if (pushedFiles !== void 0) { + console.log("Pushed!", pushedFiles); + if (pushedFiles > 0) { + this.displayMessage( + `Pushed ${pushedFiles} ${pushedFiles == 1 ? "file" : "files"} to remote` + ); + } else { + this.displayMessage(`No changes to push`); + } + } + this.offlineMode = false; + this.setState(0 /* idle */); + dispatchEvent(new CustomEvent("git-refresh")); + return true; + } + /** Used for internals + Returns whether the pull added a commit or not. + + See {@link pullChangesFromRemote} for the command version. */ + async pull() { + if (!await this.remotesAreSet()) { + return false; + } + const pulledFiles = await this.gitManager.pull() || []; + this.offlineMode = false; + if (pulledFiles.length > 0) { + this.displayMessage( + `Pulled ${pulledFiles.length} ${pulledFiles.length == 1 ? "file" : "files"} from remote` + ); + this.lastPulledFiles = pulledFiles; + } + return pulledFiles.length; + } + async fetch() { + if (!await this.remotesAreSet()) { + return; + } + await this.gitManager.fetch(); + this.displayMessage(`Fetched from remote`); + this.offlineMode = false; + dispatchEvent(new CustomEvent("git-refresh")); + } + async mayDeleteConflictFile() { + const file = this.app.vault.getAbstractFileByPath( + this.conflictOutputFile + ); + if (file) { + this.app.workspace.iterateAllLeaves((leaf) => { + var _a2; + if (leaf.view instanceof import_obsidian31.MarkdownView && ((_a2 = leaf.view.file) == null ? void 0 : _a2.path) == file.path) { + leaf.detach(); + } + }); + await this.app.vault.delete(file); + } + } + async stageFile(file) { + if (!await this.isAllInitialized()) + return false; + await this.gitManager.stage(file.path, true); + this.displayMessage(`Staged ${file.path}`); + dispatchEvent(new CustomEvent("git-refresh")); + this.setState(0 /* idle */); + return true; + } + async unstageFile(file) { + if (!await this.isAllInitialized()) + return false; + await this.gitManager.unstage(file.path, true); + this.displayMessage(`Unstaged ${file.path}`); + dispatchEvent(new CustomEvent("git-refresh")); + this.setState(0 /* idle */); + return true; + } + async switchBranch() { + var _a2; + if (!await this.isAllInitialized()) + return; + const branchInfo = await this.gitManager.branchInfo(); + const selectedBranch = await new BranchModal( + branchInfo.branches + ).open(); + if (selectedBranch != void 0) { + await this.gitManager.checkout(selectedBranch); + this.displayMessage(`Switched to ${selectedBranch}`); + (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + return selectedBranch; + } + } + async switchRemoteBranch() { + var _a2; + if (!await this.isAllInitialized()) + return; + const selectedBranch = await this.selectRemoteBranch() || ""; + const [remote, branch2] = splitRemoteBranch(selectedBranch); + if (branch2 != void 0 && remote != void 0) { + await this.gitManager.checkout(branch2, remote); + this.displayMessage(`Switched to ${selectedBranch}`); + (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + return selectedBranch; + } + } + async createBranch() { + var _a2; + if (!await this.isAllInitialized()) + return; + const newBranch = await new GeneralModal({ + placeholder: "Create new branch" + }).open(); + if (newBranch != void 0) { + await this.gitManager.createBranch(newBranch); + this.displayMessage(`Created new branch ${newBranch}`); + (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + return newBranch; + } + } + async deleteBranch() { + var _a2; + if (!await this.isAllInitialized()) + return; + const branchInfo = await this.gitManager.branchInfo(); + if (branchInfo.current) + branchInfo.branches.remove(branchInfo.current); + const branch2 = await new GeneralModal({ + options: branchInfo.branches, + placeholder: "Delete branch", + onlySelection: true + }).open(); + if (branch2 != void 0) { + let force = false; + const merged = await this.gitManager.branchIsMerged(branch2); + if (!merged) { + const forceAnswer = await new GeneralModal({ + options: ["YES", "NO"], + placeholder: "This branch isn't merged into HEAD. Force delete?", + onlySelection: true + }).open(); + if (forceAnswer !== "YES") { + return; + } + force = forceAnswer === "YES"; + } + await this.gitManager.deleteBranch(branch2, force); + this.displayMessage(`Deleted branch ${branch2}`); + (_a2 = this.branchBar) == null ? void 0 : _a2.display(); + return branch2; + } + } + // Ensures that the upstream branch is set. + // If not, it will prompt the user to set it. + // + // An exception is when the user has submodules enabled. + // In this case, the upstream branch is not required, + // to allow pulling/pushing only the submodules and not the outer repo. + async remotesAreSet() { + if (this.settings.updateSubmodules) { + return true; + } + if (!(await this.gitManager.branchInfo()).tracking) { + new import_obsidian31.Notice("No upstream branch is set. Please select one."); + return await this.setUpstreamBranch(); + } + return true; + } + async setUpstreamBranch() { + const remoteBranch = await this.selectRemoteBranch(); + if (remoteBranch == void 0) { + this.displayError("Aborted. No upstream-branch is set!", 1e4); + this.setState(0 /* idle */); + return false; + } else { + await this.gitManager.updateUpstreamBranch(remoteBranch); + this.displayMessage(`Set upstream branch to ${remoteBranch}`); + this.setState(0 /* idle */); + return true; + } + } + async setUpAutoBackup() { + if (this.settings.setLastSaveToLastCommit) { + this.clearAutoBackup(); + const lastCommitDate = await this.gitManager.getLastCommitTime(); + if (lastCommitDate) { + this.localStorage.setLastAutoBackup(lastCommitDate.toString()); + } + } + if (!this.timeoutIDBackup && !this.onFileModifyEventRef) { + const lastAutos = this.loadLastAuto(); + if (this.settings.autoSaveInterval > 0) { + const now2 = /* @__PURE__ */ new Date(); + const diff3 = this.settings.autoSaveInterval - Math.round( + (now2.getTime() - lastAutos.backup.getTime()) / 1e3 / 60 + ); + this.startAutoBackup(diff3 <= 0 ? 0 : diff3); + } + } + } + async setUpAutos() { + this.setUpAutoBackup(); + const lastAutos = this.loadLastAuto(); + if (this.settings.differentIntervalCommitAndPush && this.settings.autoPushInterval > 0) { + const now2 = /* @__PURE__ */ new Date(); + const diff3 = this.settings.autoPushInterval - Math.round( + (now2.getTime() - lastAutos.push.getTime()) / 1e3 / 60 + ); + this.startAutoPush(diff3 <= 0 ? 0 : diff3); + } + if (this.settings.autoPullInterval > 0) { + const now2 = /* @__PURE__ */ new Date(); + const diff3 = this.settings.autoPullInterval - Math.round( + (now2.getTime() - lastAutos.pull.getTime()) / 1e3 / 60 + ); + this.startAutoPull(diff3 <= 0 ? 0 : diff3); + } + } + async discardAll() { + await this.gitManager.discardAll({ + status: this.cachedStatus + }); + new import_obsidian31.Notice( + "All local changes have been discarded. New files remain untouched." + ); + } + clearAutos() { + this.clearAutoBackup(); + this.clearAutoPush(); + this.clearAutoPull(); + } + startAutoBackup(minutes) { + let time = (minutes != null ? minutes : this.settings.autoSaveInterval) * 6e4; + if (this.settings.autoBackupAfterFileChange) { + if (minutes === 0) { + this.doAutoBackup(); + } else { + this.onFileModifyEventRef = this.app.vault.on( + "modify", + () => this.autoBackupDebouncer() + ); + this.autoBackupDebouncer = (0, import_obsidian31.debounce)( + () => this.doAutoBackup(), + time, + true + ); + } + } else { + if (time > 2147483647) + time = 2147483647; + this.timeoutIDBackup = window.setTimeout( + () => this.doAutoBackup(), + time + ); + } + } + // This is used for both auto backup and commit + doAutoBackup() { + this.promiseQueue.addTask(() => { + if (this.settings.differentIntervalCommitAndPush) { + return this.commit({ fromAutoBackup: true }); + } else { + return this.createBackup(true); + } + }); + this.saveLastAuto(/* @__PURE__ */ new Date(), "backup"); + this.saveSettings(); + this.startAutoBackup(); + } + startAutoPull(minutes) { + let time = (minutes != null ? minutes : this.settings.autoPullInterval) * 6e4; + if (time > 2147483647) + time = 2147483647; + this.timeoutIDPull = window.setTimeout(() => { + this.promiseQueue.addTask(() => this.pullChangesFromRemote()); + this.saveLastAuto(/* @__PURE__ */ new Date(), "pull"); + this.saveSettings(); + this.startAutoPull(); + }, time); + } + startAutoPush(minutes) { + let time = (minutes != null ? minutes : this.settings.autoPushInterval) * 6e4; + if (time > 2147483647) + time = 2147483647; + this.timeoutIDPush = window.setTimeout(() => { + this.promiseQueue.addTask(() => this.push()); + this.saveLastAuto(/* @__PURE__ */ new Date(), "push"); + this.saveSettings(); + this.startAutoPush(); + }, time); + } + clearAutoBackup() { + var _a2; + let wasActive = false; + if (this.timeoutIDBackup) { + window.clearTimeout(this.timeoutIDBackup); + this.timeoutIDBackup = void 0; + wasActive = true; + } + if (this.onFileModifyEventRef) { + (_a2 = this.autoBackupDebouncer) == null ? void 0 : _a2.cancel(); + this.app.vault.offref(this.onFileModifyEventRef); + this.onFileModifyEventRef = void 0; + wasActive = true; + } + return wasActive; + } + clearAutoPull() { + if (this.timeoutIDPull) { + window.clearTimeout(this.timeoutIDPull); + this.timeoutIDPull = void 0; + return true; + } + return false; + } + clearAutoPush() { + if (this.timeoutIDPush) { + window.clearTimeout(this.timeoutIDPush); + this.timeoutIDPush = void 0; + return true; + } + return false; + } + async handleConflict(conflicted) { + this.setState(6 /* conflicted */); + this.localStorage.setConflict(true); + let lines; + if (conflicted !== void 0) { + lines = [ + "# Conflicts", + "Please resolve them and commit them using the commands `Git: Commit all changes` followed by `Git: Push`", + "(This file will automatically be deleted before commit)", + "[[#Additional Instructions]] available below file list", + "", + ...conflicted.map((e) => { + const file = this.app.vault.getAbstractFileByPath(e); + if (file instanceof import_obsidian31.TFile) { + const link = this.app.metadataCache.fileToLinktext( + file, + "/" + ); + return `- [[${link}]]`; + } else { + return `- Not a file: ${e}`; + } + }), + ` +# Additional Instructions +I strongly recommend to use "Source mode" for viewing the conflicted files. For simple conflicts, in each file listed above replace every occurrence of the following text blocks with the desired text. + +\`\`\`diff +<<<<<<< HEAD + File changes in local repository +======= + File changes in remote repository +>>>>>>> origin/main +\`\`\`` + ]; + } + this.writeAndOpenFile(lines == null ? void 0 : lines.join("\n")); + } + async editRemotes() { + if (!await this.isAllInitialized()) + return; + const remotes = await this.gitManager.getRemotes(); + const nameModal = new GeneralModal({ + options: remotes, + placeholder: "Select or create a new remote by typing its name and selecting it" + }); + const remoteName = await nameModal.open(); + if (remoteName) { + const oldUrl = await this.gitManager.getRemoteUrl(remoteName); + const urlModal = new GeneralModal({ initialValue: oldUrl }); + const remoteURL = await urlModal.open(); + if (remoteURL) { + await this.gitManager.setRemote(remoteName, remoteURL); + return remoteName; + } + } + } + async selectRemoteBranch() { + let remotes = await this.gitManager.getRemotes(); + let selectedRemote; + if (remotes.length === 0) { + selectedRemote = await this.editRemotes(); + if (selectedRemote == void 0) { + remotes = await this.gitManager.getRemotes(); + } + } + const nameModal = new GeneralModal({ + options: remotes, + placeholder: "Select or create a new remote by typing its name and selecting it" + }); + const remoteName = selectedRemote != null ? selectedRemote : await nameModal.open(); + if (remoteName) { + this.displayMessage("Fetching remote branches"); + await this.gitManager.fetch(remoteName); + const branches = await this.gitManager.getRemoteBranches(remoteName); + const branchModal = new GeneralModal({ + options: branches, + placeholder: "Select or create a new remote branch by typing its name and selecting it" + }); + return await branchModal.open(); + } + } + async removeRemote() { + if (!await this.isAllInitialized()) + return; + const remotes = await this.gitManager.getRemotes(); + const nameModal = new GeneralModal({ + options: remotes, + placeholder: "Select a remote" + }); + const remoteName = await nameModal.open(); + if (remoteName) { + this.gitManager.removeRemote(remoteName); + } + } + async writeAndOpenFile(text2) { + if (text2 !== void 0) { + await this.app.vault.adapter.write(this.conflictOutputFile, text2); + } + let fileIsAlreadyOpened = false; + this.app.workspace.iterateAllLeaves((leaf) => { + if (leaf.getDisplayText() != "" && this.conflictOutputFile.startsWith(leaf.getDisplayText())) { + fileIsAlreadyOpened = true; + } + }); + if (!fileIsAlreadyOpened) { + this.app.workspace.openLinkText(this.conflictOutputFile, "/", true); + } + } + handleViewActiveState(leaf) { + var _a2, _b; + if (!(leaf == null ? void 0 : leaf.view.getState().file)) + return; + const sourceControlLeaf = this.app.workspace.getLeavesOfType(SOURCE_CONTROL_VIEW_CONFIG.type).first(); + const historyLeaf = this.app.workspace.getLeavesOfType(HISTORY_VIEW_CONFIG.type).first(); + (_a2 = sourceControlLeaf == null ? void 0 : sourceControlLeaf.view.containerEl.querySelector(`div.nav-file-title.is-active`)) == null ? void 0 : _a2.removeClass("is-active"); + (_b = historyLeaf == null ? void 0 : historyLeaf.view.containerEl.querySelector(`div.nav-file-title.is-active`)) == null ? void 0 : _b.removeClass("is-active"); + if ((leaf == null ? void 0 : leaf.view) instanceof DiffView) { + const path2 = leaf.view.state.file; + this.lastDiffViewState = leaf.view.getState(); + let el; + if (sourceControlLeaf && leaf.view.state.staged) { + el = sourceControlLeaf.view.containerEl.querySelector( + `div.staged div.nav-file-title[data-path='${path2}']` + ); + } else if (sourceControlLeaf && leaf.view.state.staged === false && !leaf.view.state.hash) { + el = sourceControlLeaf.view.containerEl.querySelector( + `div.changes div.nav-file-title[data-path='${path2}']` + ); + } else if (historyLeaf && leaf.view.state.hash) { + el = historyLeaf.view.containerEl.querySelector( + `div.nav-file-title[data-path='${path2}']` + ); + } + el == null ? void 0 : el.addClass("is-active"); + } else { + this.lastDiffViewState = void 0; + } + } + // region: displaying / formatting messages + displayMessage(message, timeout = 4 * 1e3) { + var _a2; + (_a2 = this.statusBar) == null ? void 0 : _a2.displayMessage(message.toLowerCase(), timeout); + if (!this.settings.disablePopups) { + if (!this.settings.disablePopupsForNoChanges || !message.startsWith("No changes")) { + new import_obsidian31.Notice(message, 5 * 1e3); + } + } + this.log(message); + } + displayError(message, timeout = 10 * 1e3) { + var _a2; + if (message instanceof Errors.UserCanceledError) { + new import_obsidian31.Notice("Aborted"); + return; + } + message = message.toString(); + new import_obsidian31.Notice(message, timeout); + console.log(`git obsidian error: ${message}`); + (_a2 = this.statusBar) == null ? void 0 : _a2.displayMessage(message.toLowerCase(), timeout); + } + log(message) { + console.log(`${this.manifest.id}: ` + message); + } +}; +/*! Bundled license information: + +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + +buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +crc-32/crc32.js: + (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *) + +js-sha256/src/sha256.js: + (** + * [js-sha256]{@link https://github.com/emn178/js-sha256} + * + * @version 0.9.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT + *) + +feather-icons/dist/feather.js: + (*! + Copyright (c) 2016 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames + *) +*/ diff --git a/src/content/blog/.obsidian/plugins/obsidian-git/manifest.json b/src/content/blog/.obsidian/plugins/obsidian-git/manifest.json new file mode 100644 index 0000000..045f4f8 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-git/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "obsidian-git", + "name": "Git", + "description": "Backup your vault with Git.", + "isDesktopOnly": false, + "fundingUrl": "https://ko-fi.com/vinzent", + "js": "main.js", + "version": "2.24.2" +} diff --git a/src/content/blog/.obsidian/plugins/obsidian-git/styles.css b/src/content/blog/.obsidian/plugins/obsidian-git/styles.css new file mode 100644 index 0000000..71a55ea --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-git/styles.css @@ -0,0 +1,558 @@ +@keyframes loading { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} + +.workspace-leaf-content[data-type="git-view"] .button-border { + border: 2px solid var(--interactive-accent); + border-radius: var(--radius-s); +} + +.workspace-leaf-content[data-type="git-view"] .view-content { + padding: 0; +} + +.workspace-leaf-content[data-type="git-history-view"] .view-content { + padding: 0; +} + +.loading > svg { + animation: 2s linear infinite loading; + transform-origin: 50% 50%; + display: inline-block; +} + +.obsidian-git-center { + margin: auto; + text-align: center; + width: 50%; +} + +.obsidian-git-textarea { + display: block; + margin-left: auto; + margin-right: auto; +} + +.obsidian-git-center-button { + display: block; + margin: 20px auto; +} + +.tooltip.mod-left { + overflow-wrap: break-word; +} + +.tooltip.mod-right { + overflow-wrap: break-word; +} +.git-tools { + display: flex; + margin-left: auto; +} +.git-tools .type { + padding-left: var(--size-2-1); + display: flex; + align-items: center; + justify-content: center; + width: 11px; +} + +.git-tools .type[data-type="M"] { + color: orange; +} +.git-tools .type[data-type="D"] { + color: red; +} +.git-tools .buttons { + display: flex; +} +.git-tools .buttons > * { + padding: 0 0; + height: auto; +} + +.git-author { + color: var(--text-accent); +} + +.git-date { + color: var(--text-accent); +} + +.git-ref { + color: var(--text-accent); +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-d-none { + display: none; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-wrapper { + text-align: left; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-header { + background-color: var(--background-primary); + border-bottom: 1px solid var(--interactive-accent); + font-family: var(--font-monospace); + height: 35px; + padding: 5px 10px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-header, +.workspace-leaf-content[data-type="diff-view"] .d2h-file-stats { + display: -webkit-box; + display: -ms-flexbox; + display: flex; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-stats { + font-size: 14px; + margin-left: auto; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-lines-added { + border: 1px solid #b4e2b4; + border-radius: 5px 0 0 5px; + color: #399839; + padding: 2px; + text-align: right; + vertical-align: middle; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-lines-deleted { + border: 1px solid #e9aeae; + border-radius: 0 5px 5px 0; + color: #c33; + margin-left: 1px; + padding: 2px; + text-align: left; + vertical-align: middle; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-name-wrapper { + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 15px; + width: 100%; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-name { + overflow-x: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-wrapper { + border: 1px solid var(--background-modifier-border); + border-radius: 3px; + margin-bottom: 1em; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-collapse { + -webkit-box-pack: end; + -ms-flex-pack: end; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + border: 1px solid var(--background-modifier-border); + border-radius: 3px; + cursor: pointer; + display: none; + font-size: 12px; + justify-content: flex-end; + padding: 4px 8px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-collapse.d2h-selected { + background-color: #c8e1ff; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-collapse-input { + margin: 0 4px 0 0; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-diff-table { + border-collapse: collapse; + font-family: Menlo, Consolas, monospace; + font-size: 13px; + width: 100%; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-files-diff { + width: 100%; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-diff { + overflow-y: hidden; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-side-diff { + display: inline-block; + margin-bottom: -8px; + margin-right: -4px; + overflow-x: scroll; + overflow-y: hidden; + width: 50%; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line { + padding: 0 8em; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-line { + display: inline-block; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + white-space: nowrap; + width: 100%; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-line { + padding: 0 4.5em; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line-ctn { + word-wrap: normal; + background: none; + display: inline-block; + padding: 0; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + vertical-align: middle; + white-space: pre; + width: 100%; +} + +.theme-light .workspace-leaf-content[data-type="diff-view"] .d2h-code-line del, +.theme-light + .workspace-leaf-content[data-type="diff-view"] + .d2h-code-side-line + del { + background-color: #ffb6ba; +} + +.theme-dark .workspace-leaf-content[data-type="diff-view"] .d2h-code-line del, +.theme-dark + .workspace-leaf-content[data-type="diff-view"] + .d2h-code-side-line + del { + background-color: #8d232881; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line del, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line ins, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-line del, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-line ins { + border-radius: 0.2em; + display: inline-block; + margin-top: -1px; + text-decoration: none; + vertical-align: middle; +} + +.theme-light .workspace-leaf-content[data-type="diff-view"] .d2h-code-line ins, +.theme-light + .workspace-leaf-content[data-type="diff-view"] + .d2h-code-side-line + ins { + background-color: #97f295; + text-align: left; +} + +.theme-dark .workspace-leaf-content[data-type="diff-view"] .d2h-code-line ins, +.theme-dark + .workspace-leaf-content[data-type="diff-view"] + .d2h-code-side-line + ins { + background-color: #1d921996; + text-align: left; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line-prefix { + word-wrap: normal; + background: none; + display: inline; + padding: 0; + white-space: pre; +} + +.workspace-leaf-content[data-type="diff-view"] .line-num1 { + float: left; +} + +.workspace-leaf-content[data-type="diff-view"] .line-num1, +.workspace-leaf-content[data-type="diff-view"] .line-num2 { + -webkit-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + padding: 0 0.5em; + text-overflow: ellipsis; + width: 3.5em; +} + +.workspace-leaf-content[data-type="diff-view"] .line-num2 { + float: right; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-muted); + cursor: pointer; + display: inline-block; + position: absolute; + text-align: right; + width: 7.5em; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-linenumber:after { + content: "\200b"; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-muted); + cursor: pointer; + display: inline-block; + overflow: hidden; + padding: 0 0.5em; + position: absolute; + text-align: right; + text-overflow: ellipsis; + width: 4em; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-diff-tbody tr { + position: relative; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-linenumber:after { + content: "\200b"; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-emptyplaceholder, +.workspace-leaf-content[data-type="diff-view"] .d2h-emptyplaceholder { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-line-prefix, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-linenumber, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-linenumber, +.workspace-leaf-content[data-type="diff-view"] .d2h-emptyplaceholder { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-code-linenumber, +.workspace-leaf-content[data-type="diff-view"] .d2h-code-side-linenumber { + direction: rtl; +} + +.theme-light .workspace-leaf-content[data-type="diff-view"] .d2h-del { + background-color: #fee8e9; + border-color: #e9aeae; +} + +.theme-light .workspace-leaf-content[data-type="diff-view"] .d2h-ins { + background-color: #dfd; + border-color: #b4e2b4; +} + +.theme-dark .workspace-leaf-content[data-type="diff-view"] .d2h-del { + background-color: #521b1d83; + border-color: #691d1d73; +} + +.theme-dark .workspace-leaf-content[data-type="diff-view"] .d2h-ins { + background-color: rgba(30, 71, 30, 0.5); + border-color: #13501381; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-info { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); + color: var(--text-normal); +} + +.theme-light + .workspace-leaf-content[data-type="diff-view"] + .d2h-file-diff + .d2h-del.d2h-change { + background-color: #fdf2d0; +} + +.theme-dark + .workspace-leaf-content[data-type="diff-view"] + .d2h-file-diff + .d2h-del.d2h-change { + background-color: #55492480; +} + +.theme-light + .workspace-leaf-content[data-type="diff-view"] + .d2h-file-diff + .d2h-ins.d2h-change { + background-color: #ded; +} + +.theme-dark + .workspace-leaf-content[data-type="diff-view"] + .d2h-file-diff + .d2h-ins.d2h-change { + background-color: rgba(37, 78, 37, 0.418); +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list-wrapper { + margin-bottom: 10px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list-wrapper a { + color: #3572b0; + text-decoration: none; +} + +.workspace-leaf-content[data-type="diff-view"] + .d2h-file-list-wrapper + a:visited { + color: #3572b0; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list-header { + text-align: left; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list-title { + font-weight: 700; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list-line { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + text-align: left; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list { + display: block; + list-style: none; + margin: 0; + padding: 0; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list > li { + border-bottom: 1px solid var(--background-modifier-border); + margin: 0; + padding: 5px 10px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-list > li:last-child { + border-bottom: none; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-file-switch { + cursor: pointer; + display: none; + font-size: 10px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-icon { + fill: currentColor; + margin-right: 10px; + vertical-align: middle; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-deleted { + color: #c33; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-added { + color: #399839; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-changed { + color: #d0b44c; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-moved { + color: #3572b0; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-tag { + background-color: var(--background-primary); + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 10px; + margin-left: 5px; + padding: 0 2px; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-deleted-tag { + border: 2px solid #c33; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-added-tag { + border: 1px solid #399839; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-changed-tag { + border: 1px solid #d0b44c; +} + +.workspace-leaf-content[data-type="diff-view"] .d2h-moved-tag { + border: 1px solid #3572b0; +} + +/* ====================== Line Authoring Information ====================== */ + +.cm-gutterElement.obs-git-blame-gutter { + /* Add background color to spacing inbetween and around the gutter for better aesthetics */ + border-width: 0px 2px 0.2px 2px; + border-style: solid; + border-color: var(--background-secondary); + background-color: var(--background-secondary); +} + +.cm-gutterElement.obs-git-blame-gutter > div, +.line-author-settings-preview { + /* delegate text color to settings */ + color: var(--obs-git-gutter-text); + font-family: monospace; + height: 100%; /* ensure, that age-based background color occupies entire parent */ + text-align: right; + padding: 0px 6px 0px 6px; + white-space: pre; /* Keep spaces and do not collapse them. */ +} + +@media(max-width:800px){ + /* hide git blame gutter not to superpose text */ + .cm-gutterElement.obs-git-blame-gutter { + display: none; + } +} diff --git a/src/content/blog/.obsidian/plugins/obsidian-livesync/data.json b/src/content/blog/.obsidian/plugins/obsidian-livesync/data.json new file mode 100644 index 0000000..7f25e00 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-livesync/data.json @@ -0,0 +1,70 @@ +{ + "couchDB_URI": "", + "couchDB_USER": "", + "couchDB_PASSWORD": "", + "couchDB_DBNAME": "", + "liveSync": true, + "syncOnSave": false, + "syncOnStart": false, + "savingDelay": 200, + "lessInformationInLog": false, + "gcDelay": 0, + "versionUpFlash": "", + "minimumChunkSize": 20, + "longLineThreshold": 250, + "showVerboseLog": false, + "suspendFileWatching": false, + "trashInsteadDelete": true, + "periodicReplication": false, + "periodicReplicationInterval": 60, + "syncOnFileOpen": false, + "encrypt": false, + "passphrase": "", + "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": 50, + "batches_limit": 40, + "useHistory": true, + "disableRequestURI": true, + "skipOlderFilesOnSync": true, + "checkConflictOnlyOnOpen": false, + "syncInternalFiles": false, + "syncInternalFilesBeforeReplication": false, + "syncInternalFilesIgnorePatterns": "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/", + "syncInternalFilesInterval": 60, + "additionalSuffixOfDatabaseName": "", + "ignoreVersionCheck": false, + "lastReadUpdates": 0, + "deleteMetadataOfDeletedFiles": false, + "syncIgnoreRegEx": "", + "syncOnlyRegEx": "", + "customChunkSize": 100, + "readChunksOnline": true, + "watchInternalFileChanges": true, + "automaticallyDeleteMetadataOfDeletedFiles": 0, + "disableMarkdownAutoMerge": false, + "writeDocumentsIfConflicted": false, + "useDynamicIterationCount": false, + "syncAfterMerge": false, + "configPassphraseStore": "", + "encryptedPassphrase": "", + "encryptedCouchDBConnection": "[\"WxsQs2gfmXFZCqA8MYSo/ZGeKOHSq6hYKM77yVJdih4mKrTXFIRZVtrGbF7q80eivURsqjAoSzWCWdL8nrEOzSZoWULLtYGb5t/JpQqfP6o+ubYimw63IGCQPxpOLlyGLYm/RITk0sLXDTMCIkKUzeiMB0kQ6bnmQyfnRsD105xIZVnGjbgdVtQTFk0b/PTs0R6FgcG2DSjSbKGgyZw=\",\"49337be5455b0d06216a912b20000000\",\"7aa93e29c36d6c9ce6a9126b1dbb8ee5\"]", + "permitEmptyPassphrase": false, + "useIndexedDBAdapter": false, + "useTimeouts": false, + "writeLogToTheFile": false, + "hashCacheMaxCount": 300, + "hashCacheMaxAmount": 50, + "concurrencyOfReadChunksOnline": 100, + "minimumIntervalOfReadChunksOnline": 333 +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/obsidian-livesync/main.js b/src/content/blog/.obsidian/plugins/obsidian-livesync/main.js new file mode 100644 index 0000000..c34e031 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-livesync/main.js @@ -0,0 +1,24242 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +"use strict"; +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 __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// 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_patch4 = 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_DELETE5 = -1; + var DIFF_INSERT5 = 1; + var DIFF_EQUAL4 = 0; + diff_match_patch4.Diff = function(op, text2) { + return [op, text2]; + }; + diff_match_patch4.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_patch4.Diff(DIFF_EQUAL4, 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_patch4.Diff(DIFF_EQUAL4, commonprefix)); + } + if (commonsuffix) { + diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, commonsuffix)); + } + this.diff_cleanupMerge(diffs); + return diffs; + }; + diff_match_patch4.prototype.diff_compute_ = function(text1, text2, checklines, deadline) { + var diffs; + if (!text1) { + return [new diff_match_patch4.Diff(DIFF_INSERT5, text2)]; + } + if (!text2) { + return [new diff_match_patch4.Diff(DIFF_DELETE5, text1)]; + } + var longtext = text1.length > text2.length ? text1 : text2; + var shorttext = text1.length > text2.length ? text2 : text1; + var i = longtext.indexOf(shorttext); + if (i != -1) { + diffs = [ + new diff_match_patch4.Diff(DIFF_INSERT5, longtext.substring(0, i)), + new diff_match_patch4.Diff(DIFF_EQUAL4, shorttext), + new diff_match_patch4.Diff( + DIFF_INSERT5, + longtext.substring(i + shorttext.length) + ) + ]; + if (text1.length > text2.length) { + diffs[0][0] = diffs[2][0] = DIFF_DELETE5; + } + return diffs; + } + if (shorttext.length == 1) { + return [ + new diff_match_patch4.Diff(DIFF_DELETE5, text1), + new diff_match_patch4.Diff(DIFF_INSERT5, 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_patch4.Diff(DIFF_EQUAL4, 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_patch4.prototype.diff_lineMode_ = function(text1, text2, deadline) { + var a2 = this.diff_linesToChars_(text1, text2); + text1 = a2.chars1; + text2 = a2.chars2; + var linearray = a2.lineArray; + var diffs = this.diff_main(text1, text2, false, deadline); + this.diff_charsToLines_(diffs, linearray); + this.diff_cleanupSemantic(diffs); + diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, "")); + 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_INSERT5: + count_insert++; + text_insert += diffs[pointer][1]; + break; + case DIFF_DELETE5: + count_delete++; + text_delete += diffs[pointer][1]; + break; + case DIFF_EQUAL4: + 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_patch4.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_patch4.Diff(DIFF_DELETE5, text1), + new diff_match_patch4.Diff(DIFF_INSERT5, text2) + ]; + }; + diff_match_patch4.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_patch4.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_patch4.prototype.diff_charsToLines_ = function(diffs, lineArray) { + for (var i = 0; i < diffs.length; i++) { + var chars = diffs[i][1]; + var text2 = []; + for (var j = 0; j < chars.length; j++) { + text2[j] = lineArray[chars.charCodeAt(j)]; + } + diffs[i][1] = text2.join(""); + } + }; + diff_match_patch4.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_patch4.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_patch4.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_patch4.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, i) { + var seed = longtext2.substring(i, i + 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(i), + shorttext2.substring(j) + ); + var suffixLength = dmp.diff_commonSuffix( + longtext2.substring(0, i), + 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, i - suffixLength); + best_longtext_b = longtext2.substring(i + 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_patch4.prototype.diff_cleanupSemantic = function(diffs) { + var changes3 = 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_EQUAL4) { + 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_INSERT5) { + 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_patch4.Diff(DIFF_DELETE5, lastEquality) + ); + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT5; + equalitiesLength--; + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes3 = true; + } + } + pointer++; + } + if (changes3) { + this.diff_cleanupMerge(diffs); + } + this.diff_cleanupSemanticLossless(diffs); + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] == DIFF_DELETE5 && diffs[pointer][0] == DIFF_INSERT5) { + 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_patch4.Diff( + DIFF_EQUAL4, + 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_patch4.Diff( + DIFF_EQUAL4, + deletion.substring(0, overlap_length2) + )); + diffs[pointer - 1][0] = DIFF_INSERT5; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1][0] = DIFF_DELETE5; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; + diff_match_patch4.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_patch4.nonAlphaNumericRegex_); + var nonAlphaNumeric2 = char2.match(diff_match_patch4.nonAlphaNumericRegex_); + var whitespace1 = nonAlphaNumeric1 && char1.match(diff_match_patch4.whitespaceRegex_); + var whitespace2 = nonAlphaNumeric2 && char2.match(diff_match_patch4.whitespaceRegex_); + var lineBreak1 = whitespace1 && char1.match(diff_match_patch4.linebreakRegex_); + var lineBreak2 = whitespace2 && char2.match(diff_match_patch4.linebreakRegex_); + var blankLine1 = lineBreak1 && one.match(diff_match_patch4.blanklineEndRegex_); + var blankLine2 = lineBreak2 && two.match(diff_match_patch4.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_EQUAL4 && diffs[pointer + 1][0] == DIFF_EQUAL4) { + 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_patch4.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; + diff_match_patch4.whitespaceRegex_ = /\s/; + diff_match_patch4.linebreakRegex_ = /[\r\n]/; + diff_match_patch4.blanklineEndRegex_ = /\n\r?\n$/; + diff_match_patch4.blanklineStartRegex_ = /^\r?\n\r?\n/; + diff_match_patch4.prototype.diff_cleanupEfficiency = function(diffs) { + var changes3 = 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_EQUAL4) { + 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_DELETE5) { + 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_patch4.Diff(DIFF_DELETE5, lastEquality) + ); + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT5; + 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; + } + changes3 = true; + } + } + pointer++; + } + if (changes3) { + this.diff_cleanupMerge(diffs); + } + }; + diff_match_patch4.prototype.diff_cleanupMerge = function(diffs) { + diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, "")); + 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_INSERT5: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE5: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL4: + 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_EQUAL4) { + diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); + } else { + diffs.splice(0, 0, new diff_match_patch4.Diff( + DIFF_EQUAL4, + 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_patch4.Diff(DIFF_DELETE5, text_delete) + ); + pointer++; + } + if (text_insert.length) { + diffs.splice( + pointer, + 0, + new diff_match_patch4.Diff(DIFF_INSERT5, text_insert) + ); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL4) { + 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 changes3 = false; + pointer = 1; + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] == DIFF_EQUAL4 && diffs[pointer + 1][0] == DIFF_EQUAL4) { + 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); + changes3 = 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); + changes3 = true; + } + } + pointer++; + } + if (changes3) { + this.diff_cleanupMerge(diffs); + } + }; + diff_match_patch4.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_INSERT5) { + chars1 += diffs[x][1].length; + } + if (diffs[x][0] !== DIFF_DELETE5) { + chars2 += diffs[x][1].length; + } + if (chars1 > loc) { + break; + } + last_chars1 = chars1; + last_chars2 = chars2; + } + if (diffs.length != x && diffs[x][0] === DIFF_DELETE5) { + return last_chars2; + } + return last_chars2 + (loc - last_chars1); + }; + diff_match_patch4.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_INSERT5: + html[x] = '' + text2 + ""; + break; + case DIFF_DELETE5: + html[x] = '' + text2 + ""; + break; + case DIFF_EQUAL4: + html[x] = "" + text2 + ""; + break; + } + } + return html.join(""); + }; + diff_match_patch4.prototype.diff_text1 = function(diffs) { + var text2 = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x][0] !== DIFF_INSERT5) { + text2[x] = diffs[x][1]; + } + } + return text2.join(""); + }; + diff_match_patch4.prototype.diff_text2 = function(diffs) { + var text2 = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x][0] !== DIFF_DELETE5) { + text2[x] = diffs[x][1]; + } + } + return text2.join(""); + }; + diff_match_patch4.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_INSERT5: + insertions += data.length; + break; + case DIFF_DELETE5: + deletions += data.length; + break; + case DIFF_EQUAL4: + levenshtein += Math.max(insertions, deletions); + insertions = 0; + deletions = 0; + break; + } + } + levenshtein += Math.max(insertions, deletions); + return levenshtein; + }; + diff_match_patch4.prototype.diff_toDelta = function(diffs) { + var text2 = []; + for (var x = 0; x < diffs.length; x++) { + switch (diffs[x][0]) { + case DIFF_INSERT5: + text2[x] = "+" + encodeURI(diffs[x][1]); + break; + case DIFF_DELETE5: + text2[x] = "-" + diffs[x][1].length; + break; + case DIFF_EQUAL4: + text2[x] = "=" + diffs[x][1].length; + break; + } + } + return text2.join(" ").replace(/%20/g, " "); + }; + diff_match_patch4.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_patch4.Diff(DIFF_INSERT5, decodeURI(param)); + } catch (ex) { + throw new Error("Illegal escape in diff_fromDelta: " + param); + } + break; + case "-": + case "=": + var n2 = parseInt(param, 10); + if (isNaN(n2) || n2 < 0) { + throw new Error("Invalid number in diff_fromDelta: " + param); + } + var text2 = text1.substring(pointer, pointer += n2); + if (tokens[x].charAt(0) == "=") { + diffs[diffsLength++] = new diff_match_patch4.Diff(DIFF_EQUAL4, text2); + } else { + diffs[diffsLength++] = new diff_match_patch4.Diff(DIFF_DELETE5, 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_patch4.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_patch4.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_(e2, x) { + var accuracy = e2 / 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_patch4.prototype.match_alphabet_ = function(pattern) { + var s = {}; + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] = 0; + } + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] |= 1 << pattern.length - i - 1; + } + return s; + }; + diff_match_patch4.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_patch4.Diff(DIFF_EQUAL4, prefix)); + } + var suffix = text2.substring( + patch.start2 + patch.length1, + patch.start2 + patch.length1 + padding + ); + if (suffix) { + patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, suffix)); + } + patch.start1 -= prefix.length; + patch.start2 -= prefix.length; + patch.length1 += prefix.length + suffix.length; + patch.length2 += prefix.length + suffix.length; + }; + diff_match_patch4.prototype.patch_make = function(a2, opt_b, opt_c) { + var text1, diffs; + if (typeof a2 == "string" && typeof opt_b == "string" && typeof opt_c == "undefined") { + text1 = a2; + diffs = this.diff_main(text1, opt_b, true); + if (diffs.length > 2) { + this.diff_cleanupSemantic(diffs); + this.diff_cleanupEfficiency(diffs); + } + } else if (a2 && typeof a2 == "object" && typeof opt_b == "undefined" && typeof opt_c == "undefined") { + diffs = a2; + text1 = this.diff_text1(diffs); + } else if (typeof a2 == "string" && opt_b && typeof opt_b == "object" && typeof opt_c == "undefined") { + text1 = a2; + diffs = opt_b; + } else if (typeof a2 == "string" && typeof opt_b == "string" && opt_c && typeof opt_c == "object") { + text1 = a2; + 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_patch4.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_EQUAL4) { + patch.start1 = char_count1; + patch.start2 = char_count2; + } + switch (diff_type) { + case DIFF_INSERT5: + 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_DELETE5: + 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_EQUAL4: + 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_patch4.patch_obj(); + patchDiffLength = 0; + prepatch_text = postpatch_text; + char_count1 = char_count2; + } + } + break; + } + if (diff_type !== DIFF_INSERT5) { + char_count1 += diff_text.length; + } + if (diff_type !== DIFF_DELETE5) { + char_count2 += diff_text.length; + } + } + if (patchDiffLength) { + this.patch_addContext_(patch, prepatch_text); + patches.push(patch); + } + return patches; + }; + diff_match_patch4.prototype.patch_deepCopy = function(patches) { + var patchesCopy = []; + for (var x = 0; x < patches.length; x++) { + var patch = patches[x]; + var patchCopy = new diff_match_patch4.patch_obj(); + patchCopy.diffs = []; + for (var y = 0; y < patch.diffs.length; y++) { + patchCopy.diffs[y] = new diff_match_patch4.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_patch4.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 index22; + for (var y = 0; y < patches[x].diffs.length; y++) { + var mod = patches[x].diffs[y]; + if (mod[0] !== DIFF_EQUAL4) { + index22 = this.diff_xIndex(diffs, index1); + } + if (mod[0] === DIFF_INSERT5) { + text2 = text2.substring(0, start_loc + index22) + mod[1] + text2.substring(start_loc + index22); + } else if (mod[0] === DIFF_DELETE5) { + text2 = text2.substring(0, start_loc + index22) + text2.substring(start_loc + this.diff_xIndex( + diffs, + index1 + mod[1].length + )); + } + if (mod[0] !== DIFF_DELETE5) { + index1 += mod[1].length; + } + } + } + } + } + } + text2 = text2.substring(nullPadding.length, text2.length - nullPadding.length); + return [text2, results]; + }; + diff_match_patch4.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_EQUAL4) { + diffs.unshift(new diff_match_patch4.Diff(DIFF_EQUAL4, 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_EQUAL4) { + diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, 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_patch4.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_patch4.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_patch4.Diff(DIFF_EQUAL4, 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_INSERT5) { + patch.length2 += diff_text.length; + start2 += diff_text.length; + patch.diffs.push(bigpatch.diffs.shift()); + empty2 = false; + } else if (diff_type === DIFF_DELETE5 && patch.diffs.length == 1 && patch.diffs[0][0] == DIFF_EQUAL4 && diff_text.length > 2 * patch_size) { + patch.length1 += diff_text.length; + start1 += diff_text.length; + empty2 = false; + patch.diffs.push(new diff_match_patch4.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_EQUAL4) { + patch.length2 += diff_text.length; + start2 += diff_text.length; + } else { + empty2 = false; + } + patch.diffs.push(new diff_match_patch4.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_EQUAL4) { + patch.diffs[patch.diffs.length - 1][1] += postcontext; + } else { + patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, postcontext)); + } + } + if (!empty2) { + patches.splice(++x, 0, patch); + } + } + } + }; + diff_match_patch4.prototype.patch_toText = function(patches) { + var text2 = []; + for (var x = 0; x < patches.length; x++) { + text2[x] = patches[x]; + } + return text2.join(""); + }; + diff_match_patch4.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_patch4.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_patch4.Diff(DIFF_DELETE5, line)); + } else if (sign == "+") { + patch.diffs.push(new diff_match_patch4.Diff(DIFF_INSERT5, line)); + } else if (sign == " ") { + patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4, line)); + } else if (sign == "@") { + break; + } else if (sign === "") { + } else { + throw new Error('Invalid patch mode "' + sign + '" in: ' + line); + } + textPointer++; + } + } + return patches; + }; + diff_match_patch4.patch_obj = function() { + this.diffs = []; + this.start1 = null; + this.start2 = null; + this.length1 = 0; + this.length2 = 0; + }; + diff_match_patch4.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_INSERT5: + op = "+"; + break; + case DIFF_DELETE5: + op = "-"; + break; + case DIFF_EQUAL4: + op = " "; + break; + } + text2[x + 1] = op + encodeURI(this.diffs[x][1]) + "\n"; + } + return text2.join("").replace(/%20/g, " "); + }; + module2.exports = diff_match_patch4; + module2.exports["diff_match_patch"] = diff_match_patch4; + module2.exports["DIFF_DELETE"] = DIFF_DELETE5; + module2.exports["DIFF_INSERT"] = DIFF_INSERT5; + module2.exports["DIFF_EQUAL"] = DIFF_EQUAL4; + } +}); + +// (disabled):node_modules/immediate/lib/nextTick +var require_nextTick = __commonJS({ + "(disabled):node_modules/immediate/lib/nextTick"() { + } +}); + +// node_modules/immediate/lib/queueMicrotask.js +var require_queueMicrotask = __commonJS({ + "node_modules/immediate/lib/queueMicrotask.js"(exports) { + "use strict"; + exports.test = function() { + return typeof window.queueMicrotask === "function"; + }; + exports.install = function(func) { + return function() { + window.queueMicrotask(func); + }; + }; + } +}); + +// node_modules/immediate/lib/mutation.js +var require_mutation = __commonJS({ + "node_modules/immediate/lib/mutation.js"(exports) { + "use strict"; + var Mutation = window.MutationObserver || window.WebKitMutationObserver; + exports.test = function() { + return Mutation; + }; + exports.install = function(handle) { + var called = 0; + var observer = new Mutation(handle); + var element2 = window.document.createTextNode(""); + observer.observe(element2, { + characterData: true + }); + return function() { + element2.data = called = ++called % 2; + }; + }; + } +}); + +// node_modules/immediate/lib/messageChannel.js +var require_messageChannel = __commonJS({ + "node_modules/immediate/lib/messageChannel.js"(exports) { + "use strict"; + exports.test = function() { + if (window.setImmediate) { + return false; + } + return typeof window.MessageChannel !== "undefined"; + }; + exports.install = function(func) { + var channel = new window.MessageChannel(); + channel.port1.onmessage = func; + return function() { + channel.port2.postMessage(0); + }; + }; + } +}); + +// node_modules/immediate/lib/stateChange.js +var require_stateChange = __commonJS({ + "node_modules/immediate/lib/stateChange.js"(exports) { + "use strict"; + exports.test = function() { + return "document" in window && "onreadystatechange" in window.document.createElement("script"); + }; + exports.install = function(handle) { + return function() { + var scriptEl = window.document.createElement("script"); + scriptEl.onreadystatechange = function() { + handle(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + window.document.documentElement.appendChild(scriptEl); + return handle; + }; + }; + } +}); + +// node_modules/immediate/lib/timeout.js +var require_timeout = __commonJS({ + "node_modules/immediate/lib/timeout.js"(exports) { + "use strict"; + exports.test = function() { + return true; + }; + exports.install = function(t2) { + return function() { + setTimeout(t2, 0); + }; + }; + } +}); + +// node_modules/immediate/lib/index.js +var require_lib = __commonJS({ + "node_modules/immediate/lib/index.js"(exports, module2) { + "use strict"; + var types = [ + require_nextTick(), + require_queueMicrotask(), + require_mutation(), + require_messageChannel(), + require_stateChange(), + require_timeout() + ]; + var draining; + var currentQueue; + var queueIndex = -1; + var queue2 = []; + var scheduled = false; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue2 = currentQueue.concat(queue2); + } else { + queueIndex = -1; + } + if (queue2.length) { + nextTick(); + } + } + function nextTick() { + if (draining) { + return; + } + scheduled = false; + draining = true; + var len2 = queue2.length; + var timeout = setTimeout(cleanUpNextTick); + while (len2) { + currentQueue = queue2; + queue2 = []; + while (currentQueue && ++queueIndex < len2) { + currentQueue[queueIndex].run(); + } + queueIndex = -1; + len2 = queue2.length; + } + currentQueue = null; + queueIndex = -1; + draining = false; + clearTimeout(timeout); + } + var scheduleDrain; + var i = -1; + var len = types.length; + while (++i < len) { + if (types[i] && types[i].test && types[i].test()) { + scheduleDrain = types[i].install(nextTick); + break; + } + } + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function() { + var fun = this.fun; + var array = this.array; + switch (array.length) { + case 0: + return fun(); + case 1: + return fun(array[0]); + case 2: + return fun(array[0], array[1]); + case 3: + return fun(array[0], array[1], array[2]); + default: + return fun.apply(null, array); + } + }; + module2.exports = immediate2; + function immediate2(task) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i2 = 1; i2 < arguments.length; i2++) { + args[i2 - 1] = arguments[i2]; + } + } + queue2.push(new Item(task, args)); + if (!scheduled && !draining) { + scheduled = true; + scheduleDrain(); + } + } + } +}); + +// node_modules/events/events.js +var require_events = __commonJS({ + "node_modules/events/events.js"(exports, module2) { + "use strict"; + var R = typeof Reflect === "object" ? Reflect : null; + var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + var ReflectOwnKeys; + if (R && typeof R.ownKeys === "function") { + ReflectOwnKeys = R.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }; + } + function ProcessEmitWarning(warning) { + if (console && console.warn) + console.warn(warning); + } + var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { + return value !== value; + }; + function EventEmitter2() { + EventEmitter2.init.call(this); + } + module2.exports = EventEmitter2; + module2.exports.once = once2; + EventEmitter2.EventEmitter = EventEmitter2; + EventEmitter2.prototype._events = void 0; + EventEmitter2.prototype._eventsCount = 0; + EventEmitter2.prototype._maxListeners = void 0; + var defaultMaxListeners = 10; + function checkListener(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + Object.defineProperty(EventEmitter2, "defaultMaxListeners", { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + } + }); + EventEmitter2.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + }; + EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n2) { + if (typeof n2 !== "number" || n2 < 0 || NumberIsNaN(n2)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n2 + "."); + } + this._maxListeners = n2; + return this; + }; + function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter2.defaultMaxListeners; + return that._maxListeners; + } + EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; + EventEmitter2.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) + args.push(arguments[i]); + var doError = type === "error"; + var events = this._events; + if (events !== void 0) + doError = doError && events.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events[type]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + return true; + }; + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + checkListener(listener); + events = target._events; + if (events === void 0) { + events = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + target.emit( + "newListener", + type, + listener.listener ? listener.listener : listener + ); + events = target._events; + } + existing = events[type]; + } + if (existing === void 0) { + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + return target; + } + EventEmitter2.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; + EventEmitter2.prototype.prependListener = function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: void 0, target, type, listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + EventEmitter2.prototype.once = function once3(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.removeListener = function removeListener(type, listener) { + var list, events, position, i, originalListener; + checkListener(listener); + events = this._events; + if (events === void 0) + return this; + list = events[type]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events[type] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type, originalListener || listener); + } + return this; + }; + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { + var listeners, events, i; + events = this._events; + if (events === void 0) + return this; + if (events.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type]; + } + return this; + } + if (arguments.length === 0) { + var keys2 = Object.keys(events); + var key; + for (i = 0; i < keys2.length; ++i) { + key = keys2[i]; + if (key === "removeListener") + continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners = events[type]; + if (typeof listeners === "function") { + this.removeListener(type, listeners); + } else if (listeners !== void 0) { + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + return this; + }; + function _listeners(target, type, unwrap2) { + var events = target._events; + if (events === void 0) + return []; + var evlistener = events[type]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap2 ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap2 ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + } + EventEmitter2.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; + EventEmitter2.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; + EventEmitter2.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } else { + return listenerCount2.call(emitter, type); + } + }; + EventEmitter2.prototype.listenerCount = listenerCount2; + function listenerCount2(type) { + var events = this._events; + if (events !== void 0) { + var evlistener = events[type]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; + } + EventEmitter2.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; + function arrayClone(arr, n2) { + var copy = new Array(n2); + for (var i = 0; i < n2; ++i) + copy[i] = arr[i]; + return copy; + } + function spliceOne(list, index5) { + for (; index5 + 1 < list.length; index5++) + list[index5] = list[index5 + 1]; + list.pop(); + } + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + function once2(emitter, name) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + ; + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } + } + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + } +}); + +// node_modules/spark-md5/spark-md5.js +var require_spark_md5 = __commonJS({ + "node_modules/spark-md5/spark-md5.js"(exports, module2) { + (function(factory) { + if (typeof exports === "object") { + module2.exports = factory(); + } else if (typeof define === "function" && define.amd) { + define(factory); + } else { + var glob; + try { + glob = window; + } catch (e2) { + glob = self; + } + glob.SparkMD5 = factory(); + } + })(function(undefined2) { + "use strict"; + var add32 = function(a2, b) { + return a2 + b & 4294967295; + }, hex_chr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + function cmn(q, a2, b, x, s, t2) { + a2 = add32(add32(a2, q), add32(x, t2)); + return add32(a2 << s | a2 >>> 32 - s, b); + } + function md5cycle(x, k) { + var a2 = x[0], b = x[1], c = x[2], d = x[3]; + a2 += (b & c | ~b & d) + k[0] - 680876936 | 0; + a2 = (a2 << 7 | a2 >>> 25) + b | 0; + d += (a2 & b | ~a2 & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a2 | 0; + c += (d & a2 | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a2) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a2 += (b & c | ~b & d) + k[4] - 176418897 | 0; + a2 = (a2 << 7 | a2 >>> 25) + b | 0; + d += (a2 & b | ~a2 & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a2 | 0; + c += (d & a2 | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a2) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a2 += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a2 = (a2 << 7 | a2 >>> 25) + b | 0; + d += (a2 & b | ~a2 & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a2 | 0; + c += (d & a2 | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a2) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a2 += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a2 = (a2 << 7 | a2 >>> 25) + b | 0; + d += (a2 & b | ~a2 & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a2 | 0; + c += (d & a2 | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a2) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a2 += (b & d | c & ~d) + k[1] - 165796510 | 0; + a2 = (a2 << 5 | a2 >>> 27) + b | 0; + d += (a2 & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a2 | 0; + c += (d & b | a2 & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a2 | d & ~a2) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a2 += (b & d | c & ~d) + k[5] - 701558691 | 0; + a2 = (a2 << 5 | a2 >>> 27) + b | 0; + d += (a2 & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a2 | 0; + c += (d & b | a2 & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a2 | d & ~a2) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a2 += (b & d | c & ~d) + k[9] + 568446438 | 0; + a2 = (a2 << 5 | a2 >>> 27) + b | 0; + d += (a2 & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a2 | 0; + c += (d & b | a2 & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a2 | d & ~a2) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a2 += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a2 = (a2 << 5 | a2 >>> 27) + b | 0; + d += (a2 & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a2 | 0; + c += (d & b | a2 & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a2 | d & ~a2) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a2 += (b ^ c ^ d) + k[5] - 378558 | 0; + a2 = (a2 << 4 | a2 >>> 28) + b | 0; + d += (a2 ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a2 | 0; + c += (d ^ a2 ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a2) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a2 += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a2 = (a2 << 4 | a2 >>> 28) + b | 0; + d += (a2 ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a2 | 0; + c += (d ^ a2 ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a2) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a2 += (b ^ c ^ d) + k[13] + 681279174 | 0; + a2 = (a2 << 4 | a2 >>> 28) + b | 0; + d += (a2 ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a2 | 0; + c += (d ^ a2 ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a2) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a2 += (b ^ c ^ d) + k[9] - 640364487 | 0; + a2 = (a2 << 4 | a2 >>> 28) + b | 0; + d += (a2 ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a2 | 0; + c += (d ^ a2 ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a2) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a2 += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a2 = (a2 << 6 | a2 >>> 26) + b | 0; + d += (b ^ (a2 | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a2 | 0; + c += (a2 ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a2)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a2 += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a2 = (a2 << 6 | a2 >>> 26) + b | 0; + d += (b ^ (a2 | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a2 | 0; + c += (a2 ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a2)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a2 += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a2 = (a2 << 6 | a2 >>> 26) + b | 0; + d += (b ^ (a2 | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a2 | 0; + c += (a2 ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a2)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a2 += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a2 = (a2 << 6 | a2 >>> 26) + b | 0; + d += (b ^ (a2 | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a2 | 0; + c += (a2 ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a2)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a2 + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + function md5blk(s) { + var md5blks = [], i; + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); + } + return md5blks; + } + function md5blk_array(a2) { + var md5blks = [], i; + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = a2[i] + (a2[i + 1] << 8) + (a2[i + 2] << 16) + (a2[i + 3] << 24); + } + return md5blks; + } + function md51(s) { + var n2 = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i, length, tail, tmp, lo, hi; + for (i = 64; i <= n2; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); + } + s = s.substring(i - 64); + length = s.length; + tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < length; i += 1) { + tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3); + } + tail[i >> 2] |= 128 << (i % 4 << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i += 1) { + tail[i] = 0; + } + } + tmp = n2 * 8; + tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); + lo = parseInt(tmp[2], 16); + hi = parseInt(tmp[1], 16) || 0; + tail[14] = lo; + tail[15] = hi; + md5cycle(state, tail); + return state; + } + function md51_array(a2) { + var n2 = a2.length, state = [1732584193, -271733879, -1732584194, 271733878], i, length, tail, tmp, lo, hi; + for (i = 64; i <= n2; i += 64) { + md5cycle(state, md5blk_array(a2.subarray(i - 64, i))); + } + a2 = i - 64 < n2 ? a2.subarray(i - 64) : new Uint8Array(0); + length = a2.length; + tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < length; i += 1) { + tail[i >> 2] |= a2[i] << (i % 4 << 3); + } + tail[i >> 2] |= 128 << (i % 4 << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i += 1) { + tail[i] = 0; + } + } + tmp = n2 * 8; + tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); + lo = parseInt(tmp[2], 16); + hi = parseInt(tmp[1], 16) || 0; + tail[14] = lo; + tail[15] = hi; + md5cycle(state, tail); + return state; + } + function rhex(n2) { + var s = "", j; + for (j = 0; j < 4; j += 1) { + s += hex_chr[n2 >> j * 8 + 4 & 15] + hex_chr[n2 >> j * 8 & 15]; + } + return s; + } + function hex(x) { + var i; + for (i = 0; i < x.length; i += 1) { + x[i] = rhex(x[i]); + } + return x.join(""); + } + if (hex(md51("hello")) !== "5d41402abc4b2a76b9719d911017c592") { + add32 = function(x, y) { + var lsw = (x & 65535) + (y & 65535), msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 65535; + }; + } + if (typeof ArrayBuffer !== "undefined" && !ArrayBuffer.prototype.slice) { + (function() { + function clamp(val, length) { + val = val | 0 || 0; + if (val < 0) { + return Math.max(val + length, 0); + } + return Math.min(val, length); + } + ArrayBuffer.prototype.slice = function(from, to) { + var length = this.byteLength, begin = clamp(from, length), end = length, num, target, targetArray, sourceArray; + if (to !== undefined2) { + end = clamp(to, length); + } + if (begin > end) { + return new ArrayBuffer(0); + } + num = end - begin; + target = new ArrayBuffer(num); + targetArray = new Uint8Array(target); + sourceArray = new Uint8Array(this, begin, num); + targetArray.set(sourceArray); + return target; + }; + })(); + } + function toUtf8(str) { + if (/[\u0080-\uFFFF]/.test(str)) { + str = unescape(encodeURIComponent(str)); + } + return str; + } + function utf8Str2ArrayBuffer(str, returnUInt8Array) { + var length = str.length, buff = new ArrayBuffer(length), arr = new Uint8Array(buff), i; + for (i = 0; i < length; i += 1) { + arr[i] = str.charCodeAt(i); + } + return returnUInt8Array ? arr : buff; + } + function arrayBuffer2Utf8Str(buff) { + return String.fromCharCode.apply(null, new Uint8Array(buff)); + } + function concatenateArrayBuffers(first, second, returnUInt8Array) { + var result = new Uint8Array(first.byteLength + second.byteLength); + result.set(new Uint8Array(first)); + result.set(new Uint8Array(second), first.byteLength); + return returnUInt8Array ? result : result.buffer; + } + function hexToBinaryString(hex2) { + var bytes = [], length = hex2.length, x; + for (x = 0; x < length - 1; x += 2) { + bytes.push(parseInt(hex2.substr(x, 2), 16)); + } + return String.fromCharCode.apply(String, bytes); + } + function SparkMD5() { + this.reset(); + } + SparkMD5.prototype.append = function(str) { + this.appendBinary(toUtf8(str)); + return this; + }; + SparkMD5.prototype.appendBinary = function(contents) { + this._buff += contents; + this._length += contents.length; + var length = this._buff.length, i; + for (i = 64; i <= length; i += 64) { + md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i))); + } + this._buff = this._buff.substring(i - 64); + return this; + }; + SparkMD5.prototype.end = function(raw) { + var buff = this._buff, length = buff.length, i, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ret; + for (i = 0; i < length; i += 1) { + tail[i >> 2] |= buff.charCodeAt(i) << (i % 4 << 3); + } + this._finish(tail, length); + ret = hex(this._hash); + if (raw) { + ret = hexToBinaryString(ret); + } + this.reset(); + return ret; + }; + SparkMD5.prototype.reset = function() { + this._buff = ""; + this._length = 0; + this._hash = [1732584193, -271733879, -1732584194, 271733878]; + return this; + }; + SparkMD5.prototype.getState = function() { + return { + buff: this._buff, + length: this._length, + hash: this._hash.slice() + }; + }; + SparkMD5.prototype.setState = function(state) { + this._buff = state.buff; + this._length = state.length; + this._hash = state.hash; + return this; + }; + SparkMD5.prototype.destroy = function() { + delete this._hash; + delete this._buff; + delete this._length; + }; + SparkMD5.prototype._finish = function(tail, length) { + var i = length, tmp, lo, hi; + tail[i >> 2] |= 128 << (i % 4 << 3); + if (i > 55) { + md5cycle(this._hash, tail); + for (i = 0; i < 16; i += 1) { + tail[i] = 0; + } + } + tmp = this._length * 8; + tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); + lo = parseInt(tmp[2], 16); + hi = parseInt(tmp[1], 16) || 0; + tail[14] = lo; + tail[15] = hi; + md5cycle(this._hash, tail); + }; + SparkMD5.hash = function(str, raw) { + return SparkMD5.hashBinary(toUtf8(str), raw); + }; + SparkMD5.hashBinary = function(content, raw) { + var hash = md51(content), ret = hex(hash); + return raw ? hexToBinaryString(ret) : ret; + }; + SparkMD5.ArrayBuffer = function() { + this.reset(); + }; + SparkMD5.ArrayBuffer.prototype.append = function(arr) { + var buff = concatenateArrayBuffers(this._buff.buffer, arr, true), length = buff.length, i; + this._length += arr.byteLength; + for (i = 64; i <= length; i += 64) { + md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i))); + } + this._buff = i - 64 < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0); + return this; + }; + SparkMD5.ArrayBuffer.prototype.end = function(raw) { + var buff = this._buff, length = buff.length, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], i, ret; + for (i = 0; i < length; i += 1) { + tail[i >> 2] |= buff[i] << (i % 4 << 3); + } + this._finish(tail, length); + ret = hex(this._hash); + if (raw) { + ret = hexToBinaryString(ret); + } + this.reset(); + return ret; + }; + SparkMD5.ArrayBuffer.prototype.reset = function() { + this._buff = new Uint8Array(0); + this._length = 0; + this._hash = [1732584193, -271733879, -1732584194, 271733878]; + return this; + }; + SparkMD5.ArrayBuffer.prototype.getState = function() { + var state = SparkMD5.prototype.getState.call(this); + state.buff = arrayBuffer2Utf8Str(state.buff); + return state; + }; + SparkMD5.ArrayBuffer.prototype.setState = function(state) { + state.buff = utf8Str2ArrayBuffer(state.buff, true); + return SparkMD5.prototype.setState.call(this, state); + }; + SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy; + SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish; + SparkMD5.ArrayBuffer.hash = function(arr, raw) { + var hash = md51_array(new Uint8Array(arr)), ret = hex(hash); + return raw ? hexToBinaryString(ret) : ret; + }; + return SparkMD5; + }); + } +}); + +// node_modules/vuvuzela/index.js +var require_vuvuzela = __commonJS({ + "node_modules/vuvuzela/index.js"(exports) { + "use strict"; + exports.stringify = function stringify3(input) { + var queue2 = []; + queue2.push({ obj: input }); + var res2 = ""; + var next, obj, prefix, val, i, arrayPrefix, keys2, k, key, value, objPrefix; + while (next = queue2.pop()) { + obj = next.obj; + prefix = next.prefix || ""; + val = next.val || ""; + res2 += prefix; + if (val) { + res2 += val; + } else if (typeof obj !== "object") { + res2 += typeof obj === "undefined" ? null : JSON.stringify(obj); + } else if (obj === null) { + res2 += "null"; + } else if (Array.isArray(obj)) { + queue2.push({ val: "]" }); + for (i = obj.length - 1; i >= 0; i--) { + arrayPrefix = i === 0 ? "" : ","; + queue2.push({ obj: obj[i], prefix: arrayPrefix }); + } + queue2.push({ val: "[" }); + } else { + keys2 = []; + for (k in obj) { + if (obj.hasOwnProperty(k)) { + keys2.push(k); + } + } + queue2.push({ val: "}" }); + for (i = keys2.length - 1; i >= 0; i--) { + key = keys2[i]; + value = obj[key]; + objPrefix = i > 0 ? "," : ""; + objPrefix += JSON.stringify(key) + ":"; + queue2.push({ obj: value, prefix: objPrefix }); + } + queue2.push({ val: "{" }); + } + } + return res2; + }; + function pop2(obj, stack, metaStack) { + var lastMetaElement = metaStack[metaStack.length - 1]; + if (obj === lastMetaElement.element) { + metaStack.pop(); + lastMetaElement = metaStack[metaStack.length - 1]; + } + var element2 = lastMetaElement.element; + var lastElementIndex = lastMetaElement.index; + if (Array.isArray(element2)) { + element2.push(obj); + } else if (lastElementIndex === stack.length - 2) { + var key = stack.pop(); + element2[key] = obj; + } else { + stack.push(obj); + } + } + exports.parse = function(str) { + var stack = []; + var metaStack = []; + var i = 0; + var collationIndex2, parsedNum, numChar; + var parsedString, lastCh, numConsecutiveSlashes, ch; + var arrayElement, objElement; + while (true) { + collationIndex2 = str[i++]; + if (collationIndex2 === "}" || collationIndex2 === "]" || typeof collationIndex2 === "undefined") { + if (stack.length === 1) { + return stack.pop(); + } else { + pop2(stack.pop(), stack, metaStack); + continue; + } + } + switch (collationIndex2) { + case " ": + case " ": + case "\n": + case ":": + case ",": + break; + case "n": + i += 3; + pop2(null, stack, metaStack); + break; + case "t": + i += 3; + pop2(true, stack, metaStack); + break; + case "f": + i += 4; + pop2(false, stack, metaStack); + break; + case "0": + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + case "-": + parsedNum = ""; + i--; + while (true) { + numChar = str[i++]; + if (/[\d\.\-e\+]/.test(numChar)) { + parsedNum += numChar; + } else { + i--; + break; + } + } + pop2(parseFloat(parsedNum), stack, metaStack); + break; + case '"': + parsedString = ""; + lastCh = void 0; + numConsecutiveSlashes = 0; + while (true) { + ch = str[i++]; + if (ch !== '"' || lastCh === "\\" && numConsecutiveSlashes % 2 === 1) { + parsedString += ch; + lastCh = ch; + if (lastCh === "\\") { + numConsecutiveSlashes++; + } else { + numConsecutiveSlashes = 0; + } + } else { + break; + } + } + pop2(JSON.parse('"' + parsedString + '"'), stack, metaStack); + break; + case "[": + arrayElement = { element: [], index: stack.length }; + stack.push(arrayElement.element); + metaStack.push(arrayElement); + break; + case "{": + objElement = { element: {}, index: stack.length }; + stack.push(objElement.element); + metaStack.push(objElement); + break; + default: + throw new Error( + "unexpectedly reached end of input: " + collationIndex2 + ); + } + } + }; + } +}); + +// node_modules/pouchdb-wrappers/index.js +var require_pouchdb_wrappers = __commonJS({ + "node_modules/pouchdb-wrappers/index.js"(exports, module2) { + "use strict"; + function nodify(promise, callback) { + promise.then((...args) => { + callback(null, ...args); + }).catch((err) => { + callback(err); + }); + } + function installWrappers(base, handlers = {}) { + if (!base._originals || !base._handlers) { + base._originals = {}; + base._handlers = {}; + } + for (const [method, handler] of Object.entries(handlers)) { + if (!(method in base)) { + throw new Error(`Method '${method}' does not exist on given base, so it cannot be wrapped.`); + } + if (!(method in base._originals)) { + base._originals[method] = base[method]; + } + if (method in base._handlers) { + base._handlers[method].unshift(handler); + } else { + base._handlers[method] = [handler]; + base[method] = replacementMethod(base, method); + } + } + } + function replacementMethod(base, method) { + return function(...args) { + function doMethod() { + let callback = null; + const minArgs = method === "query" ? 1 : 0; + if (args.length > minArgs && typeof args[args.length - 1] === "function") { + callback = args.pop(); + } + let prev = base._originals[method].bind(base); + for (const handler of base._handlers[method]) { + prev = handler.bind(base, prev); + } + const result = prev(...args); + if (result.then && callback) { + nodify(result, callback); + } + return result; + } + if (method !== "changes" && base.taskqueue && !base.taskqueue.isReady) { + const dbReady = new Promise((resolve, reject) => { + base.taskqueue.addTask((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + return dbReady.then(doMethod); + } else { + return doMethod(); + } + }; + } + function uninstallWrappers(base, handlers) { + if (!base._originals || !base._handlers) { + throw new Error("No wrapper methods installed, so no methods can be uninstalled."); + } + for (const [method, handler] of Object.entries(handlers)) { + const errorMessage = `Wrapper method for '${method}' not installed: ${handler.toString()}`; + if (!(method in base._handlers)) { + throw new Error(errorMessage); + } + const i = base._handlers[method].indexOf(handler); + if (i === -1) { + throw new Error(errorMessage); + } else { + base._handlers[method].splice(i, 1); + } + } + } + var toExport = { + install: installWrappers, + uninstall: uninstallWrappers + }; + try { + module2.exports = toExport; + } catch (e2) { + } + try { + window.PouchDBWrappers = toExport; + } catch (e2) { + } + } +}); + +// node_modules/transform-pouch/index.js +var require_transform_pouch = __commonJS({ + "node_modules/transform-pouch/index.js"(exports, module2) { + "use strict"; + var wrappers = require_pouchdb_wrappers(); + function isntInternalKey(key) { + return key[0] !== "_"; + } + function isUntransformable(doc) { + if (typeof doc._id === "string" && /^_local/.test(doc._id)) { + return true; + } + if (doc._deleted) { + return Object.keys(doc).filter(isntInternalKey).length === 0; + } + return false; + } + module2.exports = { + transform: transform2, + filter: transform2 + }; + function transform2(config) { + const db = this; + const incoming = function(doc) { + if (!isUntransformable(doc) && config.incoming) { + return config.incoming(doc); + } + return doc; + }; + const outgoing = function(doc) { + if (!isUntransformable(doc) && config.outgoing) { + return config.outgoing(doc); + } + return doc; + }; + const handlers = { + async get(orig, ...args) { + const response = await orig(...args); + if (Array.isArray(response)) { + await Promise.all(response.map(async (row) => { + if (row.ok) { + row.ok = await outgoing(row.ok); + } + })); + return response; + } else { + return outgoing(response); + } + }, + async bulkDocs(orig, docs, ...args) { + if (docs.docs) { + docs.docs = await Promise.all(docs.docs.map(incoming)); + } else { + docs = await Promise.all(docs.map(incoming)); + } + return orig(docs, ...args); + }, + async allDocs(orig, ...args) { + const response = await orig(...args); + await Promise.all(response.rows.map(async (row) => { + if (row.doc) { + row.doc = await outgoing(row.doc); + } + })); + return response; + }, + async bulkGet(orig, ...args) { + const mapDoc = async (doc) => { + if (doc.ok) { + return { ok: await outgoing(doc.ok) }; + } else { + return doc; + } + }; + const mapResult = async (result) => { + const { id, docs } = result; + if (id && docs && Array.isArray(docs)) { + return { id, docs: await Promise.all(docs.map(mapDoc)) }; + } else { + return result; + } + }; + let { results, ...res2 } = await orig(...args); + results = await Promise.all(results.map(mapResult)); + return { results, ...res2 }; + }, + changes(orig, ...args) { + async function modifyChange(change) { + if (change.doc) { + change.doc = await outgoing(change.doc); + return change; + } + return change; + } + async function modifyChanges(res2) { + if (res2.results) { + res2.results = await Promise.all(res2.results.map(modifyChange)); + return res2; + } + return res2; + } + const changes3 = orig(...args); + const { on: origOn, then: origThen } = changes3; + return Object.assign(changes3, { + on(event, listener) { + const origListener = listener; + if (event === "change") { + listener = async (change) => { + origListener(await modifyChange(change)); + }; + } else if (event === "complete") { + listener = async (res2) => { + origListener(await modifyChanges(res2)); + }; + } + return origOn.call(changes3, event, listener); + }, + then(resolve, reject) { + return origThen.call(changes3, modifyChanges).then(resolve, reject); + } + }); + } + }; + if (db.type() === "http") { + handlers.put = async function(orig, doc, ...args) { + doc = await incoming(doc); + return orig(doc, ...args); + }; + handlers.query = async function(orig, ...args) { + const response = await orig(...args); + await Promise.all(response.rows.map(async (row) => { + if (row.doc) { + row.doc = await outgoing(row.doc); + } + })); + return response; + }; + } + wrappers.install(db, handlers); + } + if (typeof window !== "undefined" && window.PouchDB) { + window.PouchDB.plugin(exports); + } + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => ObsidianLiveSyncPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_diff_match_patch4 = __toESM(require_diff_match_patch(), 1); + +// src/deps.ts +var import_obsidian = require("obsidian"); + +// src/lib/src/types.ts +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: "", + 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: 50, + batches_limit: 40, + useHistory: false, + disableRequestURI: false, + skipOlderFilesOnSync: true, + checkConflictOnlyOnOpen: false, + syncInternalFiles: false, + syncInternalFilesBeforeReplication: false, + syncInternalFilesIgnorePatterns: "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/", + syncInternalFilesInterval: 60, + additionalSuffixOfDatabaseName: "", + ignoreVersionCheck: false, + lastReadUpdates: 0, + deleteMetadataOfDeletedFiles: false, + syncIgnoreRegEx: "", + syncOnlyRegEx: "", + customChunkSize: 0, + readChunksOnline: true, + watchInternalFileChanges: true, + automaticallyDeleteMetadataOfDeletedFiles: 0, + disableMarkdownAutoMerge: false, + writeDocumentsIfConflicted: false, + useDynamicIterationCount: false, + syncAfterMerge: false, + configPassphraseStore: "", + encryptedPassphrase: "", + encryptedCouchDBConnection: "", + permitEmptyPassphrase: false, + useIndexedDBAdapter: false, + useTimeouts: false, + writeLogToTheFile: false, + hashCacheMaxCount: 300, + hashCacheMaxAmount: 50, + concurrencyOfReadChunksOnline: 100, + minimumIntervalOfReadChunksOnline: 333 +}; +var PREFIXMD_LOGFILE = "LIVESYNC_LOG_"; +var FLAGMD_REDFLAG = "redflag.md"; +var FLAGMD_REDFLAG2 = "redflag2.md"; +var FLAGMD_REDFLAG3 = "redflag3.md"; +var SYNCINFO_ID = "syncinfo"; +var SALT_OF_PASSPHRASE = "rHGMPtr6oWw7VSa3W3wpa8fT8U"; + +// src/types.ts +var PERIODIC_PLUGIN_SWEEP = 60; +var CHeader = "h:"; +var PSCHeader = "ps:"; +var PSCHeaderEnd = "ps;"; +var ICHeader = "i:"; +var ICHeaderEnd = "i;"; +var ICHeaderLength = ICHeader.length; +var FileWatchEventQueueMax = 10; +var configURIBase = "obsidian://setuplivesync?settings="; + +// src/lib/src/store.ts +var ReadOnlyObservableStore = class { +}; +var ObservableStore = class extends ReadOnlyObservableStore { + constructor(value) { + super(); + this.observers = []; + this.interceptors = []; + this.value = value; + } + set(value) { + if (this.value != value) { + let v = value; + if (this.interceptors.length > 0) { + for (const f3 of this.interceptors) { + v = f3(v); + } + } + this.value = v; + this.invalidate(); + } + } + apply(func) { + this.value = func(this.value); + this.invalidate(); + } + peek() { + return this.value; + } + invalidate() { + const value = this.value; + if (value === void 0) + return; + const watchers = this.observers; + for (const f3 of watchers) { + f3(value); + } + } + intercept(interceptor) { + this.interceptors.push(interceptor); + return () => this.removeInterceptor(interceptor); + } + removeInterceptor(interceptor) { + this.interceptors = this.interceptors.filter((e2) => e2 != interceptor); + } + observe(observer) { + this.observers.push(observer); + return () => this.unobserve(observer); + } + unobserve(observer) { + this.observers = this.observers.filter((e2) => e2 != observer); + } +}; +var StreamStore = class extends ObservableStore { + constructor(init3) { + super(init3 != null ? init3 : []); + this.itemInterceptors = []; + this.subscribers = []; + } + push(value) { + var _a; + let v = value; + for (const f3 of this.itemInterceptors) { + v = f3(v); + } + for (const f3 of this.subscribers) { + f3(v); + } + this.set([...(_a = this.value) != null ? _a : [], v]); + } + pop() { + var _a; + const v = [...(_a = this.value) != null ? _a : []]; + const val = v.pop(); + this.set(v); + return val; + } + unshift(value) { + var _a; + let v = value; + for (const f3 of this.itemInterceptors) { + v = f3(v); + } + for (const f3 of this.subscribers) { + f3(v); + } + this.set([v, ...(_a = this.value) != null ? _a : []]); + } + shift() { + var _a; + const [val, ...rest] = [...(_a = this.value) != null ? _a : []]; + this.set(rest); + return val; + } + subscribe(subscriber) { + this.subscribers.push(subscriber); + return () => this.unsubscribe(subscriber); + } + unsubscribe(subscriber) { + this.subscribers = this.subscribers.filter((e2) => e2 != subscriber); + } + interceptEach(interceptor) { + this.itemInterceptors.push(interceptor); + return () => this.removeEachInterceptor(interceptor); + } + removeEachInterceptor(interceptor) { + this.itemInterceptors = this.itemInterceptors.filter((e2) => e2 != interceptor); + } +}; +var globalStore = /* @__PURE__ */ new Map(); +var globalStream = /* @__PURE__ */ new Map(); +function getGlobalStore(name, init3) { + if (!globalStore.has(name)) { + globalStore.set(name, new ObservableStore(init3)); + } + return globalStore.get(name); +} +function getGlobalStreamStore(name, init3) { + if (!globalStream.has(name)) { + globalStream.set(name, new StreamStore(init3)); + } + return globalStream.get(name); +} +function observeStores(storeA, storeB) { + const value = { ...storeA.peek(), ...storeB.peek() }; + const store = new ObservableStore(value); + storeA.observe((value2) => store.apply((e2) => ({ ...e2, ...value2 }))); + storeB.observe((value2) => store.apply((e2) => ({ ...e2, ...value2 }))); + return store; +} + +// src/lib/src/stores.ts +var lockStore = getGlobalStore("locks", { pending: [], running: [], count: 0 }); +var waitingData = getGlobalStore("processingLast", 0); +var logStore = getGlobalStreamStore("logs", []); +var logMessageStore = getGlobalStore("logMessage", []); + +// src/lib/src/logger.ts +function Logger(message, level, key) { + const entry = { message, level, key }; + logStore.push(entry); +} +logStore.intercept((e2) => e2.slice(Math.min(e2.length - 200, 0))); + +// src/lib/src/e2ee_v2.ts +var import_crypto = require("crypto"); + +// src/lib/src/strbin.ts +var revMap = {}; +var numMap = {}; +for (let i = 0; i < 256; i++) { + revMap[`00${i.toString(16)}`.slice(-2)] = i; + numMap[i] = `00${i.toString(16)}`.slice(-2); +} +function hexStringToUint8Array(src) { + const len = src.length / 2; + const ret = new Uint8Array(len); + for (let i = 0; i < len; i++) { + ret[i] = revMap[src[i * 2] + src[i * 2 + 1]]; + } + return ret; +} +function uint8ArrayToHexString(src) { + return [...src].map((e2) => numMap[e2]).join(""); +} +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 QUANTUM = 32768; +var writeString = (string) => { + const buffer = new Uint8Array(string.length * 4); + const length = string.length; + let index5 = 0; + let chr = 0; + let idx = 0; + while (idx < length) { + chr = string.charCodeAt(idx++); + if (chr < 128) { + buffer[index5++] = chr; + } else if (chr < 2048) { + buffer[index5++] = 192 | chr >>> 6; + buffer[index5++] = 128 | chr & 63; + } else if (chr < 55296 || chr > 57343) { + buffer[index5++] = 224 | chr >>> 12; + buffer[index5++] = 128 | chr >>> 6 & 63; + buffer[index5++] = 128 | chr & 63; + } else { + chr = (chr - 55296 << 10 | string.charCodeAt(idx++) - 56320) + 65536; + buffer[index5++] = 240 | chr >>> 18; + buffer[index5++] = 128 | chr >>> 12 & 63; + buffer[index5++] = 128 | chr >>> 6 & 63; + buffer[index5++] = 128 | chr & 63; + } + } + return buffer.slice(0, index5); +}; +var readString = (buffer) => { + const length = buffer.length; + let index5 = 0; + const end = length; + let string = ""; + while (index5 < end) { + const chunk = []; + const cEnd = Math.min(index5 + QUANTUM, end); + while (index5 < cEnd) { + const chr = buffer[index5++]; + if (chr < 128) { + chunk.push(chr); + } else if ((chr & 224) === 192) { + chunk.push((chr & 31) << 6 | buffer[index5++] & 63); + } else if ((chr & 240) === 224) { + chunk.push((chr & 15) << 12 | (buffer[index5++] & 63) << 6 | buffer[index5++] & 63); + } else if ((chr & 248) === 240) { + let code = (chr & 7) << 18 | (buffer[index5++] & 63) << 12 | (buffer[index5++] & 63) << 6 | buffer[index5++] & 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 i = 0; i < len; i += QUANTUM) { + ret += String.fromCharCode( + ...src.slice(i, i + QUANTUM) + ); + } + return ret; +} +var encodeChunkSize = 3 * 5e7; +function arrayBufferToBase64internalBrowser(buffer) { + return new Promise((res2, rej) => { + const blob = new Blob([buffer], { type: "application/octet-binary" }); + const reader = new FileReader(); + reader.onload = function(evt) { + var _a, _b; + const dataURI = ((_b = (_a = evt.target) == null ? void 0 : _a.result) == null ? void 0 : _b.toString()) || ""; + if (buffer.byteLength != 0 && (dataURI == "" || dataURI == "data:")) + return rej(new TypeError("Could not parse the encoded string")); + const result = dataURI.substring(dataURI.indexOf(",") + 1); + res2(result); + }; + reader.readAsDataURL(blob); + }); +} +function arrayBufferToBase64internalNode(buffer) { + const ret = Buffer.from(buffer.buffer).toString("base64"); + return ret; +} +var arrayBufferToBase64internal = typeof window !== "undefined" ? arrayBufferToBase64internalBrowser : arrayBufferToBase64internalNode; +async function arrayBufferToBase64(buffer) { + const bufLen = buffer.byteLength; + const pieces = []; + let idx = 0; + do { + const offset = idx * encodeChunkSize; + const pBuf = new DataView(buffer, offset, Math.min(encodeChunkSize, buffer.byteLength - offset)); + pieces.push(await arrayBufferToBase64internal(pBuf)); + idx++; + } while (idx * encodeChunkSize < bufLen); + return pieces; +} +function base64ToString(base64) { + try { + if (typeof base64 != "string") + return base64.map((e2) => base64ToString(e2)).join(""); + const binary_string = atob2(base64); + const len = binary_string.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binary_string.charCodeAt(i); + } + return readString(bytes); + } catch (ex) { + if (typeof base64 != "string") + return base64.join(""); + return base64; + } +} +function base64ToArrayBuffer(base64) { + if (typeof base64 == "string") + return base64ToArrayBufferInternal(base64); + const bufItems = base64.map((e2) => base64ToArrayBufferInternal(e2)); + const len = bufItems.reduce((p, c) => p + c.byteLength, 0); + const joinedArray = new Uint8Array(len); + let offset = 0; + bufItems.forEach((e2) => { + joinedArray.set(new Uint8Array(e2), offset); + offset += e2.byteLength; + }); + return joinedArray; +} +var base64ToArrayBufferInternal = typeof window !== "undefined" ? base64ToArrayBufferInternalBrowser : base64ToArrayBufferInternalNode; +function base64ToArrayBufferInternalNode(base64) { + try { + return Buffer.from(base64, "base64").buffer; + } catch (ex) { + return writeString(base64).buffer; + } +} +function base64ToArrayBufferInternalBrowser(base64) { + try { + const binary_string = atob2(base64); + const len = binary_string.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binary_string.charCodeAt(i); + } + return bytes.buffer; + } catch (ex) { + const len = base64.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = base64.charCodeAt(i); + } + return bytes.buffer; + } +} +function* pickPiece(leftData, minimumChunkSize) { + let buffer = ""; + L1: + do { + const curLine = leftData.shift(); + if (typeof curLine === "undefined") { + yield buffer; + break L1; + } + if (curLine.startsWith("```") || curLine.startsWith(" ```") || curLine.startsWith(" ```") || curLine.startsWith(" ```")) { + yield buffer; + buffer = curLine + (leftData.length != 0 ? "\n" : ""); + L2: + do { + const curPx = leftData.shift(); + if (typeof curPx === "undefined") { + break L2; + } + buffer += curPx + (leftData.length != 0 ? "\n" : ""); + } while (leftData.length > 0 && !(leftData[0].startsWith("```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```"))); + const isLooksLikeBASE64 = buffer.endsWith("="); + const maybeUneditable = buffer.length > 2048; + const endOfCodeBlock = leftData.shift(); + if (typeof endOfCodeBlock !== "undefined") { + buffer += endOfCodeBlock; + buffer += leftData.length != 0 ? "\n" : ""; + } + if (!isLooksLikeBASE64 && !maybeUneditable) { + const splitExpr = /(.*?[;,:<])/g; + const sx = buffer.split(splitExpr).filter((e2) => e2 != ""); + for (const v of sx) { + yield v; + } + } else { + yield buffer; + } + buffer = ""; + } else { + buffer += curLine + (leftData.length != 0 ? "\n" : ""); + if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") { + yield buffer; + buffer = ""; + } + } + } while (leftData.length > 0); +} +function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, longLineThreshold) { + return function* pieces() { + const dataList = typeof dataSrc == "string" ? [dataSrc] : dataSrc; + for (const data of dataList) { + if (plainSplit) { + const leftData = data.split("\n"); + const f3 = pickPiece(leftData, minimumChunkSize); + for (const piece of f3) { + let buffer = piece; + do { + let ps = pieceSize; + if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) { + ps++; + } + yield buffer.substring(0, ps); + buffer = buffer.substring(ps); + } while (buffer != ""); + } + } else { + let leftData = data; + do { + const piece = leftData.substring(0, pieceSize); + leftData = leftData.substring(pieceSize); + yield piece; + } while (leftData != ""); + } + } + }; +} +function versionNumberString2Number(version2) { + return version2.split(".").reverse().map((e2, i) => e2 / 1 * 1e3 ** i).reduce((prev, current) => prev + current, 0); +} +var escapeStringToHTML = (str) => { + if (!str) + return ""; + return str.replace(/[<>&"'`]/g, (match2) => { + const escape = { + "<": "<", + ">": ">", + "&": "&", + '"': """, + "'": "'", + "`": "`" + }; + return escape[match2]; + }); +}; + +// src/lib/src/e2ee_v2.ts +var webcrypto; +if (typeof window !== "undefined" && window.crypto) { + webcrypto = window.crypto; +} else { + const crypto2 = import_crypto.webcrypto; + webcrypto = crypto2; +} +var KeyBuffs = /* @__PURE__ */ new Map(); +var decKeyBuffs = /* @__PURE__ */ new Map(); +var KEY_RECYCLE_COUNT = 100; +var semiStaticFieldBuffer; +var nonceBuffer = new Uint32Array(1); +async function getKeyForEncrypt(passphrase, autoCalculateIterations) { + const buffKey = `${passphrase}-${autoCalculateIterations}`; + const f3 = KeyBuffs.get(buffKey); + if (f3) { + f3.count--; + if (f3.count > 0) { + return [f3.key, f3.salt]; + } + f3.count--; + } + const passphraseLen = 15 - passphrase.length; + const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5; + 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: iteration, + hash: "SHA-256" + }, + keyMaterial, + { name: "AES-GCM", length: 256 }, + false, + ["encrypt"] + ); + KeyBuffs.set(buffKey, { + 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, autoCalculateIterations) { + 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) + autoCalculateIterations; + const f3 = decKeyBuffs.get(bufKey); + if (f3) { + f3.count = decKeyIdx; + return [f3.key, f3.salt]; + } + const passphraseLen = 15 - passphrase.length; + const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5; + 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: iteration, + 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; +} +async function encrypt(input, passphrase, autoCalculateIterations) { + const [key, salt] = await getKeyForEncrypt(passphrase, autoCalculateIterations); + 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, autoCalculateIterations) { + try { + if (!encryptedResult.startsWith("[") || !encryptedResult.endsWith("]")) { + throw new Error("Encrypted data corrupted!"); + } + const w = encryptedResult.substring(1, encryptedResult.length - 1).split(",").map((e2) => e2[0] == '"' ? e2.substring(1, e2.length - 1) : e2); + const [encryptedData, ivString, salt] = w; + const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations); + const iv = hexStringToUint8Array(ivString); + const encryptedDataBin = atob2(encryptedData); + const len = encryptedDataBin.length; + const encryptedDataArrayBuffer = new Uint8Array(len); + for (let i = 0; i < len; i++) { + encryptedDataArrayBuffer[i] = encryptedDataBin.charCodeAt(i); + } + 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 tryDecrypt(encryptedResult, passphrase, autoCalculateIterations) { + if (!passphrase) + return false; + try { + return await decrypt(encryptedResult, passphrase, autoCalculateIterations); + } catch (ex) { + return false; + } +} +async function testCrypt() { + const src = "supercalifragilisticexpialidocious"; + const encoded = await encrypt(src, "passwordTest", false); + const decrypted = await decrypt(encoded, "passwordTest", false); + 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_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 version2 = versionInfo.version; + if (version2 < barrier) { + const versionUpResult = await migrate(version2, barrier); + if (versionUpResult) { + await bumpRemoteVersion(db); + return true; + } + } + if (version2 == barrier) + return true; + return false; + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + 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 (isErrorOfMissingDoc(ex)) { + const randomStrSrc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + const temp = [...Array(30)].map((e2) => Math.floor(Math.random() * randomStrSrc.length)).map((e2) => randomStrSrc[e2]).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 (isErrorOfMissingDoc(ex)) { + delete design._rev; + await db.put(design); + return true; + } else { + Logger("Could not make design documents", LOG_LEVEL.INFO); + } + } + return false; +} +var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt) => { + const decrypted = /* @__PURE__ */ 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, useDynamicIterationCount); + } 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, useDynamicIterationCount); + if (migrationDecrypt) { + decrypted.set(loadDoc._id, true); + } + } catch (ex) { + if (useDynamicIterationCount) { + try { + loadDoc.data = await decrypt(loadDoc.data, passphrase, false); + if (migrationDecrypt) { + decrypted.set(loadDoc._id, true); + } + } catch (ex2) { + if (migrationDecrypt && ex2.name == "SyntaxError") { + return loadDoc; + } + Logger("Decryption failed.", LOG_LEVEL.NOTICE); + Logger(ex2); + throw ex2; + } + } else { + Logger("Decryption failed.", LOG_LEVEL.NOTICE); + Logger(ex); + throw ex; + } + } + } + return loadDoc; + } + }); +}; +function isErrorOfMissingDoc(ex) { + return (ex && (ex == null ? void 0 : ex.status)) == 404; +} + +// src/lib/src/utils.ts +function resolveWithIgnoreKnownError(p, def) { + return new Promise((res2, rej) => { + p.then(res2).catch((ex) => isErrorOfMissingDoc(ex) ? res2(def) : rej(ex)); + }); +} +var delay = (ms) => { + return new Promise((res2) => { + setTimeout(() => { + res2(); + }, ms); + }); +}; +function getDocData(doc) { + return typeof doc == "string" ? doc : doc.join(""); +} +function getDocDataAsArray(doc) { + return typeof doc == "string" ? [doc] : doc; +} +var chunkCheckLen = 1e6; +function stringYielder(src) { + return function* gen() { + let buf = ""; + for (const piece of src) { + buf += piece; + while (buf.length > chunkCheckLen) { + const p = buf.slice(0, chunkCheckLen); + buf = buf.substring(chunkCheckLen); + yield p; + } + } + if (buf != "") + yield buf; + return; + }(); +} +function isDocContentSame(docA, docB) { + const docAArray = getDocDataAsArray(docA); + const docBArray = getDocDataAsArray(docB); + const chunkA = stringYielder(docAArray); + const chunkB = stringYielder(docBArray); + let genA; + let genB; + do { + genA = chunkA.next(); + genB = chunkB.next(); + if (genA.value != genB.value) { + return false; + } + if (genA.done != genB.done) { + return false; + } + } while (!genA.done); + if (!genB.done) + return false; + return true; +} + +// node_modules/pouchdb-collections/lib/index.es.js +function mangle(key) { + return "$" + key; +} +function unmangle(key) { + return key.substring(1); +} +function Map$1() { + this._store = {}; +} +Map$1.prototype.get = function(key) { + var mangled = mangle(key); + return this._store[mangled]; +}; +Map$1.prototype.set = function(key, value) { + var mangled = mangle(key); + this._store[mangled] = value; + return true; +}; +Map$1.prototype.has = function(key) { + var mangled = mangle(key); + return mangled in this._store; +}; +Map$1.prototype.keys = function() { + return Object.keys(this._store).map((k) => unmangle(k)); +}; +Map$1.prototype.delete = function(key) { + var mangled = mangle(key); + var res2 = mangled in this._store; + delete this._store[mangled]; + return res2; +}; +Map$1.prototype.forEach = function(cb) { + var keys2 = Object.keys(this._store); + for (var i = 0, len = keys2.length; i < len; i++) { + var key = keys2[i]; + var value = this._store[key]; + key = unmangle(key); + cb(value, key); + } +}; +Object.defineProperty(Map$1.prototype, "size", { + get: function() { + return Object.keys(this._store).length; + } +}); +function Set$1(array) { + this._store = new Map$1(); + if (array && Array.isArray(array)) { + for (var i = 0, len = array.length; i < len; i++) { + this.add(array[i]); + } + } +} +Set$1.prototype.add = function(key) { + return this._store.set(key, true); +}; +Set$1.prototype.has = function(key) { + return this._store.has(key); +}; +Set$1.prototype.forEach = function(cb) { + this._store.forEach(function(value, key) { + cb(key); + }); +}; +Object.defineProperty(Set$1.prototype, "size", { + get: function() { + return this._store.size; + } +}); +function supportsMapAndSet() { + if (typeof Symbol === "undefined" || typeof Map === "undefined" || typeof Set === "undefined") { + return false; + } + var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species); + return prop && "get" in prop && Map[Symbol.species] === Map; +} +var ExportedSet; +var ExportedMap; +{ + if (supportsMapAndSet()) { + ExportedSet = Set; + ExportedMap = Map; + } else { + ExportedSet = Set$1; + ExportedMap = Map$1; + } +} + +// node_modules/pouchdb-utils/lib/index-browser.es.js +var import_immediate = __toESM(require_lib()); + +// node_modules/pouchdb-errors/lib/index.es.js +var PouchError = class extends Error { + constructor(status, error, reason) { + super(); + this.status = status; + this.name = error; + this.message = reason; + this.error = true; + } + toString() { + return JSON.stringify({ + status: this.status, + name: this.name, + message: this.message, + reason: this.reason + }); + } +}; +var UNAUTHORIZED = new PouchError(401, "unauthorized", "Name or password is incorrect."); +var MISSING_BULK_DOCS = new PouchError(400, "bad_request", "Missing JSON list of 'docs'"); +var MISSING_DOC = new PouchError(404, "not_found", "missing"); +var REV_CONFLICT = new PouchError(409, "conflict", "Document update conflict"); +var INVALID_ID = new PouchError(400, "bad_request", "_id field must contain a string"); +var MISSING_ID = new PouchError(412, "missing_id", "_id is required for puts"); +var RESERVED_ID = new PouchError(400, "bad_request", "Only reserved document ids may start with underscore."); +var NOT_OPEN = new PouchError(412, "precondition_failed", "Database not open"); +var UNKNOWN_ERROR = new PouchError(500, "unknown_error", "Database encountered an unknown error"); +var BAD_ARG = new PouchError(500, "badarg", "Some query argument is invalid"); +var INVALID_REQUEST = new PouchError(400, "invalid_request", "Request was invalid"); +var QUERY_PARSE_ERROR = new PouchError(400, "query_parse_error", "Some query parameter is invalid"); +var DOC_VALIDATION = new PouchError(500, "doc_validation", "Bad special document member"); +var BAD_REQUEST = new PouchError(400, "bad_request", "Something wrong with the request"); +var NOT_AN_OBJECT = new PouchError(400, "bad_request", "Document must be a JSON object"); +var DB_MISSING = new PouchError(404, "not_found", "Database not found"); +var IDB_ERROR = new PouchError(500, "indexed_db_went_bad", "unknown"); +var WSQ_ERROR = new PouchError(500, "web_sql_went_bad", "unknown"); +var LDB_ERROR = new PouchError(500, "levelDB_went_went_bad", "unknown"); +var FORBIDDEN = new PouchError(403, "forbidden", "Forbidden by design doc validate_doc_update function"); +var INVALID_REV = new PouchError(400, "bad_request", "Invalid rev format"); +var FILE_EXISTS = new PouchError(412, "file_exists", "The database could not be created, the file already exists."); +var MISSING_STUB = new PouchError(412, "missing_stub", "A pre-existing attachment stub wasn't found"); +var INVALID_URL = new PouchError(413, "invalid_url", "Provided URL is invalid"); +function createError(error, reason) { + function CustomPouchError(reason2) { + var names = Object.getOwnPropertyNames(error); + for (var i = 0, len = names.length; i < len; i++) { + if (typeof error[names[i]] !== "function") { + this[names[i]] = error[names[i]]; + } + } + if (this.stack === void 0) { + this.stack = new Error().stack; + } + if (reason2 !== void 0) { + this.reason = reason2; + } + } + CustomPouchError.prototype = PouchError.prototype; + return new CustomPouchError(reason); +} +function generateErrorFromResponse(err) { + if (typeof err !== "object") { + var data = err; + err = UNKNOWN_ERROR; + err.data = data; + } + if ("error" in err && err.error === "conflict") { + err.name = "conflict"; + err.status = 409; + } + if (!("name" in err)) { + err.name = err.error || "unknown"; + } + if (!("status" in err)) { + err.status = 500; + } + if (!("message" in err)) { + err.message = err.message || err.reason; + } + if (!("stack" in err)) { + err.stack = new Error().stack; + } + return err; +} + +// node_modules/pouchdb-utils/lib/index-browser.es.js +var import_events = __toESM(require_events()); + +// node_modules/uuid/dist/esm-browser/rng.js +var getRandomValues; +var rnds8 = new Uint8Array(16); +function rng() { + if (!getRandomValues) { + getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== "undefined" && typeof msCrypto.getRandomValues === "function" && msCrypto.getRandomValues.bind(msCrypto); + if (!getRandomValues) { + throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); + } + } + return getRandomValues(rnds8); +} + +// node_modules/uuid/dist/esm-browser/regex.js +var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; + +// node_modules/uuid/dist/esm-browser/validate.js +function validate(uuid2) { + return typeof uuid2 === "string" && regex_default.test(uuid2); +} +var validate_default = validate; + +// node_modules/uuid/dist/esm-browser/stringify.js +var byteToHex = []; +for (i = 0; i < 256; ++i) { + byteToHex.push((i + 256).toString(16).substr(1)); +} +var i; +function stringify(arr) { + var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; + var uuid2 = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); + if (!validate_default(uuid2)) { + throw TypeError("Stringified UUID is invalid"); + } + return uuid2; +} +var stringify_default = stringify; + +// node_modules/uuid/dist/esm-browser/v4.js +function v4(options, buf, offset) { + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return stringify_default(rnds); +} +var v4_default = v4; + +// node_modules/pouchdb-binary-utils/lib/index-browser.es.js +var thisAtob = function(str) { + return atob(str); +}; +var thisBtoa = function(str) { + return btoa(str); +}; +function createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e2) { + if (e2.name !== "TypeError") { + throw e2; + } + var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} +function binaryStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} +function binStringToBluffer(binString, type) { + return createBlob([binaryStringToArrayBuffer(binString)], { type }); +} +function b64ToBluffer(b64, type) { + return binStringToBluffer(thisAtob(b64), type); +} +function arrayBufferToBinaryString(buffer) { + var binary = ""; + var bytes = new Uint8Array(buffer); + var length = bytes.byteLength; + for (var i = 0; i < length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return binary; +} +function readAsBinaryString(blob, callback) { + var reader = new FileReader(); + var hasBinaryString = typeof reader.readAsBinaryString === "function"; + reader.onloadend = function(e2) { + var result = e2.target.result || ""; + if (hasBinaryString) { + return callback(result); + } + callback(arrayBufferToBinaryString(result)); + }; + if (hasBinaryString) { + reader.readAsBinaryString(blob); + } else { + reader.readAsArrayBuffer(blob); + } +} +function blobToBinaryString(blobOrBuffer, callback) { + readAsBinaryString(blobOrBuffer, function(bin) { + callback(bin); + }); +} +function blobToBase64(blobOrBuffer, callback) { + blobToBinaryString(blobOrBuffer, function(base64) { + callback(thisBtoa(base64)); + }); +} +function readAsArrayBuffer(blob, callback) { + var reader = new FileReader(); + reader.onloadend = function(e2) { + var result = e2.target.result || new ArrayBuffer(0); + callback(result); + }; + reader.readAsArrayBuffer(blob); +} + +// node_modules/pouchdb-md5/lib/index-browser.es.js +var import_spark_md5 = __toESM(require_spark_md5()); +var setImmediateShim = self.setImmediate || self.setTimeout; +var MD5_CHUNK_SIZE = 32768; +function rawToBase64(raw) { + return thisBtoa(raw); +} +function sliceBlob(blob, start, end) { + if (blob.webkitSlice) { + return blob.webkitSlice(start, end); + } + return blob.slice(start, end); +} +function appendBlob(buffer, blob, start, end, callback) { + if (start > 0 || end < blob.size) { + blob = sliceBlob(blob, start, end); + } + readAsArrayBuffer(blob, function(arrayBuffer) { + buffer.append(arrayBuffer); + callback(); + }); +} +function appendString(buffer, string, start, end, callback) { + if (start > 0 || end < string.length) { + string = string.substring(start, end); + } + buffer.appendBinary(string); + callback(); +} +function binaryMd5(data, callback) { + var inputIsString = typeof data === "string"; + var len = inputIsString ? data.length : data.size; + var chunkSize = Math.min(MD5_CHUNK_SIZE, len); + var chunks = Math.ceil(len / chunkSize); + var currentChunk = 0; + var buffer = inputIsString ? new import_spark_md5.default() : new import_spark_md5.default.ArrayBuffer(); + var append2 = inputIsString ? appendString : appendBlob; + function next() { + setImmediateShim(loadNextChunk); + } + function done() { + var raw = buffer.end(true); + var base64 = rawToBase64(raw); + callback(base64); + buffer.destroy(); + } + function loadNextChunk() { + var start = currentChunk * chunkSize; + var end = start + chunkSize; + currentChunk++; + if (currentChunk < chunks) { + append2(buffer, data, start, end, next); + } else { + append2(buffer, data, start, end, done); + } + } + loadNextChunk(); +} +function stringMd5(string) { + return import_spark_md5.default.hash(string); +} + +// node_modules/pouchdb-utils/lib/index-browser.es.js +function isBinaryObject(object) { + return typeof ArrayBuffer !== "undefined" && object instanceof ArrayBuffer || typeof Blob !== "undefined" && object instanceof Blob; +} +function cloneArrayBuffer(buff) { + if (typeof buff.slice === "function") { + return buff.slice(0); + } + var target = new ArrayBuffer(buff.byteLength); + var targetArray = new Uint8Array(target); + var sourceArray = new Uint8Array(buff); + targetArray.set(sourceArray); + return target; +} +function cloneBinaryObject(object) { + if (object instanceof ArrayBuffer) { + return cloneArrayBuffer(object); + } + var size = object.size; + var type = object.type; + if (typeof object.slice === "function") { + return object.slice(0, size, type); + } + return object.webkitSlice(0, size, type); +} +var funcToString = Function.prototype.toString; +var objectCtorString = funcToString.call(Object); +function isPlainObject(value) { + var proto = Object.getPrototypeOf(value); + if (proto === null) { + return true; + } + var Ctor = proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; +} +function clone(object) { + var newObject; + var i; + var len; + if (!object || typeof object !== "object") { + return object; + } + if (Array.isArray(object)) { + newObject = []; + for (i = 0, len = object.length; i < len; i++) { + newObject[i] = clone(object[i]); + } + return newObject; + } + if (object instanceof Date && isFinite(object)) { + return object.toISOString(); + } + if (isBinaryObject(object)) { + return cloneBinaryObject(object); + } + if (!isPlainObject(object)) { + return object; + } + newObject = {}; + for (i in object) { + if (Object.prototype.hasOwnProperty.call(object, i)) { + var value = clone(object[i]); + if (typeof value !== "undefined") { + newObject[i] = value; + } + } + } + return newObject; +} +function once(fun) { + var called = false; + return function(...args) { + if (called) { + throw new Error("once called more than once"); + } else { + called = true; + fun.apply(this, args); + } + }; +} +function toPromise(func) { + return function(...args) { + args = clone(args); + var self2 = this; + var usedCB = typeof args[args.length - 1] === "function" ? args.pop() : false; + var promise = new Promise(function(fulfill, reject) { + var resp; + try { + var callback = once(function(err, mesg) { + if (err) { + reject(err); + } else { + fulfill(mesg); + } + }); + args.push(callback); + resp = func.apply(self2, args); + if (resp && typeof resp.then === "function") { + fulfill(resp); + } + } catch (e2) { + reject(e2); + } + }); + if (usedCB) { + promise.then(function(result) { + usedCB(null, result); + }, usedCB); + } + return promise; + }; +} +function logApiCall(self2, name, args) { + if (self2.constructor.listeners("debug").length) { + var logArgs = ["api", self2.name, name]; + for (var i = 0; i < args.length - 1; i++) { + logArgs.push(args[i]); + } + self2.constructor.emit("debug", logArgs); + var origCallback = args[args.length - 1]; + args[args.length - 1] = function(err, res2) { + var responseArgs = ["api", self2.name, name]; + responseArgs = responseArgs.concat( + err ? ["error", err] : ["success", res2] + ); + self2.constructor.emit("debug", responseArgs); + origCallback(err, res2); + }; + } +} +function adapterFun(name, callback) { + return toPromise(function(...args) { + if (this._closed) { + return Promise.reject(new Error("database is closed")); + } + if (this._destroyed) { + return Promise.reject(new Error("database is destroyed")); + } + var self2 = this; + logApiCall(self2, name, args); + if (!this.taskqueue.isReady) { + return new Promise(function(fulfill, reject) { + self2.taskqueue.addTask(function(failed) { + if (failed) { + reject(failed); + } else { + fulfill(self2[name].apply(self2, args)); + } + }); + }); + } + return callback.apply(this, args); + }); +} +function pick(obj, arr) { + var res2 = {}; + for (var i = 0, len = arr.length; i < len; i++) { + var prop = arr[i]; + if (prop in obj) { + res2[prop] = obj[prop]; + } + } + return res2; +} +var MAX_NUM_CONCURRENT_REQUESTS = 6; +function identityFunction(x) { + return x; +} +function formatResultForOpenRevsGet(result) { + return [{ + ok: result + }]; +} +function bulkGet(db, opts, callback) { + var requests = opts.docs; + var requestsById = new ExportedMap(); + requests.forEach(function(request) { + if (requestsById.has(request.id)) { + requestsById.get(request.id).push(request); + } else { + requestsById.set(request.id, [request]); + } + }); + var numDocs = requestsById.size; + var numDone = 0; + var perDocResults = new Array(numDocs); + function collapseResultsAndFinish() { + var results = []; + perDocResults.forEach(function(res2) { + res2.docs.forEach(function(info2) { + results.push({ + id: res2.id, + docs: [info2] + }); + }); + }); + callback(null, { results }); + } + function checkDone() { + if (++numDone === numDocs) { + collapseResultsAndFinish(); + } + } + function gotResult(docIndex, id, docs) { + perDocResults[docIndex] = { id, docs }; + checkDone(); + } + var allRequests = []; + requestsById.forEach(function(value, key) { + allRequests.push(key); + }); + var i = 0; + function nextBatch() { + if (i >= allRequests.length) { + return; + } + var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length); + var batch = allRequests.slice(i, upTo); + processBatch(batch, i); + i += batch.length; + } + function processBatch(batch, offset) { + batch.forEach(function(docId, j) { + var docIdx = offset + j; + var docRequests = requestsById.get(docId); + var docOpts = pick(docRequests[0], ["atts_since", "attachments"]); + docOpts.open_revs = docRequests.map(function(request) { + return request.rev; + }); + docOpts.open_revs = docOpts.open_revs.filter(identityFunction); + var formatResult = identityFunction; + if (docOpts.open_revs.length === 0) { + delete docOpts.open_revs; + formatResult = formatResultForOpenRevsGet; + } + ["revs", "attachments", "binary", "ajax", "latest"].forEach(function(param) { + if (param in opts) { + docOpts[param] = opts[param]; + } + }); + db.get(docId, docOpts, function(err, res2) { + var result; + if (err) { + result = [{ error: err }]; + } else { + result = formatResult(res2); + } + gotResult(docIdx, docId, result); + nextBatch(); + }); + }); + } + nextBatch(); +} +var hasLocal; +try { + localStorage.setItem("_pouch_check_localstorage", 1); + hasLocal = !!localStorage.getItem("_pouch_check_localstorage"); +} catch (e2) { + hasLocal = false; +} +function hasLocalStorage() { + return hasLocal; +} +var Changes = class extends import_events.default { + constructor() { + super(); + this._listeners = {}; + if (hasLocalStorage()) { + addEventListener("storage", (e2) => { + this.emit(e2.key); + }); + } + } + addListener(dbName, id, db, opts) { + if (this._listeners[id]) { + return; + } + var inprogress = false; + var self2 = this; + function eventFunction() { + if (!self2._listeners[id]) { + return; + } + if (inprogress) { + inprogress = "waiting"; + return; + } + inprogress = true; + var changesOpts = pick(opts, [ + "style", + "include_docs", + "attachments", + "conflicts", + "filter", + "doc_ids", + "view", + "since", + "query_params", + "binary", + "return_docs" + ]); + function onError() { + inprogress = false; + } + db.changes(changesOpts).on("change", function(c) { + if (c.seq > opts.since && !opts.cancelled) { + opts.since = c.seq; + opts.onChange(c); + } + }).on("complete", function() { + if (inprogress === "waiting") { + (0, import_immediate.default)(eventFunction); + } + inprogress = false; + }).on("error", onError); + } + this._listeners[id] = eventFunction; + this.on(dbName, eventFunction); + } + removeListener(dbName, id) { + if (!(id in this._listeners)) { + return; + } + super.removeListener(dbName, this._listeners[id]); + delete this._listeners[id]; + } + notifyLocalWindows(dbName) { + if (hasLocalStorage()) { + localStorage[dbName] = localStorage[dbName] === "a" ? "b" : "a"; + } + } + notify(dbName) { + this.emit(dbName); + this.notifyLocalWindows(dbName); + } +}; +function guardedConsole(method) { + if (typeof console !== "undefined" && typeof console[method] === "function") { + var args = Array.prototype.slice.call(arguments, 1); + console[method].apply(console, args); + } +} +function randomNumber(min, max2) { + var maxTimeout = 6e5; + min = parseInt(min, 10) || 0; + max2 = parseInt(max2, 10); + if (max2 !== max2 || max2 <= min) { + max2 = (min || 1) << 1; + } else { + max2 = max2 + 1; + } + if (max2 > maxTimeout) { + min = maxTimeout >> 1; + max2 = maxTimeout; + } + var ratio = Math.random(); + var range = max2 - min; + return ~~(range * ratio + min); +} +function defaultBackOff(min) { + var max2 = 0; + if (!min) { + max2 = 2e3; + } + return randomNumber(min, max2); +} +function explainError(status, str) { + guardedConsole("info", "The above " + status + " is totally normal. " + str); +} +var assign$1; +{ + if (typeof Object.assign === "function") { + assign$1 = Object.assign; + } else { + assign$1 = function(target) { + var to = Object(target); + for (var index5 = 1; index5 < arguments.length; index5++) { + var nextSource = arguments[index5]; + if (nextSource != null) { + for (var nextKey in nextSource) { + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; + } +} +var assign$2 = assign$1; +function tryFilter(filter2, doc, req) { + try { + return !filter2(doc, req); + } catch (err) { + var msg = "Filter function threw: " + err.toString(); + return createError(BAD_REQUEST, msg); + } +} +function filterChange(opts) { + var req = {}; + var hasFilter = opts.filter && typeof opts.filter === "function"; + req.query = opts.query_params; + return function filter2(change) { + if (!change.doc) { + change.doc = {}; + } + var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); + if (typeof filterReturn === "object") { + return filterReturn; + } + if (filterReturn) { + return false; + } + if (!opts.include_docs) { + delete change.doc; + } else if (!opts.attachments) { + for (var att in change.doc._attachments) { + if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) { + change.doc._attachments[att].stub = true; + } + } + } + return true; + }; +} +function flatten(arrs) { + var res2 = []; + for (var i = 0, len = arrs.length; i < len; i++) { + res2 = res2.concat(arrs[i]); + } + return res2; +} +function f() { +} +var hasName = f.name; +var res; +if (hasName) { + res = function(fun) { + return fun.name; + }; +} else { + res = function(fun) { + var match2 = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/); + if (match2 && match2[1]) { + return match2[1]; + } else { + return ""; + } + }; +} +function invalidIdError(id) { + var err; + if (!id) { + err = createError(MISSING_ID); + } else if (typeof id !== "string") { + err = createError(INVALID_ID); + } else if (/^_/.test(id) && !/^_(design|local)/.test(id)) { + err = createError(RESERVED_ID); + } + if (err) { + throw err; + } +} +function isRemote(db) { + if (typeof db._remote === "boolean") { + return db._remote; + } + if (typeof db.type === "function") { + guardedConsole( + "warn", + "db.type() is deprecated and will be removed in a future version of PouchDB" + ); + return db.type() === "http"; + } + return false; +} +function listenerCount(ee, type) { + return "listenerCount" in ee ? ee.listenerCount(type) : import_events.default.listenerCount(ee, type); +} +function parseDesignDocFunctionName(s) { + if (!s) { + return null; + } + var parts = s.split("/"); + if (parts.length === 2) { + return parts; + } + if (parts.length === 1) { + return [s, s]; + } + return null; +} +function normalizeDesignDocFunctionName(s) { + var normalized = parseDesignDocFunctionName(s); + return normalized ? normalized.join("/") : null; +} +var keys = [ + "source", + "protocol", + "authority", + "userInfo", + "user", + "password", + "host", + "port", + "relative", + "path", + "directory", + "file", + "query", + "anchor" +]; +var qName = "queryKey"; +var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g; +var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; +function parseUri(str) { + var m = parser.exec(str); + var uri = {}; + var i = 14; + while (i--) { + var key = keys[i]; + var value = m[i] || ""; + var encoded = ["user", "password"].indexOf(key) !== -1; + uri[key] = encoded ? decodeURIComponent(value) : value; + } + uri[qName] = {}; + uri[keys[12]].replace(qParser, function($0, $1, $2) { + if ($1) { + uri[qName][$1] = $2; + } + }); + return uri; +} +function scopeEval(source, scope) { + var keys2 = []; + var values = []; + for (var key in scope) { + if (Object.prototype.hasOwnProperty.call(scope, key)) { + keys2.push(key); + values.push(scope[key]); + } + } + keys2.push(source); + return Function.apply(null, keys2).apply(null, values); +} +function upsert(db, docId, diffFun) { + return db.get(docId).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return {}; + }).then(function(doc) { + var docRev = doc._rev; + var newDoc = diffFun(doc); + if (!newDoc) { + return { updated: false, rev: docRev }; + } + newDoc._id = docId; + newDoc._rev = docRev; + return tryAndPut(db, newDoc, diffFun); + }); +} +function tryAndPut(db, doc, diffFun) { + return db.put(doc).then(function(res2) { + return { + updated: true, + rev: res2.rev + }; + }, function(err) { + if (err.status !== 409) { + throw err; + } + return upsert(db, doc._id, diffFun); + }); +} +function rev(doc, deterministic_revs) { + if (!deterministic_revs) { + return v4_default().replace(/-/g, "").toLowerCase(); + } + var mutateableDoc = assign$2({}, doc); + delete mutateableDoc._rev_tree; + return stringMd5(JSON.stringify(mutateableDoc)); +} +var uuid = v4_default; + +// node_modules/pouchdb-merge/lib/index.es.js +function winningRev(metadata) { + var winningId; + var winningPos; + var winningDeleted; + var toVisit = metadata.rev_tree.slice(); + var node; + while (node = toVisit.pop()) { + var tree = node.ids; + var branches = tree[2]; + var pos = node.pos; + if (branches.length) { + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: pos + 1, ids: branches[i] }); + } + continue; + } + var deleted = !!tree[1].deleted; + var id = tree[0]; + if (!winningId || (winningDeleted !== deleted ? winningDeleted : winningPos !== pos ? winningPos < pos : winningId < id)) { + winningId = id; + winningPos = pos; + winningDeleted = deleted; + } + } + return winningPos + "-" + winningId; +} +function traverseRevTree(revs, callback) { + var toVisit = revs.slice(); + var node; + while (node = toVisit.pop()) { + var pos = node.pos; + var tree = node.ids; + var branches = tree[2]; + var newCtx = callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: pos + 1, ids: branches[i], ctx: newCtx }); + } + } +} +function sortByPos(a2, b) { + return a2.pos - b.pos; +} +function collectLeaves(revs) { + var leaves = []; + traverseRevTree(revs, function(isLeaf, pos, id, acc, opts) { + if (isLeaf) { + leaves.push({ rev: pos + "-" + id, pos, opts }); + } + }); + leaves.sort(sortByPos).reverse(); + for (var i = 0, len = leaves.length; i < len; i++) { + delete leaves[i].pos; + } + return leaves; +} +function collectConflicts(metadata) { + var win = winningRev(metadata); + var leaves = collectLeaves(metadata.rev_tree); + var conflicts = []; + for (var i = 0, len = leaves.length; i < len; i++) { + var leaf = leaves[i]; + if (leaf.rev !== win && !leaf.opts.deleted) { + conflicts.push(leaf.rev); + } + } + return conflicts; +} +function compactTree(metadata) { + var revs = []; + traverseRevTree(metadata.rev_tree, function(isLeaf, pos, revHash, ctx, opts) { + if (opts.status === "available" && !isLeaf) { + revs.push(pos + "-" + revHash); + opts.status = "missing"; + } + }); + return revs; +} +function findPathToLeaf(revs, targetRev) { + let path = []; + const toVisit = revs.slice(); + let node; + while (node = toVisit.pop()) { + const { pos, ids: tree } = node; + const rev2 = `${pos}-${tree[0]}`; + const branches = tree[2]; + path.push(rev2); + if (rev2 === targetRev) { + if (branches.length !== 0) { + throw new Error("The requested revision is not a leaf"); + } + return path.reverse(); + } + if (branches.length === 0 || branches.length > 1) { + path = []; + } + for (let i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: pos + 1, ids: branches[i] }); + } + } + if (path.length === 0) { + throw new Error("The requested revision does not exist"); + } + return path.reverse(); +} +function rootToLeaf(revs) { + var paths = []; + var toVisit = revs.slice(); + var node; + while (node = toVisit.pop()) { + var pos = node.pos; + var tree = node.ids; + var id = tree[0]; + var opts = tree[1]; + var branches = tree[2]; + var isLeaf = branches.length === 0; + var history = node.history ? node.history.slice() : []; + history.push({ id, opts }); + if (isLeaf) { + paths.push({ pos: pos + 1 - history.length, ids: history }); + } + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: pos + 1, ids: branches[i], history }); + } + } + return paths.reverse(); +} +function sortByPos$1(a2, b) { + return a2.pos - b.pos; +} +function binarySearch(arr, item, comparator) { + var low = 0; + var high = arr.length; + var mid; + while (low < high) { + mid = low + high >>> 1; + if (comparator(arr[mid], item) < 0) { + low = mid + 1; + } else { + high = mid; + } + } + return low; +} +function insertSorted(arr, item, comparator) { + var idx = binarySearch(arr, item, comparator); + arr.splice(idx, 0, item); +} +function pathToTree(path, numStemmed) { + var root; + var leaf; + for (var i = numStemmed, len = path.length; i < len; i++) { + var node = path[i]; + var currentLeaf = [node.id, node.opts, []]; + if (leaf) { + leaf[2].push(currentLeaf); + leaf = currentLeaf; + } else { + root = leaf = currentLeaf; + } + } + return root; +} +function compareTree(a2, b) { + return a2[0] < b[0] ? -1 : 1; +} +function mergeTree(in_tree1, in_tree2) { + var queue2 = [{ tree1: in_tree1, tree2: in_tree2 }]; + var conflicts = false; + while (queue2.length > 0) { + var item = queue2.pop(); + var tree1 = item.tree1; + var tree2 = item.tree2; + if (tree1[1].status || tree2[1].status) { + tree1[1].status = tree1[1].status === "available" || tree2[1].status === "available" ? "available" : "missing"; + } + for (var i = 0; i < tree2[2].length; i++) { + if (!tree1[2][0]) { + conflicts = "new_leaf"; + tree1[2][0] = tree2[2][i]; + continue; + } + var merged = false; + for (var j = 0; j < tree1[2].length; j++) { + if (tree1[2][j][0] === tree2[2][i][0]) { + queue2.push({ tree1: tree1[2][j], tree2: tree2[2][i] }); + merged = true; + } + } + if (!merged) { + conflicts = "new_branch"; + insertSorted(tree1[2], tree2[2][i], compareTree); + } + } + } + return { conflicts, tree: in_tree1 }; +} +function doMerge(tree, path, dontExpand) { + var restree = []; + var conflicts = false; + var merged = false; + var res2; + if (!tree.length) { + return { tree: [path], conflicts: "new_leaf" }; + } + for (var i = 0, len = tree.length; i < len; i++) { + var branch = tree[i]; + if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { + res2 = mergeTree(branch.ids, path.ids); + restree.push({ pos: branch.pos, ids: res2.tree }); + conflicts = conflicts || res2.conflicts; + merged = true; + } else if (dontExpand !== true) { + var t1 = branch.pos < path.pos ? branch : path; + var t2 = branch.pos < path.pos ? path : branch; + var diff = t2.pos - t1.pos; + var candidateParents = []; + var trees = []; + trees.push({ ids: t1.ids, diff, parent: null, parentIdx: null }); + while (trees.length > 0) { + var item = trees.pop(); + if (item.diff === 0) { + if (item.ids[0] === t2.ids[0]) { + candidateParents.push(item); + } + continue; + } + var elements = item.ids[2]; + for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { + trees.push({ + ids: elements[j], + diff: item.diff - 1, + parent: item.ids, + parentIdx: j + }); + } + } + var el = candidateParents[0]; + if (!el) { + restree.push(branch); + } else { + res2 = mergeTree(el.ids, t2.ids); + el.parent[2][el.parentIdx] = res2.tree; + restree.push({ pos: t1.pos, ids: t1.ids }); + conflicts = conflicts || res2.conflicts; + merged = true; + } + } else { + restree.push(branch); + } + } + if (!merged) { + restree.push(path); + } + restree.sort(sortByPos$1); + return { + tree: restree, + conflicts: conflicts || "internal_node" + }; +} +function stem(tree, depth) { + var paths = rootToLeaf(tree); + var stemmedRevs; + var result; + for (var i = 0, len = paths.length; i < len; i++) { + var path = paths[i]; + var stemmed = path.ids; + var node; + if (stemmed.length > depth) { + if (!stemmedRevs) { + stemmedRevs = {}; + } + var numStemmed = stemmed.length - depth; + node = { + pos: path.pos + numStemmed, + ids: pathToTree(stemmed, numStemmed) + }; + for (var s = 0; s < numStemmed; s++) { + var rev2 = path.pos + s + "-" + stemmed[s].id; + stemmedRevs[rev2] = true; + } + } else { + node = { + pos: path.pos, + ids: pathToTree(stemmed, 0) + }; + } + if (result) { + result = doMerge(result, node, true).tree; + } else { + result = [node]; + } + } + if (stemmedRevs) { + traverseRevTree(result, function(isLeaf, pos, revHash) { + delete stemmedRevs[pos + "-" + revHash]; + }); + } + return { + tree: result, + revs: stemmedRevs ? Object.keys(stemmedRevs) : [] + }; +} +function merge(tree, path, depth) { + var newTree = doMerge(tree, path); + var stemmed = stem(newTree.tree, depth); + return { + tree: stemmed.tree, + stemmedRevs: stemmed.revs, + conflicts: newTree.conflicts + }; +} +function removeLeafFromRevTree(tree, leafRev) { + return tree.flatMap((path) => { + path = removeLeafFromPath(path, leafRev); + return path ? [path] : []; + }); +} +function removeLeafFromPath(path, leafRev) { + const tree = clone(path); + const toVisit = [tree]; + let node; + while (node = toVisit.pop()) { + const { pos, ids: [id, , branches], parent } = node; + const isLeaf = branches.length === 0; + const hash = `${pos}-${id}`; + if (isLeaf && hash === leafRev) { + if (!parent) { + return null; + } + parent.ids[2] = parent.ids[2].filter(function(branchNode) { + return branchNode[0] !== id; + }); + return tree; + } + for (let i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: pos + 1, ids: branches[i], parent: node }); + } + } + return tree; +} +function revExists(revs, rev2) { + var toVisit = revs.slice(); + var splitRev = rev2.split("-"); + var targetPos = parseInt(splitRev[0], 10); + var targetId = splitRev[1]; + var node; + while (node = toVisit.pop()) { + if (node.pos === targetPos && node.ids[0] === targetId) { + return true; + } + var branches = node.ids[2]; + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({ pos: node.pos + 1, ids: branches[i] }); + } + } + return false; +} +function getTrees(node) { + return node.ids; +} +function isDeleted(metadata, rev2) { + if (!rev2) { + rev2 = winningRev(metadata); + } + var id = rev2.substring(rev2.indexOf("-") + 1); + var toVisit = metadata.rev_tree.map(getTrees); + var tree; + while (tree = toVisit.pop()) { + if (tree[0] === id) { + return !!tree[1].deleted; + } + toVisit = toVisit.concat(tree[2]); + } +} +function isLocalId(id) { + return /^_local/.test(id); +} +function latest(rev2, metadata) { + var toVisit = metadata.rev_tree.slice(); + var node; + while (node = toVisit.pop()) { + var pos = node.pos; + var tree = node.ids; + var id = tree[0]; + var opts = tree[1]; + var branches = tree[2]; + var isLeaf = branches.length === 0; + var history = node.history ? node.history.slice() : []; + history.push({ id, pos, opts }); + if (isLeaf) { + for (var i = 0, len = history.length; i < len; i++) { + var historyNode = history[i]; + var historyRev = historyNode.pos + "-" + historyNode.id; + if (historyRev === rev2) { + return pos + "-" + id; + } + } + } + for (var j = 0, l = branches.length; j < l; j++) { + toVisit.push({ pos: pos + 1, ids: branches[j], history }); + } + } + throw new Error("Unable to resolve latest revision for id " + metadata.id + ", rev " + rev2); +} + +// node_modules/pouchdb-core/lib/index.es.js +var import_events2 = __toESM(require_events()); + +// node_modules/pouchdb-fetch/lib/index-browser.es.js +var a = typeof AbortController !== "undefined" ? AbortController : function() { + return { abort: function() { + } }; +}; +var f2 = fetch; +var h = Headers; + +// node_modules/pouchdb-collate/lib/index.es.js +function pad(str, padWith, upToLength) { + var padding = ""; + var targetLength = upToLength - str.length; + while (padding.length < targetLength) { + padding += padWith; + } + return padding; +} +function padLeft(str, padWith, upToLength) { + var padding = pad(str, padWith, upToLength); + return padding + str; +} +var MIN_MAGNITUDE = -324; +var MAGNITUDE_DIGITS = 3; +var SEP = ""; +function collate(a2, b) { + if (a2 === b) { + return 0; + } + a2 = normalizeKey(a2); + b = normalizeKey(b); + var ai = collationIndex(a2); + var bi = collationIndex(b); + if (ai - bi !== 0) { + return ai - bi; + } + switch (typeof a2) { + case "number": + return a2 - b; + case "boolean": + return a2 < b ? -1 : 1; + case "string": + return stringCollate(a2, b); + } + return Array.isArray(a2) ? arrayCollate(a2, b) : objectCollate(a2, b); +} +function normalizeKey(key) { + switch (typeof key) { + case "undefined": + return null; + case "number": + if (key === Infinity || key === -Infinity || isNaN(key)) { + return null; + } + return key; + case "object": + var origKey = key; + if (Array.isArray(key)) { + var len = key.length; + key = new Array(len); + for (var i = 0; i < len; i++) { + key[i] = normalizeKey(origKey[i]); + } + } else if (key instanceof Date) { + return key.toJSON(); + } else if (key !== null) { + key = {}; + for (var k in origKey) { + if (Object.prototype.hasOwnProperty.call(origKey, k)) { + var val = origKey[k]; + if (typeof val !== "undefined") { + key[k] = normalizeKey(val); + } + } + } + } + } + return key; +} +function indexify(key) { + if (key !== null) { + switch (typeof key) { + case "boolean": + return key ? 1 : 0; + case "number": + return numToIndexableString(key); + case "string": + return key.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, ""); + case "object": + var isArray2 = Array.isArray(key); + var arr = isArray2 ? key : Object.keys(key); + var i = -1; + var len = arr.length; + var result = ""; + if (isArray2) { + while (++i < len) { + result += toIndexableString(arr[i]); + } + } else { + while (++i < len) { + var objKey = arr[i]; + result += toIndexableString(objKey) + toIndexableString(key[objKey]); + } + } + return result; + } + } + return ""; +} +function toIndexableString(key) { + var zero = "\0"; + key = normalizeKey(key); + return collationIndex(key) + SEP + indexify(key) + zero; +} +function parseNumber(str, i) { + var originalIdx = i; + var num; + var zero = str[i] === "1"; + if (zero) { + num = 0; + i++; + } else { + var neg = str[i] === "0"; + i++; + var numAsString = ""; + var magAsString = str.substring(i, i + MAGNITUDE_DIGITS); + var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE; + if (neg) { + magnitude = -magnitude; + } + i += MAGNITUDE_DIGITS; + while (true) { + var ch = str[i]; + if (ch === "\0") { + break; + } else { + numAsString += ch; + } + i++; + } + numAsString = numAsString.split("."); + if (numAsString.length === 1) { + num = parseInt(numAsString, 10); + } else { + num = parseFloat(numAsString[0] + "." + numAsString[1]); + } + if (neg) { + num = num - 10; + } + if (magnitude !== 0) { + num = parseFloat(num + "e" + magnitude); + } + } + return { num, length: i - originalIdx }; +} +function pop(stack, metaStack) { + var obj = stack.pop(); + if (metaStack.length) { + var lastMetaElement = metaStack[metaStack.length - 1]; + if (obj === lastMetaElement.element) { + metaStack.pop(); + lastMetaElement = metaStack[metaStack.length - 1]; + } + var element2 = lastMetaElement.element; + var lastElementIndex = lastMetaElement.index; + if (Array.isArray(element2)) { + element2.push(obj); + } else if (lastElementIndex === stack.length - 2) { + var key = stack.pop(); + element2[key] = obj; + } else { + stack.push(obj); + } + } +} +function parseIndexableString(str) { + var stack = []; + var metaStack = []; + var i = 0; + while (true) { + var collationIndex2 = str[i++]; + if (collationIndex2 === "\0") { + if (stack.length === 1) { + return stack.pop(); + } else { + pop(stack, metaStack); + continue; + } + } + switch (collationIndex2) { + case "1": + stack.push(null); + break; + case "2": + stack.push(str[i] === "1"); + i++; + break; + case "3": + var parsedNum = parseNumber(str, i); + stack.push(parsedNum.num); + i += parsedNum.length; + break; + case "4": + var parsedStr = ""; + while (true) { + var ch = str[i]; + if (ch === "\0") { + break; + } + parsedStr += ch; + i++; + } + parsedStr = parsedStr.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, ""); + stack.push(parsedStr); + break; + case "5": + var arrayElement = { element: [], index: stack.length }; + stack.push(arrayElement.element); + metaStack.push(arrayElement); + break; + case "6": + var objElement = { element: {}, index: stack.length }; + stack.push(objElement.element); + metaStack.push(objElement); + break; + default: + throw new Error( + "bad collationIndex or unexpectedly reached end of input: " + collationIndex2 + ); + } + } +} +function arrayCollate(a2, b) { + var len = Math.min(a2.length, b.length); + for (var i = 0; i < len; i++) { + var sort = collate(a2[i], b[i]); + if (sort !== 0) { + return sort; + } + } + return a2.length === b.length ? 0 : a2.length > b.length ? 1 : -1; +} +function stringCollate(a2, b) { + return a2 === b ? 0 : a2 > b ? 1 : -1; +} +function objectCollate(a2, b) { + var ak = Object.keys(a2), bk = Object.keys(b); + var len = Math.min(ak.length, bk.length); + for (var i = 0; i < len; i++) { + var sort = collate(ak[i], bk[i]); + if (sort !== 0) { + return sort; + } + sort = collate(a2[ak[i]], b[bk[i]]); + if (sort !== 0) { + return sort; + } + } + return ak.length === bk.length ? 0 : ak.length > bk.length ? 1 : -1; +} +function collationIndex(x) { + var id = ["boolean", "number", "string", "object"]; + var idx = id.indexOf(typeof x); + if (~idx) { + if (x === null) { + return 1; + } + if (Array.isArray(x)) { + return 5; + } + return idx < 3 ? idx + 2 : idx + 3; + } + if (Array.isArray(x)) { + return 5; + } +} +function numToIndexableString(num) { + if (num === 0) { + return "1"; + } + var expFormat = num.toExponential().split(/e\+?/); + var magnitude = parseInt(expFormat[1], 10); + var neg = num < 0; + var result = neg ? "0" : "2"; + var magForComparison = (neg ? -magnitude : magnitude) - MIN_MAGNITUDE; + var magString = padLeft(magForComparison.toString(), "0", MAGNITUDE_DIGITS); + result += SEP + magString; + var factor = Math.abs(parseFloat(expFormat[0])); + if (neg) { + factor = 10 - factor; + } + var factorStr = factor.toFixed(20); + factorStr = factorStr.replace(/\.?0+$/, ""); + result += SEP + factorStr; + return result; +} + +// node_modules/pouchdb-selector-core/lib/index.es.js +function getFieldFromDoc(doc, parsedField) { + var value = doc; + for (var i = 0, len = parsedField.length; i < len; i++) { + var key = parsedField[i]; + value = value[key]; + if (!value) { + break; + } + } + return value; +} +function setFieldInDoc(doc, parsedField, value) { + for (var i = 0, len = parsedField.length; i < len - 1; i++) { + var elem = parsedField[i]; + doc = doc[elem] = doc[elem] || {}; + } + doc[parsedField[len - 1]] = value; +} +function compare(left, right) { + return left < right ? -1 : left > right ? 1 : 0; +} +function parseField(fieldName) { + var fields = []; + var current = ""; + for (var i = 0, len = fieldName.length; i < len; i++) { + var ch = fieldName[i]; + if (i > 0 && fieldName[i - 1] === "\\" && (ch === "$" || ch === ".")) { + current = current.substring(0, current.length - 1) + ch; + } else if (ch === ".") { + fields.push(current); + current = ""; + } else { + current += ch; + } + } + fields.push(current); + return fields; +} +var combinationFields = ["$or", "$nor", "$not"]; +function isCombinationalField(field) { + return combinationFields.indexOf(field) > -1; +} +function getKey(obj) { + return Object.keys(obj)[0]; +} +function getValue(obj) { + return obj[getKey(obj)]; +} +function mergeAndedSelectors(selectors) { + var res2 = {}; + var first = { $or: true, $nor: true }; + selectors.forEach(function(selector) { + Object.keys(selector).forEach(function(field) { + var matcher = selector[field]; + if (typeof matcher !== "object") { + matcher = { $eq: matcher }; + } + if (isCombinationalField(field)) { + if (matcher instanceof Array) { + if (first[field]) { + first[field] = false; + res2[field] = matcher; + return; + } + var entries = []; + res2[field].forEach(function(existing) { + Object.keys(matcher).forEach(function(key) { + var m = matcher[key]; + var longest = Math.max(Object.keys(existing).length, Object.keys(m).length); + var merged = mergeAndedSelectors([existing, m]); + if (Object.keys(merged).length <= longest) { + return; + } + entries.push(merged); + }); + }); + res2[field] = entries; + } else { + res2[field] = mergeAndedSelectors([matcher]); + } + } else { + var fieldMatchers = res2[field] = res2[field] || {}; + Object.keys(matcher).forEach(function(operator) { + var value = matcher[operator]; + if (operator === "$gt" || operator === "$gte") { + return mergeGtGte(operator, value, fieldMatchers); + } else if (operator === "$lt" || operator === "$lte") { + return mergeLtLte(operator, value, fieldMatchers); + } else if (operator === "$ne") { + return mergeNe(value, fieldMatchers); + } else if (operator === "$eq") { + return mergeEq(value, fieldMatchers); + } else if (operator === "$regex") { + return mergeRegex(value, fieldMatchers); + } + fieldMatchers[operator] = value; + }); + } + }); + }); + return res2; +} +function mergeGtGte(operator, value, fieldMatchers) { + if (typeof fieldMatchers.$eq !== "undefined") { + return; + } + if (typeof fieldMatchers.$gte !== "undefined") { + if (operator === "$gte") { + if (value > fieldMatchers.$gte) { + fieldMatchers.$gte = value; + } + } else { + if (value >= fieldMatchers.$gte) { + delete fieldMatchers.$gte; + fieldMatchers.$gt = value; + } + } + } else if (typeof fieldMatchers.$gt !== "undefined") { + if (operator === "$gte") { + if (value > fieldMatchers.$gt) { + delete fieldMatchers.$gt; + fieldMatchers.$gte = value; + } + } else { + if (value > fieldMatchers.$gt) { + fieldMatchers.$gt = value; + } + } + } else { + fieldMatchers[operator] = value; + } +} +function mergeLtLte(operator, value, fieldMatchers) { + if (typeof fieldMatchers.$eq !== "undefined") { + return; + } + if (typeof fieldMatchers.$lte !== "undefined") { + if (operator === "$lte") { + if (value < fieldMatchers.$lte) { + fieldMatchers.$lte = value; + } + } else { + if (value <= fieldMatchers.$lte) { + delete fieldMatchers.$lte; + fieldMatchers.$lt = value; + } + } + } else if (typeof fieldMatchers.$lt !== "undefined") { + if (operator === "$lte") { + if (value < fieldMatchers.$lt) { + delete fieldMatchers.$lt; + fieldMatchers.$lte = value; + } + } else { + if (value < fieldMatchers.$lt) { + fieldMatchers.$lt = value; + } + } + } else { + fieldMatchers[operator] = value; + } +} +function mergeNe(value, fieldMatchers) { + if ("$ne" in fieldMatchers) { + fieldMatchers.$ne.push(value); + } else { + fieldMatchers.$ne = [value]; + } +} +function mergeEq(value, fieldMatchers) { + delete fieldMatchers.$gt; + delete fieldMatchers.$gte; + delete fieldMatchers.$lt; + delete fieldMatchers.$lte; + delete fieldMatchers.$ne; + fieldMatchers.$eq = value; +} +function mergeRegex(value, fieldMatchers) { + if ("$regex" in fieldMatchers) { + fieldMatchers.$regex.push(value); + } else { + fieldMatchers.$regex = [value]; + } +} +function mergeAndedSelectorsNested(obj) { + for (var prop in obj) { + if (Array.isArray(obj)) { + for (var i in obj) { + if (obj[i]["$and"]) { + obj[i] = mergeAndedSelectors(obj[i]["$and"]); + } + } + } + var value = obj[prop]; + if (typeof value === "object") { + mergeAndedSelectorsNested(value); + } + } + return obj; +} +function isAndInSelector(obj, isAnd) { + for (var prop in obj) { + if (prop === "$and") { + isAnd = true; + } + var value = obj[prop]; + if (typeof value === "object") { + isAnd = isAndInSelector(value, isAnd); + } + } + return isAnd; +} +function massageSelector(input) { + var result = clone(input); + if (isAndInSelector(result, false)) { + result = mergeAndedSelectorsNested(result); + if ("$and" in result) { + result = mergeAndedSelectors(result["$and"]); + } + } + ["$or", "$nor"].forEach(function(orOrNor) { + if (orOrNor in result) { + result[orOrNor].forEach(function(subSelector) { + var fields2 = Object.keys(subSelector); + for (var i2 = 0; i2 < fields2.length; i2++) { + var field2 = fields2[i2]; + var matcher2 = subSelector[field2]; + if (typeof matcher2 !== "object" || matcher2 === null) { + subSelector[field2] = { $eq: matcher2 }; + } + } + }); + } + }); + if ("$not" in result) { + result["$not"] = mergeAndedSelectors([result["$not"]]); + } + var fields = Object.keys(result); + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + var matcher = result[field]; + if (typeof matcher !== "object" || matcher === null) { + matcher = { $eq: matcher }; + } + result[field] = matcher; + } + normalizeArrayOperators(result); + return result; +} +function normalizeArrayOperators(selector) { + Object.keys(selector).forEach(function(field) { + var matcher = selector[field]; + if (Array.isArray(matcher)) { + matcher.forEach(function(matcherItem) { + if (matcherItem && typeof matcherItem === "object") { + normalizeArrayOperators(matcherItem); + } + }); + } else if (field === "$ne") { + selector.$ne = [matcher]; + } else if (field === "$regex") { + selector.$regex = [matcher]; + } else if (matcher && typeof matcher === "object") { + normalizeArrayOperators(matcher); + } + }); +} +function createFieldSorter(sort) { + function getFieldValuesAsArray(doc) { + return sort.map(function(sorting) { + var fieldName = getKey(sorting); + var parsedField = parseField(fieldName); + var docFieldValue = getFieldFromDoc(doc, parsedField); + return docFieldValue; + }); + } + return function(aRow, bRow) { + var aFieldValues = getFieldValuesAsArray(aRow.doc); + var bFieldValues = getFieldValuesAsArray(bRow.doc); + var collation = collate(aFieldValues, bFieldValues); + if (collation !== 0) { + return collation; + } + return compare(aRow.doc._id, bRow.doc._id); + }; +} +function filterInMemoryFields(rows, requestDef, inMemoryFields) { + rows = rows.filter(function(row) { + return rowFilter(row.doc, requestDef.selector, inMemoryFields); + }); + if (requestDef.sort) { + var fieldSorter = createFieldSorter(requestDef.sort); + rows = rows.sort(fieldSorter); + if (typeof requestDef.sort[0] !== "string" && getValue(requestDef.sort[0]) === "desc") { + rows = rows.reverse(); + } + } + if ("limit" in requestDef || "skip" in requestDef) { + var skip = requestDef.skip || 0; + var limit = ("limit" in requestDef ? requestDef.limit : rows.length) + skip; + rows = rows.slice(skip, limit); + } + return rows; +} +function rowFilter(doc, selector, inMemoryFields) { + return inMemoryFields.every(function(field) { + var matcher = selector[field]; + var parsedField = parseField(field); + var docFieldValue = getFieldFromDoc(doc, parsedField); + if (isCombinationalField(field)) { + return matchCominationalSelector(field, matcher, doc); + } + return matchSelector(matcher, doc, parsedField, docFieldValue); + }); +} +function matchSelector(matcher, doc, parsedField, docFieldValue) { + if (!matcher) { + return true; + } + if (typeof matcher === "object") { + return Object.keys(matcher).every(function(maybeUserOperator) { + var userValue = matcher[maybeUserOperator]; + if (maybeUserOperator.indexOf("$") === 0) { + return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue); + } else { + var subParsedField = parseField(maybeUserOperator); + if (docFieldValue === void 0 && typeof userValue !== "object" && subParsedField.length > 0) { + return false; + } + var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField); + if (typeof userValue === "object") { + return matchSelector(userValue, doc, parsedField, subDocFieldValue); + } + return match("$eq", doc, userValue, subParsedField, subDocFieldValue); + } + }); + } + return matcher === docFieldValue; +} +function matchCominationalSelector(field, matcher, doc) { + if (field === "$or") { + return matcher.some(function(orMatchers) { + return rowFilter(doc, orMatchers, Object.keys(orMatchers)); + }); + } + if (field === "$not") { + return !rowFilter(doc, matcher, Object.keys(matcher)); + } + return !matcher.find(function(orMatchers) { + return rowFilter(doc, orMatchers, Object.keys(orMatchers)); + }); +} +function match(userOperator, doc, userValue, parsedField, docFieldValue) { + if (!matchers[userOperator]) { + throw new Error('unknown operator "' + userOperator + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all'); + } + return matchers[userOperator](doc, userValue, parsedField, docFieldValue); +} +function fieldExists(docFieldValue) { + return typeof docFieldValue !== "undefined" && docFieldValue !== null; +} +function fieldIsNotUndefined(docFieldValue) { + return typeof docFieldValue !== "undefined"; +} +function modField(docFieldValue, userValue) { + if (typeof docFieldValue !== "number" || parseInt(docFieldValue, 10) !== docFieldValue) { + return false; + } + var divisor = userValue[0]; + var mod = userValue[1]; + return docFieldValue % divisor === mod; +} +function arrayContainsValue(docFieldValue, userValue) { + return userValue.some(function(val) { + if (docFieldValue instanceof Array) { + return docFieldValue.some(function(docFieldValueItem) { + return collate(val, docFieldValueItem) === 0; + }); + } + return collate(val, docFieldValue) === 0; + }); +} +function arrayContainsAllValues(docFieldValue, userValue) { + return userValue.every(function(val) { + return docFieldValue.some(function(docFieldValueItem) { + return collate(val, docFieldValueItem) === 0; + }); + }); +} +function arraySize(docFieldValue, userValue) { + return docFieldValue.length === userValue; +} +function regexMatch(docFieldValue, userValue) { + var re = new RegExp(userValue); + return re.test(docFieldValue); +} +function typeMatch(docFieldValue, userValue) { + switch (userValue) { + case "null": + return docFieldValue === null; + case "boolean": + return typeof docFieldValue === "boolean"; + case "number": + return typeof docFieldValue === "number"; + case "string": + return typeof docFieldValue === "string"; + case "array": + return docFieldValue instanceof Array; + case "object": + return {}.toString.call(docFieldValue) === "[object Object]"; + } +} +var matchers = { + "$elemMatch": function(doc, userValue, parsedField, docFieldValue) { + if (!Array.isArray(docFieldValue)) { + return false; + } + if (docFieldValue.length === 0) { + return false; + } + if (typeof docFieldValue[0] === "object" && docFieldValue[0] !== null) { + return docFieldValue.some(function(val) { + return rowFilter(val, userValue, Object.keys(userValue)); + }); + } + return docFieldValue.some(function(val) { + return matchSelector(userValue, doc, parsedField, val); + }); + }, + "$allMatch": function(doc, userValue, parsedField, docFieldValue) { + if (!Array.isArray(docFieldValue)) { + return false; + } + if (docFieldValue.length === 0) { + return false; + } + if (typeof docFieldValue[0] === "object" && docFieldValue[0] !== null) { + return docFieldValue.every(function(val) { + return rowFilter(val, userValue, Object.keys(userValue)); + }); + } + return docFieldValue.every(function(val) { + return matchSelector(userValue, doc, parsedField, val); + }); + }, + "$eq": function(doc, userValue, parsedField, docFieldValue) { + return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0; + }, + "$gte": function(doc, userValue, parsedField, docFieldValue) { + return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0; + }, + "$gt": function(doc, userValue, parsedField, docFieldValue) { + return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0; + }, + "$lte": function(doc, userValue, parsedField, docFieldValue) { + return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0; + }, + "$lt": function(doc, userValue, parsedField, docFieldValue) { + return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0; + }, + "$exists": function(doc, userValue, parsedField, docFieldValue) { + if (userValue) { + return fieldIsNotUndefined(docFieldValue); + } + return !fieldIsNotUndefined(docFieldValue); + }, + "$mod": function(doc, userValue, parsedField, docFieldValue) { + return fieldExists(docFieldValue) && modField(docFieldValue, userValue); + }, + "$ne": function(doc, userValue, parsedField, docFieldValue) { + return userValue.every(function(neValue) { + return collate(docFieldValue, neValue) !== 0; + }); + }, + "$in": function(doc, userValue, parsedField, docFieldValue) { + return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue); + }, + "$nin": function(doc, userValue, parsedField, docFieldValue) { + return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue); + }, + "$size": function(doc, userValue, parsedField, docFieldValue) { + return fieldExists(docFieldValue) && Array.isArray(docFieldValue) && arraySize(docFieldValue, userValue); + }, + "$all": function(doc, userValue, parsedField, docFieldValue) { + return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue); + }, + "$regex": function(doc, userValue, parsedField, docFieldValue) { + return fieldExists(docFieldValue) && typeof docFieldValue == "string" && userValue.every(function(regexValue) { + return regexMatch(docFieldValue, regexValue); + }); + }, + "$type": function(doc, userValue, parsedField, docFieldValue) { + return typeMatch(docFieldValue, userValue); + } +}; +function matchesSelector(doc, selector) { + if (typeof selector !== "object") { + throw new Error("Selector error: expected a JSON object"); + } + selector = massageSelector(selector); + var row = { + "doc": doc + }; + var rowsMatched = filterInMemoryFields([row], { "selector": selector }, Object.keys(selector)); + return rowsMatched && rowsMatched.length === 1; +} + +// node_modules/pouchdb-changes-filter/lib/index-browser.es.js +function evalFilter(input) { + return scopeEval('"use strict";\nreturn ' + input + ";", {}); +} +function evalView(input) { + var code = [ + "return function(doc) {", + ' "use strict";', + " var emitted = false;", + " var emit = function (a, b) {", + " emitted = true;", + " };", + " var view = " + input + ";", + " view(doc);", + " if (emitted) {", + " return true;", + " }", + "};" + ].join("\n"); + return scopeEval(code, {}); +} +function validate2(opts, callback) { + if (opts.selector) { + if (opts.filter && opts.filter !== "_selector") { + var filterName = typeof opts.filter === "string" ? opts.filter : "function"; + return callback(new Error('selector invalid for filter "' + filterName + '"')); + } + } + callback(); +} +function normalize(opts) { + if (opts.view && !opts.filter) { + opts.filter = "_view"; + } + if (opts.selector && !opts.filter) { + opts.filter = "_selector"; + } + if (opts.filter && typeof opts.filter === "string") { + if (opts.filter === "_view") { + opts.view = normalizeDesignDocFunctionName(opts.view); + } else { + opts.filter = normalizeDesignDocFunctionName(opts.filter); + } + } +} +function shouldFilter(changesHandler, opts) { + return opts.filter && typeof opts.filter === "string" && !opts.doc_ids && !isRemote(changesHandler.db); +} +function filter(changesHandler, opts) { + var callback = opts.complete; + if (opts.filter === "_view") { + if (!opts.view || typeof opts.view !== "string") { + var err = createError( + BAD_REQUEST, + "`view` filter parameter not found or invalid." + ); + return callback(err); + } + var viewName = parseDesignDocFunctionName(opts.view); + changesHandler.db.get("_design/" + viewName[0], function(err2, ddoc) { + if (changesHandler.isCancelled) { + return callback(null, { status: "cancelled" }); + } + if (err2) { + return callback(generateErrorFromResponse(err2)); + } + var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] && ddoc.views[viewName[1]].map; + if (!mapFun) { + return callback(createError( + MISSING_DOC, + ddoc.views ? "missing json key: " + viewName[1] : "missing json key: views" + )); + } + opts.filter = evalView(mapFun); + changesHandler.doChanges(opts); + }); + } else if (opts.selector) { + opts.filter = function(doc) { + return matchesSelector(doc, opts.selector); + }; + changesHandler.doChanges(opts); + } else { + var filterName = parseDesignDocFunctionName(opts.filter); + changesHandler.db.get("_design/" + filterName[0], function(err2, ddoc) { + if (changesHandler.isCancelled) { + return callback(null, { status: "cancelled" }); + } + if (err2) { + return callback(generateErrorFromResponse(err2)); + } + var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]]; + if (!filterFun) { + return callback(createError( + MISSING_DOC, + ddoc && ddoc.filters ? "missing json key: " + filterName[1] : "missing json key: filters" + )); + } + opts.filter = evalFilter(filterFun); + changesHandler.doChanges(opts); + }); + } +} +function applyChangesFilterPlugin(PouchDB2) { + PouchDB2._changesFilterPlugin = { + validate: validate2, + normalize, + shouldFilter, + filter + }; +} +var index_browser_es_default = applyChangesFilterPlugin; + +// node_modules/pouchdb-core/lib/index.es.js +function tryCatchInChangeListener(self2, change, pending, lastSeq) { + try { + self2.emit("change", change, pending, lastSeq); + } catch (e2) { + guardedConsole("error", 'Error in .on("change", function):', e2); + } +} +function processChange(doc, metadata, opts) { + var changeList = [{ rev: doc._rev }]; + if (opts.style === "all_docs") { + changeList = collectLeaves(metadata.rev_tree).map(function(x) { + return { rev: x.rev }; + }); + } + var change = { + id: metadata.id, + changes: changeList, + doc + }; + if (isDeleted(metadata, doc._rev)) { + change.deleted = true; + } + if (opts.conflicts) { + change.doc._conflicts = collectConflicts(metadata); + if (!change.doc._conflicts.length) { + delete change.doc._conflicts; + } + } + return change; +} +var Changes2 = class extends import_events2.default { + constructor(db, opts, callback) { + super(); + this.db = db; + opts = opts ? clone(opts) : {}; + var complete = opts.complete = once((err, resp) => { + if (err) { + if (listenerCount(this, "error") > 0) { + this.emit("error", err); + } + } else { + this.emit("complete", resp); + } + this.removeAllListeners(); + db.removeListener("destroyed", onDestroy2); + }); + if (callback) { + this.on("complete", function(resp) { + callback(null, resp); + }); + this.on("error", callback); + } + const onDestroy2 = () => { + this.cancel(); + }; + db.once("destroyed", onDestroy2); + opts.onChange = (change, pending, lastSeq) => { + if (this.isCancelled) { + return; + } + tryCatchInChangeListener(this, change, pending, lastSeq); + }; + var promise = new Promise(function(fulfill, reject) { + opts.complete = function(err, res2) { + if (err) { + reject(err); + } else { + fulfill(res2); + } + }; + }); + this.once("cancel", function() { + db.removeListener("destroyed", onDestroy2); + opts.complete(null, { status: "cancelled" }); + }); + this.then = promise.then.bind(promise); + this["catch"] = promise["catch"].bind(promise); + this.then(function(result) { + complete(null, result); + }, complete); + if (!db.taskqueue.isReady) { + db.taskqueue.addTask((failed) => { + if (failed) { + opts.complete(failed); + } else if (this.isCancelled) { + this.emit("cancel"); + } else { + this.validateChanges(opts); + } + }); + } else { + this.validateChanges(opts); + } + } + cancel() { + this.isCancelled = true; + if (this.db.taskqueue.isReady) { + this.emit("cancel"); + } + } + validateChanges(opts) { + var callback = opts.complete; + if (PouchDB._changesFilterPlugin) { + PouchDB._changesFilterPlugin.validate(opts, (err) => { + if (err) { + return callback(err); + } + this.doChanges(opts); + }); + } else { + this.doChanges(opts); + } + } + doChanges(opts) { + var callback = opts.complete; + opts = clone(opts); + if ("live" in opts && !("continuous" in opts)) { + opts.continuous = opts.live; + } + opts.processChange = processChange; + if (opts.since === "latest") { + opts.since = "now"; + } + if (!opts.since) { + opts.since = 0; + } + if (opts.since === "now") { + this.db.info().then((info2) => { + if (this.isCancelled) { + callback(null, { status: "cancelled" }); + return; + } + opts.since = info2.update_seq; + this.doChanges(opts); + }, callback); + return; + } + if (PouchDB._changesFilterPlugin) { + PouchDB._changesFilterPlugin.normalize(opts); + if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) { + return PouchDB._changesFilterPlugin.filter(this, opts); + } + } else { + ["doc_ids", "filter", "selector", "view"].forEach(function(key) { + if (key in opts) { + guardedConsole( + "warn", + 'The "' + key + '" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.' + ); + } + }); + } + if (!("descending" in opts)) { + opts.descending = false; + } + opts.limit = opts.limit === 0 ? 1 : opts.limit; + opts.complete = callback; + var newPromise = this.db._changes(opts); + if (newPromise && typeof newPromise.cancel === "function") { + const cancel = this.cancel; + this.cancel = (...args) => { + newPromise.cancel(); + cancel.apply(this, args); + }; + } + } +}; +function compare2(left, right) { + return left < right ? -1 : left > right ? 1 : 0; +} +function yankError(callback, docId) { + return function(err, results) { + if (err || results[0] && results[0].error) { + err = err || results[0]; + err.docId = docId; + callback(err); + } else { + callback(null, results.length ? results[0] : results); + } + }; +} +function cleanDocs(docs) { + for (var i = 0; i < docs.length; i++) { + var doc = docs[i]; + if (doc._deleted) { + delete doc._attachments; + } else if (doc._attachments) { + var atts = Object.keys(doc._attachments); + for (var j = 0; j < atts.length; j++) { + var att = atts[j]; + doc._attachments[att] = pick( + doc._attachments[att], + ["data", "digest", "content_type", "length", "revpos", "stub"] + ); + } + } + } +} +function compareByIdThenRev(a2, b) { + var idCompare = compare2(a2._id, b._id); + if (idCompare !== 0) { + return idCompare; + } + var aStart = a2._revisions ? a2._revisions.start : 0; + var bStart = b._revisions ? b._revisions.start : 0; + return compare2(aStart, bStart); +} +function computeHeight(revs) { + var height = {}; + var edges = []; + traverseRevTree(revs, function(isLeaf, pos, id, prnt) { + var rev$$1 = pos + "-" + id; + if (isLeaf) { + height[rev$$1] = 0; + } + if (prnt !== void 0) { + edges.push({ from: prnt, to: rev$$1 }); + } + return rev$$1; + }); + edges.reverse(); + edges.forEach(function(edge) { + if (height[edge.from] === void 0) { + height[edge.from] = 1 + height[edge.to]; + } else { + height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]); + } + }); + return height; +} +function allDocsKeysParse(opts) { + var keys2 = "limit" in opts ? opts.keys.slice(opts.skip, opts.limit + opts.skip) : opts.skip > 0 ? opts.keys.slice(opts.skip) : opts.keys; + opts.keys = keys2; + opts.skip = 0; + delete opts.limit; + if (opts.descending) { + keys2.reverse(); + opts.descending = false; + } +} +function doNextCompaction(self2) { + var task = self2._compactionQueue[0]; + var opts = task.opts; + var callback = task.callback; + self2.get("_local/compaction").catch(function() { + return false; + }).then(function(doc) { + if (doc && doc.last_seq) { + opts.last_seq = doc.last_seq; + } + self2._compact(opts, function(err, res2) { + if (err) { + callback(err); + } else { + callback(null, res2); + } + (0, import_immediate.default)(function() { + self2._compactionQueue.shift(); + if (self2._compactionQueue.length) { + doNextCompaction(self2); + } + }); + }); + }); +} +function appendPurgeSeq(db, docId, rev$$1) { + return db.get("_local/purges").then(function(doc) { + const purgeSeq = doc.purgeSeq + 1; + doc.purges.push({ + docId, + rev: rev$$1, + purgeSeq + }); + if (doc.purges.length > self.purged_infos_limit) { + doc.purges.splice(0, doc.purges.length - self.purged_infos_limit); + } + doc.purgeSeq = purgeSeq; + return doc; + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return { + _id: "_local/purges", + purges: [{ + docId, + rev: rev$$1, + purgeSeq: 0 + }], + purgeSeq: 0 + }; + }).then(function(doc) { + return db.put(doc); + }); +} +function attachmentNameError(name) { + if (name.charAt(0) === "_") { + return name + " is not a valid attachment name, attachment names cannot start with '_'"; + } + return false; +} +var AbstractPouchDB = class extends import_events2.default { + _setup() { + this.post = adapterFun("post", function(doc, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + if (typeof doc !== "object" || Array.isArray(doc)) { + return callback(createError(NOT_AN_OBJECT)); + } + this.bulkDocs({ docs: [doc] }, opts, yankError(callback, doc._id)); + }).bind(this); + this.put = adapterFun("put", function(doc, opts, cb) { + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + if (typeof doc !== "object" || Array.isArray(doc)) { + return cb(createError(NOT_AN_OBJECT)); + } + invalidIdError(doc._id); + if (isLocalId(doc._id) && typeof this._putLocal === "function") { + if (doc._deleted) { + return this._removeLocal(doc, cb); + } else { + return this._putLocal(doc, cb); + } + } + const putDoc = (next) => { + if (typeof this._put === "function" && opts.new_edits !== false) { + this._put(doc, opts, next); + } else { + this.bulkDocs({ docs: [doc] }, opts, yankError(next, doc._id)); + } + }; + if (opts.force && doc._rev) { + transformForceOptionToNewEditsOption(); + putDoc(function(err) { + var result = err ? null : { ok: true, id: doc._id, rev: doc._rev }; + cb(err, result); + }); + } else { + putDoc(cb); + } + function transformForceOptionToNewEditsOption() { + var parts = doc._rev.split("-"); + var oldRevId = parts[1]; + var oldRevNum = parseInt(parts[0], 10); + var newRevNum = oldRevNum + 1; + var newRevId = rev(); + doc._revisions = { + start: newRevNum, + ids: [newRevId, oldRevId] + }; + doc._rev = newRevNum + "-" + newRevId; + opts.new_edits = false; + } + }).bind(this); + this.putAttachment = adapterFun("putAttachment", function(docId, attachmentId, rev$$1, blob, type) { + var api = this; + if (typeof type === "function") { + type = blob; + blob = rev$$1; + rev$$1 = null; + } + if (typeof type === "undefined") { + type = blob; + blob = rev$$1; + rev$$1 = null; + } + if (!type) { + guardedConsole("warn", "Attachment", attachmentId, "on document", docId, "is missing content_type"); + } + function createAttachment(doc) { + var prevrevpos = "_rev" in doc ? parseInt(doc._rev, 10) : 0; + doc._attachments = doc._attachments || {}; + doc._attachments[attachmentId] = { + content_type: type, + data: blob, + revpos: ++prevrevpos + }; + return api.put(doc); + } + return api.get(docId).then(function(doc) { + if (doc._rev !== rev$$1) { + throw createError(REV_CONFLICT); + } + return createAttachment(doc); + }, function(err) { + if (err.reason === MISSING_DOC.message) { + return createAttachment({ _id: docId }); + } else { + throw err; + } + }); + }).bind(this); + this.removeAttachment = adapterFun("removeAttachment", function(docId, attachmentId, rev$$1, callback) { + this.get(docId, (err, obj) => { + if (err) { + callback(err); + return; + } + if (obj._rev !== rev$$1) { + callback(createError(REV_CONFLICT)); + return; + } + if (!obj._attachments) { + return callback(); + } + delete obj._attachments[attachmentId]; + if (Object.keys(obj._attachments).length === 0) { + delete obj._attachments; + } + this.put(obj, callback); + }); + }).bind(this); + this.remove = adapterFun("remove", function(docOrId, optsOrRev, opts, callback) { + var doc; + if (typeof optsOrRev === "string") { + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + } else { + doc = docOrId; + if (typeof optsOrRev === "function") { + callback = optsOrRev; + opts = {}; + } else { + callback = opts; + opts = optsOrRev; + } + } + opts = opts || {}; + opts.was_delete = true; + var newDoc = { _id: doc._id, _rev: doc._rev || opts.rev }; + newDoc._deleted = true; + if (isLocalId(newDoc._id) && typeof this._removeLocal === "function") { + return this._removeLocal(doc, callback); + } + this.bulkDocs({ docs: [newDoc] }, opts, yankError(callback, newDoc._id)); + }).bind(this); + this.revsDiff = adapterFun("revsDiff", function(req, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + var ids = Object.keys(req); + if (!ids.length) { + return callback(null, {}); + } + var count = 0; + var missing = new ExportedMap(); + function addToMissing(id, revId) { + if (!missing.has(id)) { + missing.set(id, { missing: [] }); + } + missing.get(id).missing.push(revId); + } + function processDoc(id, rev_tree) { + var missingForId = req[id].slice(0); + traverseRevTree(rev_tree, function(isLeaf, pos, revHash, ctx, opts2) { + var rev$$1 = pos + "-" + revHash; + var idx = missingForId.indexOf(rev$$1); + if (idx === -1) { + return; + } + missingForId.splice(idx, 1); + if (opts2.status !== "available") { + addToMissing(id, rev$$1); + } + }); + missingForId.forEach(function(rev$$1) { + addToMissing(id, rev$$1); + }); + } + ids.map(function(id) { + this._getRevisionTree(id, function(err, rev_tree) { + if (err && err.status === 404 && err.message === "missing") { + missing.set(id, { missing: req[id] }); + } else if (err) { + return callback(err); + } else { + processDoc(id, rev_tree); + } + if (++count === ids.length) { + var missingObj = {}; + missing.forEach(function(value, key) { + missingObj[key] = value; + }); + return callback(null, missingObj); + } + }); + }, this); + }).bind(this); + this.bulkGet = adapterFun("bulkGet", function(opts, callback) { + bulkGet(this, opts, callback); + }).bind(this); + this.compactDocument = adapterFun("compactDocument", function(docId, maxHeight, callback) { + this._getRevisionTree(docId, (err, revTree) => { + if (err) { + return callback(err); + } + var height = computeHeight(revTree); + var candidates = []; + var revs = []; + Object.keys(height).forEach(function(rev$$1) { + if (height[rev$$1] > maxHeight) { + candidates.push(rev$$1); + } + }); + traverseRevTree(revTree, function(isLeaf, pos, revHash, ctx, opts) { + var rev$$1 = pos + "-" + revHash; + if (opts.status === "available" && candidates.indexOf(rev$$1) !== -1) { + revs.push(rev$$1); + } + }); + this._doCompaction(docId, revs, callback); + }); + }).bind(this); + this.compact = adapterFun("compact", function(opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts = opts || {}; + this._compactionQueue = this._compactionQueue || []; + this._compactionQueue.push({ opts, callback }); + if (this._compactionQueue.length === 1) { + doNextCompaction(this); + } + }).bind(this); + this.get = adapterFun("get", function(id, opts, cb) { + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + if (typeof id !== "string") { + return cb(createError(INVALID_ID)); + } + if (isLocalId(id) && typeof this._getLocal === "function") { + return this._getLocal(id, cb); + } + var leaves = []; + const finishOpenRevs = () => { + var result = []; + var count = leaves.length; + if (!count) { + return cb(null, result); + } + leaves.forEach((leaf) => { + this.get(id, { + rev: leaf, + revs: opts.revs, + latest: opts.latest, + attachments: opts.attachments, + binary: opts.binary + }, function(err, doc) { + if (!err) { + var existing; + for (var i2 = 0, l2 = result.length; i2 < l2; i2++) { + if (result[i2].ok && result[i2].ok._rev === doc._rev) { + existing = true; + break; + } + } + if (!existing) { + result.push({ ok: doc }); + } + } else { + result.push({ missing: leaf }); + } + count--; + if (!count) { + cb(null, result); + } + }); + }); + }; + if (opts.open_revs) { + if (opts.open_revs === "all") { + this._getRevisionTree(id, function(err, rev_tree) { + if (err) { + return cb(err); + } + leaves = collectLeaves(rev_tree).map(function(leaf) { + return leaf.rev; + }); + finishOpenRevs(); + }); + } else { + if (Array.isArray(opts.open_revs)) { + leaves = opts.open_revs; + for (var i = 0; i < leaves.length; i++) { + var l = leaves[i]; + if (!(typeof l === "string" && /^\d+-/.test(l))) { + return cb(createError(INVALID_REV)); + } + } + finishOpenRevs(); + } else { + return cb(createError(UNKNOWN_ERROR, "function_clause")); + } + } + return; + } + return this._get(id, opts, (err, result) => { + if (err) { + err.docId = id; + return cb(err); + } + var doc = result.doc; + var metadata = result.metadata; + var ctx = result.ctx; + if (opts.conflicts) { + var conflicts = collectConflicts(metadata); + if (conflicts.length) { + doc._conflicts = conflicts; + } + } + if (isDeleted(metadata, doc._rev)) { + doc._deleted = true; + } + if (opts.revs || opts.revs_info) { + var splittedRev = doc._rev.split("-"); + var revNo = parseInt(splittedRev[0], 10); + var revHash = splittedRev[1]; + var paths = rootToLeaf(metadata.rev_tree); + var path = null; + for (var i2 = 0; i2 < paths.length; i2++) { + var currentPath = paths[i2]; + var hashIndex = currentPath.ids.map(function(x) { + return x.id; + }).indexOf(revHash); + var hashFoundAtRevPos = hashIndex === revNo - 1; + if (hashFoundAtRevPos || !path && hashIndex !== -1) { + path = currentPath; + } + } + if (!path) { + err = new Error("invalid rev tree"); + err.docId = id; + return cb(err); + } + var indexOfRev = path.ids.map(function(x) { + return x.id; + }).indexOf(doc._rev.split("-")[1]) + 1; + var howMany = path.ids.length - indexOfRev; + path.ids.splice(indexOfRev, howMany); + path.ids.reverse(); + if (opts.revs) { + doc._revisions = { + start: path.pos + path.ids.length - 1, + ids: path.ids.map(function(rev$$1) { + return rev$$1.id; + }) + }; + } + if (opts.revs_info) { + var pos = path.pos + path.ids.length; + doc._revs_info = path.ids.map(function(rev$$1) { + pos--; + return { + rev: pos + "-" + rev$$1.id, + status: rev$$1.opts.status + }; + }); + } + } + if (opts.attachments && doc._attachments) { + var attachments = doc._attachments; + var count = Object.keys(attachments).length; + if (count === 0) { + return cb(null, doc); + } + Object.keys(attachments).forEach((key2) => { + this._getAttachment(doc._id, key2, attachments[key2], { + rev: doc._rev, + binary: opts.binary, + ctx + }, function(err2, data) { + var att = doc._attachments[key2]; + att.data = data; + delete att.stub; + delete att.length; + if (!--count) { + cb(null, doc); + } + }); + }); + } else { + if (doc._attachments) { + for (var key in doc._attachments) { + if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) { + doc._attachments[key].stub = true; + } + } + } + cb(null, doc); + } + }); + }).bind(this); + this.getAttachment = adapterFun("getAttachment", function(docId, attachmentId, opts, callback) { + if (opts instanceof Function) { + callback = opts; + opts = {}; + } + this._get(docId, opts, (err, res2) => { + if (err) { + return callback(err); + } + if (res2.doc._attachments && res2.doc._attachments[attachmentId]) { + opts.ctx = res2.ctx; + opts.binary = true; + this._getAttachment( + docId, + attachmentId, + res2.doc._attachments[attachmentId], + opts, + callback + ); + } else { + return callback(createError(MISSING_DOC)); + } + }); + }).bind(this); + this.allDocs = adapterFun("allDocs", function(opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts.skip = typeof opts.skip !== "undefined" ? opts.skip : 0; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if ("keys" in opts) { + if (!Array.isArray(opts.keys)) { + return callback(new TypeError("options.keys must be an array")); + } + var incompatibleOpt = ["startkey", "endkey", "key"].filter(function(incompatibleOpt2) { + return incompatibleOpt2 in opts; + })[0]; + if (incompatibleOpt) { + callback(createError( + QUERY_PARSE_ERROR, + "Query parameter `" + incompatibleOpt + "` is not compatible with multi-get" + )); + return; + } + if (!isRemote(this)) { + allDocsKeysParse(opts); + if (opts.keys.length === 0) { + return this._allDocs({ limit: 0 }, callback); + } + } + } + return this._allDocs(opts, callback); + }).bind(this); + this.close = adapterFun("close", function(callback) { + this._closed = true; + this.emit("closed"); + return this._close(callback); + }).bind(this); + this.info = adapterFun("info", function(callback) { + this._info((err, info2) => { + if (err) { + return callback(err); + } + info2.db_name = info2.db_name || this.name; + info2.auto_compaction = !!(this.auto_compaction && !isRemote(this)); + info2.adapter = this.adapter; + callback(null, info2); + }); + }).bind(this); + this.id = adapterFun("id", function(callback) { + return this._id(callback); + }).bind(this); + this.bulkDocs = adapterFun("bulkDocs", function(req, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts = opts || {}; + if (Array.isArray(req)) { + req = { + docs: req + }; + } + if (!req || !req.docs || !Array.isArray(req.docs)) { + return callback(createError(MISSING_BULK_DOCS)); + } + for (var i = 0; i < req.docs.length; ++i) { + if (typeof req.docs[i] !== "object" || Array.isArray(req.docs[i])) { + return callback(createError(NOT_AN_OBJECT)); + } + } + var attachmentError; + req.docs.forEach(function(doc) { + if (doc._attachments) { + Object.keys(doc._attachments).forEach(function(name) { + attachmentError = attachmentError || attachmentNameError(name); + if (!doc._attachments[name].content_type) { + guardedConsole("warn", "Attachment", name, "on document", doc._id, "is missing content_type"); + } + }); + } + }); + if (attachmentError) { + return callback(createError(BAD_REQUEST, attachmentError)); + } + if (!("new_edits" in opts)) { + if ("new_edits" in req) { + opts.new_edits = req.new_edits; + } else { + opts.new_edits = true; + } + } + var adapter = this; + if (!opts.new_edits && !isRemote(adapter)) { + req.docs.sort(compareByIdThenRev); + } + cleanDocs(req.docs); + var ids = req.docs.map(function(doc) { + return doc._id; + }); + this._bulkDocs(req, opts, function(err, res2) { + if (err) { + return callback(err); + } + if (!opts.new_edits) { + res2 = res2.filter(function(x) { + return x.error; + }); + } + if (!isRemote(adapter)) { + for (var i2 = 0, l = res2.length; i2 < l; i2++) { + res2[i2].id = res2[i2].id || ids[i2]; + } + } + callback(null, res2); + }); + }).bind(this); + this.registerDependentDatabase = adapterFun("registerDependentDatabase", function(dependentDb, callback) { + var dbOptions = clone(this.__opts); + if (this.__opts.view_adapter) { + dbOptions.adapter = this.__opts.view_adapter; + } + var depDB = new this.constructor(dependentDb, dbOptions); + function diffFun(doc) { + doc.dependentDbs = doc.dependentDbs || {}; + if (doc.dependentDbs[dependentDb]) { + return false; + } + doc.dependentDbs[dependentDb] = true; + return doc; + } + upsert(this, "_local/_pouch_dependentDbs", diffFun).then(function() { + callback(null, { db: depDB }); + }).catch(callback); + }).bind(this); + this.destroy = adapterFun("destroy", function(opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + var usePrefix = "use_prefix" in this ? this.use_prefix : true; + const destroyDb = () => { + this._destroy(opts, (err, resp) => { + if (err) { + return callback(err); + } + this._destroyed = true; + this.emit("destroyed"); + callback(null, resp || { "ok": true }); + }); + }; + if (isRemote(this)) { + return destroyDb(); + } + this.get("_local/_pouch_dependentDbs", (err, localDoc) => { + if (err) { + if (err.status !== 404) { + return callback(err); + } else { + return destroyDb(); + } + } + var dependentDbs = localDoc.dependentDbs; + var PouchDB2 = this.constructor; + var deletedMap = Object.keys(dependentDbs).map((name) => { + var trueName = usePrefix ? name.replace(new RegExp("^" + PouchDB2.prefix), "") : name; + return new PouchDB2(trueName, this.__opts).destroy(); + }); + Promise.all(deletedMap).then(destroyDb, callback); + }); + }).bind(this); + } + _compact(opts, callback) { + var changesOpts = { + return_docs: false, + last_seq: opts.last_seq || 0 + }; + var promises = []; + var taskId; + var compactedDocs = 0; + const onChange = (row) => { + this.activeTasks.update(taskId, { + completed_items: ++compactedDocs + }); + promises.push(this.compactDocument(row.id, 0)); + }; + const onError = (err) => { + this.activeTasks.remove(taskId, err); + callback(err); + }; + const onComplete = (resp) => { + var lastSeq = resp.last_seq; + Promise.all(promises).then(() => { + return upsert(this, "_local/compaction", (doc) => { + if (!doc.last_seq || doc.last_seq < lastSeq) { + doc.last_seq = lastSeq; + return doc; + } + return false; + }); + }).then(() => { + this.activeTasks.remove(taskId); + callback(null, { ok: true }); + }).catch(onError); + }; + this.info().then((info2) => { + taskId = this.activeTasks.add({ + name: "database_compaction", + total_items: info2.update_seq - changesOpts.last_seq + }); + this.changes(changesOpts).on("change", onChange).on("complete", onComplete).on("error", onError); + }); + } + changes(opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts = opts || {}; + opts.return_docs = "return_docs" in opts ? opts.return_docs : !opts.live; + return new Changes2(this, opts, callback); + } + type() { + return typeof this._type === "function" ? this._type() : this.adapter; + } +}; +AbstractPouchDB.prototype.purge = adapterFun("_purge", function(docId, rev$$1, callback) { + if (typeof this._purge === "undefined") { + return callback(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter.")); + } + var self2 = this; + self2._getRevisionTree(docId, (error, revs) => { + if (error) { + return callback(error); + } + if (!revs) { + return callback(createError(MISSING_DOC)); + } + let path; + try { + path = findPathToLeaf(revs, rev$$1); + } catch (error2) { + return callback(error2.message || error2); + } + self2._purge(docId, path, (error2, result) => { + if (error2) { + return callback(error2); + } else { + appendPurgeSeq(self2, docId, rev$$1).then(function() { + return callback(null, result); + }); + } + }); + }); +}); +var TaskQueue = class { + constructor() { + this.isReady = false; + this.failed = false; + this.queue = []; + } + execute() { + var fun; + if (this.failed) { + while (fun = this.queue.shift()) { + fun(this.failed); + } + } else { + while (fun = this.queue.shift()) { + fun(); + } + } + } + fail(err) { + this.failed = err; + this.execute(); + } + ready(db) { + this.isReady = true; + this.db = db; + this.execute(); + } + addTask(fun) { + this.queue.push(fun); + if (this.failed) { + this.execute(); + } + } +}; +function parseAdapter(name, opts) { + var match2 = name.match(/([a-z-]*):\/\/(.*)/); + if (match2) { + return { + name: /https?/.test(match2[1]) ? match2[1] + "://" + match2[2] : match2[2], + adapter: match2[1] + }; + } + var adapters = PouchDB.adapters; + var preferredAdapters = PouchDB.preferredAdapters; + var prefix = PouchDB.prefix; + var adapterName = opts.adapter; + if (!adapterName) { + for (var i = 0; i < preferredAdapters.length; ++i) { + adapterName = preferredAdapters[i]; + if (adapterName === "idb" && "websql" in adapters && hasLocalStorage() && localStorage["_pouch__websqldb_" + prefix + name]) { + guardedConsole("log", 'PouchDB is downgrading "' + name + '" to WebSQL to avoid data loss, because it was already opened with WebSQL.'); + continue; + } + break; + } + } + var adapter = adapters[adapterName]; + var usePrefix = adapter && "use_prefix" in adapter ? adapter.use_prefix : true; + return { + name: usePrefix ? prefix + name : name, + adapter: adapterName + }; +} +function inherits(A, B) { + A.prototype = Object.create(B.prototype, { + constructor: { value: A } + }); +} +function createClass(parent, init3) { + let klass = function(...args) { + if (!(this instanceof klass)) { + return new klass(...args); + } + init3.apply(this, args); + }; + inherits(klass, parent); + return klass; +} +function prepareForDestruction(self2) { + function onDestroyed(from_constructor) { + self2.removeListener("closed", onClosed); + if (!from_constructor) { + self2.constructor.emit("destroyed", self2.name); + } + } + function onClosed() { + self2.removeListener("destroyed", onDestroyed); + self2.constructor.emit("unref", self2); + } + self2.once("destroyed", onDestroyed); + self2.once("closed", onClosed); + self2.constructor.emit("ref", self2); +} +var PouchInternal = class extends AbstractPouchDB { + constructor(name, opts) { + super(); + this._setup(name, opts); + } + _setup(name, opts) { + super._setup(); + opts = opts || {}; + if (name && typeof name === "object") { + opts = name; + name = opts.name; + delete opts.name; + } + if (opts.deterministic_revs === void 0) { + opts.deterministic_revs = true; + } + this.__opts = opts = clone(opts); + this.auto_compaction = opts.auto_compaction; + this.purged_infos_limit = opts.purged_infos_limit || 1e3; + this.prefix = PouchDB.prefix; + if (typeof name !== "string") { + throw new Error("Missing/invalid DB name"); + } + var prefixedName = (opts.prefix || "") + name; + var backend = parseAdapter(prefixedName, opts); + opts.name = backend.name; + opts.adapter = opts.adapter || backend.adapter; + this.name = name; + this._adapter = opts.adapter; + PouchDB.emit("debug", ["adapter", "Picked adapter: ", opts.adapter]); + if (!PouchDB.adapters[opts.adapter] || !PouchDB.adapters[opts.adapter].valid()) { + throw new Error("Invalid Adapter: " + opts.adapter); + } + if (opts.view_adapter) { + if (!PouchDB.adapters[opts.view_adapter] || !PouchDB.adapters[opts.view_adapter].valid()) { + throw new Error("Invalid View Adapter: " + opts.view_adapter); + } + } + this.taskqueue = new TaskQueue(); + this.adapter = opts.adapter; + PouchDB.adapters[opts.adapter].call(this, opts, (err) => { + if (err) { + return this.taskqueue.fail(err); + } + prepareForDestruction(this); + this.emit("created", this); + PouchDB.emit("created", this.name); + this.taskqueue.ready(this); + }); + } +}; +var PouchDB = createClass(PouchInternal, function(name, opts) { + PouchInternal.prototype._setup.call(this, name, opts); +}); +var ActiveTasks = class { + constructor() { + this.tasks = {}; + } + list() { + return Object.values(this.tasks); + } + add(task) { + const id = v4_default(); + this.tasks[id] = { + id, + name: task.name, + total_items: task.total_items, + created_at: new Date().toJSON() + }; + return id; + } + get(id) { + return this.tasks[id]; + } + remove(id, reason) { + delete this.tasks[id]; + return this.tasks; + } + update(id, updatedTask) { + const task = this.tasks[id]; + if (typeof task !== "undefined") { + const mergedTask = { + id: task.id, + name: task.name, + created_at: task.created_at, + total_items: updatedTask.total_items || task.total_items, + completed_items: updatedTask.completed_items || task.completed_items, + updated_at: new Date().toJSON() + }; + this.tasks[id] = mergedTask; + } + return this.tasks; + } +}; +PouchDB.adapters = {}; +PouchDB.preferredAdapters = []; +PouchDB.prefix = "_pouch_"; +var eventEmitter = new import_events2.default(); +function setUpEventEmitter(Pouch) { + Object.keys(import_events2.default.prototype).forEach(function(key) { + if (typeof import_events2.default.prototype[key] === "function") { + Pouch[key] = eventEmitter[key].bind(eventEmitter); + } + }); + var destructListeners = Pouch._destructionListeners = new ExportedMap(); + Pouch.on("ref", function onConstructorRef(db) { + if (!destructListeners.has(db.name)) { + destructListeners.set(db.name, []); + } + destructListeners.get(db.name).push(db); + }); + Pouch.on("unref", function onConstructorUnref(db) { + if (!destructListeners.has(db.name)) { + return; + } + var dbList = destructListeners.get(db.name); + var pos = dbList.indexOf(db); + if (pos < 0) { + return; + } + dbList.splice(pos, 1); + if (dbList.length > 1) { + destructListeners.set(db.name, dbList); + } else { + destructListeners.delete(db.name); + } + }); + Pouch.on("destroyed", function onConstructorDestroyed(name) { + if (!destructListeners.has(name)) { + return; + } + var dbList = destructListeners.get(name); + destructListeners.delete(name); + dbList.forEach(function(db) { + db.emit("destroyed", true); + }); + }); +} +setUpEventEmitter(PouchDB); +PouchDB.adapter = function(id, obj, addToPreferredAdapters) { + if (obj.valid()) { + PouchDB.adapters[id] = obj; + if (addToPreferredAdapters) { + PouchDB.preferredAdapters.push(id); + } + } +}; +PouchDB.plugin = function(obj) { + if (typeof obj === "function") { + obj(PouchDB); + } else if (typeof obj !== "object" || Object.keys(obj).length === 0) { + throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function'); + } else { + Object.keys(obj).forEach(function(id) { + PouchDB.prototype[id] = obj[id]; + }); + } + if (this.__defaults) { + PouchDB.__defaults = assign$2({}, this.__defaults); + } + return PouchDB; +}; +PouchDB.defaults = function(defaultOpts) { + let PouchWithDefaults = createClass(PouchDB, function(name, opts) { + opts = opts || {}; + if (name && typeof name === "object") { + opts = name; + name = opts.name; + delete opts.name; + } + opts = assign$2({}, PouchWithDefaults.__defaults, opts); + PouchDB.call(this, name, opts); + }); + PouchWithDefaults.preferredAdapters = PouchDB.preferredAdapters.slice(); + Object.keys(PouchDB).forEach(function(key) { + if (!(key in PouchWithDefaults)) { + PouchWithDefaults[key] = PouchDB[key]; + } + }); + PouchWithDefaults.__defaults = assign$2({}, this.__defaults, defaultOpts); + return PouchWithDefaults; +}; +PouchDB.fetch = function(url, opts) { + return f2(url, opts); +}; +PouchDB.prototype.activeTasks = PouchDB.activeTasks = new ActiveTasks(); +var version = "8.0.1"; +PouchDB.plugin(index_browser_es_default); +PouchDB.version = version; +var index_es_default = PouchDB; + +// node_modules/pouchdb-adapter-utils/lib/index.es.js +function toObject(array) { + return array.reduce(function(obj, item) { + obj[item] = true; + return obj; + }, {}); +} +var reservedWords = toObject([ + "_id", + "_rev", + "_access", + "_attachments", + "_deleted", + "_revisions", + "_revs_info", + "_conflicts", + "_deleted_conflicts", + "_local_seq", + "_rev_tree", + "_replication_id", + "_replication_state", + "_replication_state_time", + "_replication_state_reason", + "_replication_stats", + "_removed" +]); +var dataWords = toObject([ + "_access", + "_attachments", + "_replication_id", + "_replication_state", + "_replication_state_time", + "_replication_state_reason", + "_replication_stats" +]); +function parseRevisionInfo(rev$$1) { + if (!/^\d+-/.test(rev$$1)) { + return createError(INVALID_REV); + } + var idx = rev$$1.indexOf("-"); + var left = rev$$1.substring(0, idx); + var right = rev$$1.substring(idx + 1); + return { + prefix: parseInt(left, 10), + id: right + }; +} +function makeRevTreeFromRevisions(revisions, opts) { + var pos = revisions.start - revisions.ids.length + 1; + var revisionIds = revisions.ids; + var ids = [revisionIds[0], opts, []]; + for (var i = 1, len = revisionIds.length; i < len; i++) { + ids = [revisionIds[i], { status: "missing" }, [ids]]; + } + return [{ + pos, + ids + }]; +} +function parseDoc(doc, newEdits, dbOpts) { + if (!dbOpts) { + dbOpts = { + deterministic_revs: true + }; + } + var nRevNum; + var newRevId; + var revInfo; + var opts = { status: "available" }; + if (doc._deleted) { + opts.deleted = true; + } + if (newEdits) { + if (!doc._id) { + doc._id = uuid(); + } + newRevId = rev(doc, dbOpts.deterministic_revs); + if (doc._rev) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + doc._rev_tree = [{ + pos: revInfo.prefix, + ids: [revInfo.id, { status: "missing" }, [[newRevId, opts, []]]] + }]; + nRevNum = revInfo.prefix + 1; + } else { + doc._rev_tree = [{ + pos: 1, + ids: [newRevId, opts, []] + }]; + nRevNum = 1; + } + } else { + if (doc._revisions) { + doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); + nRevNum = doc._revisions.start; + newRevId = doc._revisions.ids[0]; + } + if (!doc._rev_tree) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + nRevNum = revInfo.prefix; + newRevId = revInfo.id; + doc._rev_tree = [{ + pos: nRevNum, + ids: [newRevId, opts, []] + }]; + } + } + invalidIdError(doc._id); + doc._rev = nRevNum + "-" + newRevId; + var result = { metadata: {}, data: {} }; + for (var key in doc) { + if (Object.prototype.hasOwnProperty.call(doc, key)) { + var specialKey = key[0] === "_"; + if (specialKey && !reservedWords[key]) { + var error = createError(DOC_VALIDATION, key); + error.message = DOC_VALIDATION.message + ": " + key; + throw error; + } else if (specialKey && !dataWords[key]) { + result.metadata[key.slice(1)] = doc[key]; + } else { + result.data[key] = doc[key]; + } + } + } + return result; +} +function parseBase64(data) { + try { + return thisAtob(data); + } catch (e2) { + var err = createError( + BAD_ARG, + "Attachment is not a valid base64 string" + ); + return { error: err }; + } +} +function preprocessString(att, blobType, callback) { + var asBinary = parseBase64(att.data); + if (asBinary.error) { + return callback(asBinary.error); + } + att.length = asBinary.length; + if (blobType === "blob") { + att.data = binStringToBluffer(asBinary, att.content_type); + } else if (blobType === "base64") { + att.data = thisBtoa(asBinary); + } else { + att.data = asBinary; + } + binaryMd5(asBinary, function(result) { + att.digest = "md5-" + result; + callback(); + }); +} +function preprocessBlob(att, blobType, callback) { + binaryMd5(att.data, function(md5) { + att.digest = "md5-" + md5; + att.length = att.data.size || att.data.length || 0; + if (blobType === "binary") { + blobToBinaryString(att.data, function(binString) { + att.data = binString; + callback(); + }); + } else if (blobType === "base64") { + blobToBase64(att.data, function(b64) { + att.data = b64; + callback(); + }); + } else { + callback(); + } + }); +} +function preprocessAttachment(att, blobType, callback) { + if (att.stub) { + return callback(); + } + if (typeof att.data === "string") { + preprocessString(att, blobType, callback); + } else { + preprocessBlob(att, blobType, callback); + } +} +function preprocessAttachments(docInfos, blobType, callback) { + if (!docInfos.length) { + return callback(); + } + var docv = 0; + var overallErr; + docInfos.forEach(function(docInfo) { + var attachments = docInfo.data && docInfo.data._attachments ? Object.keys(docInfo.data._attachments) : []; + var recv = 0; + if (!attachments.length) { + return done(); + } + function processedAttachment(err) { + overallErr = err; + recv++; + if (recv === attachments.length) { + done(); + } + } + for (var key in docInfo.data._attachments) { + if (Object.prototype.hasOwnProperty.call(docInfo.data._attachments, key)) { + preprocessAttachment( + docInfo.data._attachments[key], + blobType, + processedAttachment + ); + } + } + }); + function done() { + docv++; + if (docInfos.length === docv) { + if (overallErr) { + callback(overallErr); + } else { + callback(); + } + } + } +} +function updateDoc(revLimit, prev, docInfo, results, i, cb, writeDoc, newEdits) { + if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) { + results[i] = docInfo; + return cb(); + } + var previousWinningRev = prev.winningRev || winningRev(prev); + var previouslyDeleted = "deleted" in prev ? prev.deleted : isDeleted(prev, previousWinningRev); + var deleted = "deleted" in docInfo.metadata ? docInfo.metadata.deleted : isDeleted(docInfo.metadata); + var isRoot = /^1-/.test(docInfo.metadata.rev); + if (previouslyDeleted && !deleted && newEdits && isRoot) { + var newDoc = docInfo.data; + newDoc._rev = previousWinningRev; + newDoc._id = docInfo.metadata.id; + docInfo = parseDoc(newDoc, newEdits); + } + var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); + var inConflict = newEdits && (previouslyDeleted && deleted && merged.conflicts !== "new_leaf" || !previouslyDeleted && merged.conflicts !== "new_leaf" || previouslyDeleted && !deleted && merged.conflicts === "new_branch"); + if (inConflict) { + var err = createError(REV_CONFLICT); + results[i] = err; + return cb(); + } + var newRev = docInfo.metadata.rev; + docInfo.metadata.rev_tree = merged.tree; + docInfo.stemmedRevs = merged.stemmedRevs || []; + if (prev.rev_map) { + docInfo.metadata.rev_map = prev.rev_map; + } + var winningRev$$1 = winningRev(docInfo.metadata); + var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1); + var delta = previouslyDeleted === winningRevIsDeleted ? 0 : previouslyDeleted < winningRevIsDeleted ? -1 : 1; + var newRevIsDeleted; + if (newRev === winningRev$$1) { + newRevIsDeleted = winningRevIsDeleted; + } else { + newRevIsDeleted = isDeleted(docInfo.metadata, newRev); + } + writeDoc( + docInfo, + winningRev$$1, + winningRevIsDeleted, + newRevIsDeleted, + true, + delta, + i, + cb + ); +} +function rootIsMissing(docInfo) { + return docInfo.metadata.rev_tree[0].ids[1].status === "missing"; +} +function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, writeDoc, opts, overallCallback) { + revLimit = revLimit || 1e3; + function insertDoc(docInfo, resultsIdx, callback) { + var winningRev$$1 = winningRev(docInfo.metadata); + var deleted = isDeleted(docInfo.metadata, winningRev$$1); + if ("was_delete" in opts && deleted) { + results[resultsIdx] = createError(MISSING_DOC, "deleted"); + return callback(); + } + var inConflict = newEdits && rootIsMissing(docInfo); + if (inConflict) { + var err = createError(REV_CONFLICT); + results[resultsIdx] = err; + return callback(); + } + var delta = deleted ? 0 : 1; + writeDoc( + docInfo, + winningRev$$1, + deleted, + deleted, + false, + delta, + resultsIdx, + callback + ); + } + var newEdits = opts.new_edits; + var idsToDocs = new ExportedMap(); + var docsDone = 0; + var docsToDo = docInfos.length; + function checkAllDocsDone() { + if (++docsDone === docsToDo && overallCallback) { + overallCallback(); + } + } + docInfos.forEach(function(currentDoc, resultsIdx) { + if (currentDoc._id && isLocalId(currentDoc._id)) { + var fun = currentDoc._deleted ? "_removeLocal" : "_putLocal"; + api[fun](currentDoc, { ctx: tx }, function(err, res2) { + results[resultsIdx] = err || res2; + checkAllDocsDone(); + }); + return; + } + var id = currentDoc.metadata.id; + if (idsToDocs.has(id)) { + docsToDo--; + idsToDocs.get(id).push([currentDoc, resultsIdx]); + } else { + idsToDocs.set(id, [[currentDoc, resultsIdx]]); + } + }); + idsToDocs.forEach(function(docs, id) { + var numDone = 0; + function docWritten() { + if (++numDone < docs.length) { + nextDoc(); + } else { + checkAllDocsDone(); + } + } + function nextDoc() { + var value = docs[numDone]; + var currentDoc = value[0]; + var resultsIdx = value[1]; + if (fetchedDocs.has(id)) { + updateDoc( + revLimit, + fetchedDocs.get(id), + currentDoc, + results, + resultsIdx, + docWritten, + writeDoc, + newEdits + ); + } else { + var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); + currentDoc.metadata.rev_tree = merged.tree; + currentDoc.stemmedRevs = merged.stemmedRevs || []; + insertDoc(currentDoc, resultsIdx, docWritten); + } + } + nextDoc(); + }); +} + +// node_modules/pouchdb-json/lib/index.es.js +var import_vuvuzela = __toESM(require_vuvuzela()); +function safeJsonParse(str) { + try { + return JSON.parse(str); + } catch (e2) { + return import_vuvuzela.default.parse(str); + } +} +function safeJsonStringify(json) { + try { + return JSON.stringify(json); + } catch (e2) { + return import_vuvuzela.default.stringify(json); + } +} + +// node_modules/pouchdb-adapter-idb/lib/index.es.js +var ADAPTER_VERSION = 5; +var DOC_STORE = "document-store"; +var BY_SEQ_STORE = "by-sequence"; +var ATTACH_STORE = "attach-store"; +var ATTACH_AND_SEQ_STORE = "attach-seq-store"; +var META_STORE = "meta-store"; +var LOCAL_STORE = "local-store"; +var DETECT_BLOB_SUPPORT_STORE = "detect-blob-support"; +function idbError(callback) { + return function(evt) { + var message = "unknown_error"; + if (evt.target && evt.target.error) { + message = evt.target.error.name || evt.target.error.message; + } + callback(createError(IDB_ERROR, message, evt.type)); + }; +} +function encodeMetadata(metadata, winningRev$$1, deleted) { + return { + data: safeJsonStringify(metadata), + winningRev: winningRev$$1, + deletedOrLocal: deleted ? "1" : "0", + seq: metadata.seq, + id: metadata.id + }; +} +function decodeMetadata(storedObject) { + if (!storedObject) { + return null; + } + var metadata = safeJsonParse(storedObject.data); + metadata.winningRev = storedObject.winningRev; + metadata.deleted = storedObject.deletedOrLocal === "1"; + metadata.seq = storedObject.seq; + return metadata; +} +function decodeDoc(doc) { + if (!doc) { + return doc; + } + var idx = doc._doc_id_rev.lastIndexOf(":"); + doc._id = doc._doc_id_rev.substring(0, idx - 1); + doc._rev = doc._doc_id_rev.substring(idx + 1); + delete doc._doc_id_rev; + return doc; +} +function readBlobData(body, type, asBlob, callback) { + if (asBlob) { + if (!body) { + callback(createBlob([""], { type })); + } else if (typeof body !== "string") { + callback(body); + } else { + callback(b64ToBluffer(body, type)); + } + } else { + if (!body) { + callback(""); + } else if (typeof body !== "string") { + readAsBinaryString(body, function(binary) { + callback(thisBtoa(binary)); + }); + } else { + callback(body); + } + } +} +function fetchAttachmentsIfNecessary(doc, opts, txn, cb) { + var attachments = Object.keys(doc._attachments || {}); + if (!attachments.length) { + return cb && cb(); + } + var numDone = 0; + function checkDone() { + if (++numDone === attachments.length && cb) { + cb(); + } + } + function fetchAttachment(doc2, att) { + var attObj = doc2._attachments[att]; + var digest = attObj.digest; + var req = txn.objectStore(ATTACH_STORE).get(digest); + req.onsuccess = function(e2) { + attObj.body = e2.target.result.body; + checkDone(); + }; + } + attachments.forEach(function(att) { + if (opts.attachments && opts.include_docs) { + fetchAttachment(doc, att); + } else { + doc._attachments[att].stub = true; + checkDone(); + } + }); +} +function postProcessAttachments(results, asBlob) { + return Promise.all(results.map(function(row) { + if (row.doc && row.doc._attachments) { + var attNames = Object.keys(row.doc._attachments); + return Promise.all(attNames.map(function(att) { + var attObj = row.doc._attachments[att]; + if (!("body" in attObj)) { + return; + } + var body = attObj.body; + var type = attObj.content_type; + return new Promise(function(resolve) { + readBlobData(body, type, asBlob, function(data) { + row.doc._attachments[att] = assign$2( + pick(attObj, ["digest", "content_type"]), + { data } + ); + resolve(); + }); + }); + })); + } + })); +} +function compactRevs(revs, docId, txn) { + var possiblyOrphanedDigests = []; + var seqStore = txn.objectStore(BY_SEQ_STORE); + var attStore = txn.objectStore(ATTACH_STORE); + var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + var count = revs.length; + function checkDone() { + count--; + if (!count) { + deleteOrphanedAttachments(); + } + } + function deleteOrphanedAttachments() { + if (!possiblyOrphanedDigests.length) { + return; + } + possiblyOrphanedDigests.forEach(function(digest) { + var countReq = attAndSeqStore.index("digestSeq").count( + IDBKeyRange.bound( + digest + "::", + digest + "::\uFFFF", + false, + false + ) + ); + countReq.onsuccess = function(e2) { + var count2 = e2.target.result; + if (!count2) { + attStore.delete(digest); + } + }; + }); + } + revs.forEach(function(rev2) { + var index5 = seqStore.index("_doc_id_rev"); + var key = docId + "::" + rev2; + index5.getKey(key).onsuccess = function(e2) { + var seq = e2.target.result; + if (typeof seq !== "number") { + return checkDone(); + } + seqStore.delete(seq); + var cursor = attAndSeqStore.index("seq").openCursor(IDBKeyRange.only(seq)); + cursor.onsuccess = function(event) { + var cursor2 = event.target.result; + if (cursor2) { + var digest = cursor2.value.digestSeq.split("::")[0]; + possiblyOrphanedDigests.push(digest); + attAndSeqStore.delete(cursor2.primaryKey); + cursor2.continue(); + } else { + checkDone(); + } + }; + }; + }); +} +function openTransactionSafely(idb, stores, mode) { + try { + return { + txn: idb.transaction(stores, mode) + }; + } catch (err) { + return { + error: err + }; + } +} +var changesHandler$1 = new Changes(); +function idbBulkDocs(dbOpts, req, opts, api, idb, callback) { + var docInfos = req.docs; + var txn; + var docStore; + var bySeqStore; + var attachStore; + var attachAndSeqStore; + var metaStore; + var docInfoError; + var metaDoc; + for (var i = 0, len = docInfos.length; i < len; i++) { + var doc = docInfos[i]; + if (doc._id && isLocalId(doc._id)) { + continue; + } + doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts); + if (doc.error && !docInfoError) { + docInfoError = doc; + } + } + if (docInfoError) { + return callback(docInfoError); + } + var allDocsProcessed = false; + var docCountDelta = 0; + var results = new Array(docInfos.length); + var fetchedDocs = new ExportedMap(); + var preconditionErrored = false; + var blobType = api._meta.blobSupport ? "blob" : "base64"; + preprocessAttachments(docInfos, blobType, function(err) { + if (err) { + return callback(err); + } + startTransaction(); + }); + function startTransaction() { + var stores = [ + DOC_STORE, + BY_SEQ_STORE, + ATTACH_STORE, + LOCAL_STORE, + ATTACH_AND_SEQ_STORE, + META_STORE + ]; + var txnResult = openTransactionSafely(idb, stores, "readwrite"); + if (txnResult.error) { + return callback(txnResult.error); + } + txn = txnResult.txn; + txn.onabort = idbError(callback); + txn.ontimeout = idbError(callback); + txn.oncomplete = complete; + docStore = txn.objectStore(DOC_STORE); + bySeqStore = txn.objectStore(BY_SEQ_STORE); + attachStore = txn.objectStore(ATTACH_STORE); + attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + metaStore = txn.objectStore(META_STORE); + metaStore.get(META_STORE).onsuccess = function(e2) { + metaDoc = e2.target.result; + updateDocCountIfReady(); + }; + verifyAttachments(function(err) { + if (err) { + preconditionErrored = true; + return callback(err); + } + fetchExistingDocs(); + }); + } + function onAllDocsProcessed() { + allDocsProcessed = true; + updateDocCountIfReady(); + } + function idbProcessDocs() { + processDocs( + dbOpts.revs_limit, + docInfos, + api, + fetchedDocs, + txn, + results, + writeDoc, + opts, + onAllDocsProcessed + ); + } + function updateDocCountIfReady() { + if (!metaDoc || !allDocsProcessed) { + return; + } + metaDoc.docCount += docCountDelta; + metaStore.put(metaDoc); + } + function fetchExistingDocs() { + if (!docInfos.length) { + return; + } + var numFetched = 0; + function checkDone() { + if (++numFetched === docInfos.length) { + idbProcessDocs(); + } + } + function readMetadata(event) { + var metadata = decodeMetadata(event.target.result); + if (metadata) { + fetchedDocs.set(metadata.id, metadata); + } + checkDone(); + } + for (var i2 = 0, len2 = docInfos.length; i2 < len2; i2++) { + var docInfo = docInfos[i2]; + if (docInfo._id && isLocalId(docInfo._id)) { + checkDone(); + continue; + } + var req2 = docStore.get(docInfo.metadata.id); + req2.onsuccess = readMetadata; + } + } + function complete() { + if (preconditionErrored) { + return; + } + changesHandler$1.notify(api._meta.name); + callback(null, results); + } + function verifyAttachment(digest, callback2) { + var req2 = attachStore.get(digest); + req2.onsuccess = function(e2) { + if (!e2.target.result) { + var err = createError( + MISSING_STUB, + "unknown stub attachment with digest " + digest + ); + err.status = 412; + callback2(err); + } else { + callback2(); + } + }; + } + function verifyAttachments(finish) { + var digests = []; + docInfos.forEach(function(docInfo) { + if (docInfo.data && docInfo.data._attachments) { + Object.keys(docInfo.data._attachments).forEach(function(filename) { + var att = docInfo.data._attachments[filename]; + if (att.stub) { + digests.push(att.digest); + } + }); + } + }); + if (!digests.length) { + return finish(); + } + var numDone = 0; + var err; + function checkDone() { + if (++numDone === digests.length) { + finish(err); + } + } + digests.forEach(function(digest) { + verifyAttachment(digest, function(attErr) { + if (attErr && !err) { + err = attErr; + } + checkDone(); + }); + }); + } + function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted, isUpdate, delta, resultsIdx, callback2) { + docInfo.metadata.winningRev = winningRev$$1; + docInfo.metadata.deleted = winningRevIsDeleted; + var doc2 = docInfo.data; + doc2._id = docInfo.metadata.id; + doc2._rev = docInfo.metadata.rev; + if (newRevIsDeleted) { + doc2._deleted = true; + } + var hasAttachments = doc2._attachments && Object.keys(doc2._attachments).length; + if (hasAttachments) { + return writeAttachments( + docInfo, + winningRev$$1, + winningRevIsDeleted, + isUpdate, + resultsIdx, + callback2 + ); + } + docCountDelta += delta; + updateDocCountIfReady(); + finishDoc( + docInfo, + winningRev$$1, + winningRevIsDeleted, + isUpdate, + resultsIdx, + callback2 + ); + } + function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted, isUpdate, resultsIdx, callback2) { + var doc2 = docInfo.data; + var metadata = docInfo.metadata; + doc2._doc_id_rev = metadata.id + "::" + metadata.rev; + delete doc2._id; + delete doc2._rev; + function afterPutDoc(e2) { + var revsToDelete = docInfo.stemmedRevs || []; + if (isUpdate && api.auto_compaction) { + revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata)); + } + if (revsToDelete && revsToDelete.length) { + compactRevs(revsToDelete, docInfo.metadata.id, txn); + } + metadata.seq = e2.target.result; + var metadataToStore = encodeMetadata( + metadata, + winningRev$$1, + winningRevIsDeleted + ); + var metaDataReq = docStore.put(metadataToStore); + metaDataReq.onsuccess = afterPutMetadata; + } + function afterPutDocError(e2) { + e2.preventDefault(); + e2.stopPropagation(); + var index5 = bySeqStore.index("_doc_id_rev"); + var getKeyReq = index5.getKey(doc2._doc_id_rev); + getKeyReq.onsuccess = function(e3) { + var putReq2 = bySeqStore.put(doc2, e3.target.result); + putReq2.onsuccess = afterPutDoc; + }; + } + function afterPutMetadata() { + results[resultsIdx] = { + ok: true, + id: metadata.id, + rev: metadata.rev + }; + fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); + insertAttachmentMappings(docInfo, metadata.seq, callback2); + } + var putReq = bySeqStore.put(doc2); + putReq.onsuccess = afterPutDoc; + putReq.onerror = afterPutDocError; + } + function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted, isUpdate, resultsIdx, callback2) { + var doc2 = docInfo.data; + var numDone = 0; + var attachments = Object.keys(doc2._attachments); + function collectResults() { + if (numDone === attachments.length) { + finishDoc( + docInfo, + winningRev$$1, + winningRevIsDeleted, + isUpdate, + resultsIdx, + callback2 + ); + } + } + function attachmentSaved() { + numDone++; + collectResults(); + } + attachments.forEach(function(key) { + var att = docInfo.data._attachments[key]; + if (!att.stub) { + var data = att.data; + delete att.data; + att.revpos = parseInt(winningRev$$1, 10); + var digest = att.digest; + saveAttachment(digest, data, attachmentSaved); + } else { + numDone++; + collectResults(); + } + }); + } + function insertAttachmentMappings(docInfo, seq, callback2) { + var attsAdded = 0; + var attsToAdd = Object.keys(docInfo.data._attachments || {}); + if (!attsToAdd.length) { + return callback2(); + } + function checkDone() { + if (++attsAdded === attsToAdd.length) { + callback2(); + } + } + function add(att) { + var digest = docInfo.data._attachments[att].digest; + var req2 = attachAndSeqStore.put({ + seq, + digestSeq: digest + "::" + seq + }); + req2.onsuccess = checkDone; + req2.onerror = function(e2) { + e2.preventDefault(); + e2.stopPropagation(); + checkDone(); + }; + } + for (var i2 = 0; i2 < attsToAdd.length; i2++) { + add(attsToAdd[i2]); + } + } + function saveAttachment(digest, data, callback2) { + var getKeyReq = attachStore.count(digest); + getKeyReq.onsuccess = function(e2) { + var count = e2.target.result; + if (count) { + return callback2(); + } + var newAtt = { + digest, + body: data + }; + var putReq = attachStore.put(newAtt); + putReq.onsuccess = callback2; + }; + } +} +function runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) { + if (batchSize === -1) { + batchSize = 1e3; + } + var useGetAll = typeof objectStore.getAll === "function" && typeof objectStore.getAllKeys === "function" && batchSize > 1 && !descending; + var keysBatch; + var valuesBatch; + var pseudoCursor; + function onGetAll(e2) { + valuesBatch = e2.target.result; + if (keysBatch) { + onBatch(keysBatch, valuesBatch, pseudoCursor); + } + } + function onGetAllKeys(e2) { + keysBatch = e2.target.result; + if (valuesBatch) { + onBatch(keysBatch, valuesBatch, pseudoCursor); + } + } + function continuePseudoCursor() { + if (!keysBatch.length) { + return onBatch(); + } + var lastKey = keysBatch[keysBatch.length - 1]; + var newKeyRange; + if (keyRange && keyRange.upper) { + try { + newKeyRange = IDBKeyRange.bound( + lastKey, + keyRange.upper, + true, + keyRange.upperOpen + ); + } catch (e2) { + if (e2.name === "DataError" && e2.code === 0) { + return onBatch(); + } + } + } else { + newKeyRange = IDBKeyRange.lowerBound(lastKey, true); + } + keyRange = newKeyRange; + keysBatch = null; + valuesBatch = null; + objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll; + objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys; + } + function onCursor(e2) { + var cursor = e2.target.result; + if (!cursor) { + return onBatch(); + } + onBatch([cursor.key], [cursor.value], cursor); + } + if (useGetAll) { + pseudoCursor = { "continue": continuePseudoCursor }; + objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll; + objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys; + } else if (descending) { + objectStore.openCursor(keyRange, "prev").onsuccess = onCursor; + } else { + objectStore.openCursor(keyRange).onsuccess = onCursor; + } +} +function getAll(objectStore, keyRange, onSuccess) { + if (typeof objectStore.getAll === "function") { + objectStore.getAll(keyRange).onsuccess = onSuccess; + return; + } + var values = []; + function onCursor(e2) { + var cursor = e2.target.result; + if (cursor) { + values.push(cursor.value); + cursor.continue(); + } else { + onSuccess({ + target: { + result: values + } + }); + } + } + objectStore.openCursor(keyRange).onsuccess = onCursor; +} +function allDocsKeys(keys2, docStore, onBatch) { + var valuesBatch = new Array(keys2.length); + var count = 0; + keys2.forEach(function(key, index5) { + docStore.get(key).onsuccess = function(event) { + if (event.target.result) { + valuesBatch[index5] = event.target.result; + } else { + valuesBatch[index5] = { key, error: "not_found" }; + } + count++; + if (count === keys2.length) { + onBatch(keys2, valuesBatch, {}); + } + }; + }); +} +function createKeyRange(start, end, inclusiveEnd, key, descending) { + try { + if (start && end) { + if (descending) { + return IDBKeyRange.bound(end, start, !inclusiveEnd, false); + } else { + return IDBKeyRange.bound(start, end, false, !inclusiveEnd); + } + } else if (start) { + if (descending) { + return IDBKeyRange.upperBound(start); + } else { + return IDBKeyRange.lowerBound(start); + } + } else if (end) { + if (descending) { + return IDBKeyRange.lowerBound(end, !inclusiveEnd); + } else { + return IDBKeyRange.upperBound(end, !inclusiveEnd); + } + } else if (key) { + return IDBKeyRange.only(key); + } + } catch (e2) { + return { error: e2 }; + } + return null; +} +function idbAllDocs(opts, idb, callback) { + var start = "startkey" in opts ? opts.startkey : false; + var end = "endkey" in opts ? opts.endkey : false; + var key = "key" in opts ? opts.key : false; + var keys2 = "keys" in opts ? opts.keys : false; + var skip = opts.skip || 0; + var limit = typeof opts.limit === "number" ? opts.limit : -1; + var inclusiveEnd = opts.inclusive_end !== false; + var keyRange; + var keyRangeError; + if (!keys2) { + keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending); + keyRangeError = keyRange && keyRange.error; + if (keyRangeError && !(keyRangeError.name === "DataError" && keyRangeError.code === 0)) { + return callback(createError( + IDB_ERROR, + keyRangeError.name, + keyRangeError.message + )); + } + } + var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE]; + if (opts.attachments) { + stores.push(ATTACH_STORE); + } + var txnResult = openTransactionSafely(idb, stores, "readonly"); + if (txnResult.error) { + return callback(txnResult.error); + } + var txn = txnResult.txn; + txn.oncomplete = onTxnComplete; + txn.onabort = idbError(callback); + var docStore = txn.objectStore(DOC_STORE); + var seqStore = txn.objectStore(BY_SEQ_STORE); + var metaStore = txn.objectStore(META_STORE); + var docIdRevIndex = seqStore.index("_doc_id_rev"); + var results = []; + var docCount; + var updateSeq; + metaStore.get(META_STORE).onsuccess = function(e2) { + docCount = e2.target.result.docCount; + }; + if (opts.update_seq) { + getMaxUpdateSeq(seqStore, function(e2) { + if (e2.target.result && e2.target.result.length > 0) { + updateSeq = e2.target.result[0]; + } + }); + } + function getMaxUpdateSeq(objectStore, onSuccess) { + function onCursor(e2) { + var cursor = e2.target.result; + var maxKey = void 0; + if (cursor && cursor.key) { + maxKey = cursor.key; + } + return onSuccess({ + target: { + result: [maxKey] + } + }); + } + objectStore.openCursor(null, "prev").onsuccess = onCursor; + } + function fetchDocAsynchronously(metadata, row, winningRev$$1) { + var key2 = metadata.id + "::" + winningRev$$1; + docIdRevIndex.get(key2).onsuccess = function onGetDoc(e2) { + row.doc = decodeDoc(e2.target.result) || {}; + if (opts.conflicts) { + var conflicts = collectConflicts(metadata); + if (conflicts.length) { + row.doc._conflicts = conflicts; + } + } + fetchAttachmentsIfNecessary(row.doc, opts, txn); + }; + } + function allDocsInner(winningRev$$1, metadata) { + var row = { + id: metadata.id, + key: metadata.id, + value: { + rev: winningRev$$1 + } + }; + var deleted = metadata.deleted; + if (deleted) { + if (keys2) { + results.push(row); + row.value.deleted = true; + row.doc = null; + } + } else if (skip-- <= 0) { + results.push(row); + if (opts.include_docs) { + fetchDocAsynchronously(metadata, row, winningRev$$1); + } + } + } + function processBatch(batchValues) { + for (var i = 0, len = batchValues.length; i < len; i++) { + if (results.length === limit) { + break; + } + var batchValue = batchValues[i]; + if (batchValue.error && keys2) { + results.push(batchValue); + continue; + } + var metadata = decodeMetadata(batchValue); + var winningRev$$1 = metadata.winningRev; + allDocsInner(winningRev$$1, metadata); + } + } + function onBatch(batchKeys, batchValues, cursor) { + if (!cursor) { + return; + } + processBatch(batchValues); + if (results.length < limit) { + cursor.continue(); + } + } + function onGetAll(e2) { + var values = e2.target.result; + if (opts.descending) { + values = values.reverse(); + } + processBatch(values); + } + function onResultsReady() { + var returnVal = { + total_rows: docCount, + offset: opts.skip, + rows: results + }; + if (opts.update_seq && updateSeq !== void 0) { + returnVal.update_seq = updateSeq; + } + callback(null, returnVal); + } + function onTxnComplete() { + if (opts.attachments) { + postProcessAttachments(results, opts.binary).then(onResultsReady); + } else { + onResultsReady(); + } + } + if (keyRangeError || limit === 0) { + return; + } + if (keys2) { + return allDocsKeys(opts.keys, docStore, onBatch); + } + if (limit === -1) { + return getAll(docStore, keyRange, onGetAll); + } + runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch); +} +function checkBlobSupport(txn) { + return new Promise(function(resolve) { + var blob$$1 = createBlob([""]); + var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, "key"); + req.onsuccess = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + req.onerror = txn.onabort = function(e2) { + e2.preventDefault(); + e2.stopPropagation(); + resolve(false); + }; + }).catch(function() { + return false; + }); +} +function countDocs(txn, cb) { + var index5 = txn.objectStore(DOC_STORE).index("deletedOrLocal"); + index5.count(IDBKeyRange.only("0")).onsuccess = function(e2) { + cb(e2.target.result); + }; +} +var running = false; +var queue = []; +function tryCode(fun, err, res2, PouchDB2) { + try { + fun(err, res2); + } catch (err2) { + PouchDB2.emit("error", err2); + } +} +function applyNext() { + if (running || !queue.length) { + return; + } + running = true; + queue.shift()(); +} +function enqueueTask(action, callback, PouchDB2) { + queue.push(function runAction() { + action(function runCallback(err, res2) { + tryCode(callback, err, res2, PouchDB2); + running = false; + (0, import_immediate.default)(function runNext() { + applyNext(PouchDB2); + }); + }); + }); + applyNext(); +} +function changes(opts, api, dbName, idb) { + opts = clone(opts); + if (opts.continuous) { + var id = dbName + ":" + uuid(); + changesHandler$1.addListener(dbName, id, api, opts); + changesHandler$1.notify(dbName); + return { + cancel: function() { + changesHandler$1.removeListener(dbName, id); + } + }; + } + var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids); + opts.since = opts.since || 0; + var lastSeq = opts.since; + var limit = "limit" in opts ? opts.limit : -1; + if (limit === 0) { + limit = 1; + } + var results = []; + var numResults = 0; + var filter2 = filterChange(opts); + var docIdsToMetadata = new ExportedMap(); + var txn; + var bySeqStore; + var docStore; + var docIdRevIndex; + function onBatch(batchKeys, batchValues, cursor) { + if (!cursor || !batchKeys.length) { + return; + } + var winningDocs = new Array(batchKeys.length); + var metadatas = new Array(batchKeys.length); + function processMetadataAndWinningDoc(metadata, winningDoc) { + var change = opts.processChange(winningDoc, metadata, opts); + lastSeq = change.seq = metadata.seq; + var filtered = filter2(change); + if (typeof filtered === "object") { + return Promise.reject(filtered); + } + if (!filtered) { + return Promise.resolve(); + } + numResults++; + if (opts.return_docs) { + results.push(change); + } + if (opts.attachments && opts.include_docs) { + return new Promise(function(resolve) { + fetchAttachmentsIfNecessary(winningDoc, opts, txn, function() { + postProcessAttachments([change], opts.binary).then(function() { + resolve(change); + }); + }); + }); + } else { + return Promise.resolve(change); + } + } + function onBatchDone() { + var promises = []; + for (var i = 0, len = winningDocs.length; i < len; i++) { + if (numResults === limit) { + break; + } + var winningDoc = winningDocs[i]; + if (!winningDoc) { + continue; + } + var metadata = metadatas[i]; + promises.push(processMetadataAndWinningDoc(metadata, winningDoc)); + } + Promise.all(promises).then(function(changes3) { + for (var i2 = 0, len2 = changes3.length; i2 < len2; i2++) { + if (changes3[i2]) { + opts.onChange(changes3[i2]); + } + } + }).catch(opts.complete); + if (numResults !== limit) { + cursor.continue(); + } + } + var numDone = 0; + batchValues.forEach(function(value, i) { + var doc = decodeDoc(value); + var seq = batchKeys[i]; + fetchWinningDocAndMetadata(doc, seq, function(metadata, winningDoc) { + metadatas[i] = metadata; + winningDocs[i] = winningDoc; + if (++numDone === batchKeys.length) { + onBatchDone(); + } + }); + }); + } + function onGetMetadata(doc, seq, metadata, cb) { + if (metadata.seq !== seq) { + return cb(); + } + if (metadata.winningRev === doc._rev) { + return cb(metadata, doc); + } + var docIdRev = doc._id + "::" + metadata.winningRev; + var req = docIdRevIndex.get(docIdRev); + req.onsuccess = function(e2) { + cb(metadata, decodeDoc(e2.target.result)); + }; + } + function fetchWinningDocAndMetadata(doc, seq, cb) { + if (docIds && !docIds.has(doc._id)) { + return cb(); + } + var metadata = docIdsToMetadata.get(doc._id); + if (metadata) { + return onGetMetadata(doc, seq, metadata, cb); + } + docStore.get(doc._id).onsuccess = function(e2) { + metadata = decodeMetadata(e2.target.result); + docIdsToMetadata.set(doc._id, metadata); + onGetMetadata(doc, seq, metadata, cb); + }; + } + function finish() { + opts.complete(null, { + results, + last_seq: lastSeq + }); + } + function onTxnComplete() { + if (!opts.continuous && opts.attachments) { + postProcessAttachments(results).then(finish); + } else { + finish(); + } + } + var objectStores = [DOC_STORE, BY_SEQ_STORE]; + if (opts.attachments) { + objectStores.push(ATTACH_STORE); + } + var txnResult = openTransactionSafely(idb, objectStores, "readonly"); + if (txnResult.error) { + return opts.complete(txnResult.error); + } + txn = txnResult.txn; + txn.onabort = idbError(opts.complete); + txn.oncomplete = onTxnComplete; + bySeqStore = txn.objectStore(BY_SEQ_STORE); + docStore = txn.objectStore(DOC_STORE); + docIdRevIndex = bySeqStore.index("_doc_id_rev"); + var keyRange = opts.since && !opts.descending ? IDBKeyRange.lowerBound(opts.since, true) : null; + runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch); +} +var cachedDBs = new ExportedMap(); +var blobSupportPromise; +var openReqList = new ExportedMap(); +function IdbPouch(opts, callback) { + var api = this; + enqueueTask(function(thisCallback) { + init(api, opts, thisCallback); + }, callback, api.constructor); +} +function init(api, opts, callback) { + var dbName = opts.name; + var idb = null; + var idbGlobalFailureError = null; + api._meta = null; + function enrichCallbackError(callback2) { + return function(error, result) { + if (error && error instanceof Error && !error.reason) { + if (idbGlobalFailureError) { + error.reason = idbGlobalFailureError; + } + } + callback2(error, result); + }; + } + function createSchema(db) { + var docStore = db.createObjectStore(DOC_STORE, { keyPath: "id" }); + db.createObjectStore(BY_SEQ_STORE, { autoIncrement: true }).createIndex("_doc_id_rev", "_doc_id_rev", { unique: true }); + db.createObjectStore(ATTACH_STORE, { keyPath: "digest" }); + db.createObjectStore(META_STORE, { keyPath: "id", autoIncrement: false }); + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + docStore.createIndex("deletedOrLocal", "deletedOrLocal", { unique: false }); + db.createObjectStore(LOCAL_STORE, { keyPath: "_id" }); + var attAndSeqStore = db.createObjectStore( + ATTACH_AND_SEQ_STORE, + { autoIncrement: true } + ); + attAndSeqStore.createIndex("seq", "seq"); + attAndSeqStore.createIndex("digestSeq", "digestSeq", { unique: true }); + } + function addDeletedOrLocalIndex(txn, callback2) { + var docStore = txn.objectStore(DOC_STORE); + docStore.createIndex("deletedOrLocal", "deletedOrLocal", { unique: false }); + docStore.openCursor().onsuccess = function(event) { + var cursor = event.target.result; + if (cursor) { + var metadata = cursor.value; + var deleted = isDeleted(metadata); + metadata.deletedOrLocal = deleted ? "1" : "0"; + docStore.put(metadata); + cursor.continue(); + } else { + callback2(); + } + }; + } + function createLocalStoreSchema(db) { + db.createObjectStore(LOCAL_STORE, { keyPath: "_id" }).createIndex("_doc_id_rev", "_doc_id_rev", { unique: true }); + } + function migrateLocalStore(txn, cb) { + var localStore = txn.objectStore(LOCAL_STORE); + var docStore = txn.objectStore(DOC_STORE); + var seqStore = txn.objectStore(BY_SEQ_STORE); + var cursor = docStore.openCursor(); + cursor.onsuccess = function(event) { + var cursor2 = event.target.result; + if (cursor2) { + var metadata = cursor2.value; + var docId = metadata.id; + var local = isLocalId(docId); + var rev2 = winningRev(metadata); + if (local) { + var docIdRev = docId + "::" + rev2; + var start = docId + "::"; + var end = docId + "::~"; + var index5 = seqStore.index("_doc_id_rev"); + var range = IDBKeyRange.bound(start, end, false, false); + var seqCursor = index5.openCursor(range); + seqCursor.onsuccess = function(e2) { + seqCursor = e2.target.result; + if (!seqCursor) { + docStore.delete(cursor2.primaryKey); + cursor2.continue(); + } else { + var data = seqCursor.value; + if (data._doc_id_rev === docIdRev) { + localStore.put(data); + } + seqStore.delete(seqCursor.primaryKey); + seqCursor.continue(); + } + }; + } else { + cursor2.continue(); + } + } else if (cb) { + cb(); + } + }; + } + function addAttachAndSeqStore(db) { + var attAndSeqStore = db.createObjectStore( + ATTACH_AND_SEQ_STORE, + { autoIncrement: true } + ); + attAndSeqStore.createIndex("seq", "seq"); + attAndSeqStore.createIndex("digestSeq", "digestSeq", { unique: true }); + } + function migrateAttsAndSeqs(txn, callback2) { + var seqStore = txn.objectStore(BY_SEQ_STORE); + var attStore = txn.objectStore(ATTACH_STORE); + var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + var req2 = attStore.count(); + req2.onsuccess = function(e2) { + var count = e2.target.result; + if (!count) { + return callback2(); + } + seqStore.openCursor().onsuccess = function(e3) { + var cursor = e3.target.result; + if (!cursor) { + return callback2(); + } + var doc = cursor.value; + var seq = cursor.primaryKey; + var atts = Object.keys(doc._attachments || {}); + var digestMap = {}; + for (var j = 0; j < atts.length; j++) { + var att = doc._attachments[atts[j]]; + digestMap[att.digest] = true; + } + var digests = Object.keys(digestMap); + for (j = 0; j < digests.length; j++) { + var digest = digests[j]; + attAndSeqStore.put({ + seq, + digestSeq: digest + "::" + seq + }); + } + cursor.continue(); + }; + }; + } + function migrateMetadata(txn) { + function decodeMetadataCompat(storedObject) { + if (!storedObject.data) { + storedObject.deleted = storedObject.deletedOrLocal === "1"; + return storedObject; + } + return decodeMetadata(storedObject); + } + var bySeqStore = txn.objectStore(BY_SEQ_STORE); + var docStore = txn.objectStore(DOC_STORE); + var cursor = docStore.openCursor(); + cursor.onsuccess = function(e2) { + var cursor2 = e2.target.result; + if (!cursor2) { + return; + } + var metadata = decodeMetadataCompat(cursor2.value); + metadata.winningRev = metadata.winningRev || winningRev(metadata); + function fetchMetadataSeq() { + var start = metadata.id + "::"; + var end = metadata.id + "::\uFFFF"; + var req2 = bySeqStore.index("_doc_id_rev").openCursor( + IDBKeyRange.bound(start, end) + ); + var metadataSeq = 0; + req2.onsuccess = function(e3) { + var cursor3 = e3.target.result; + if (!cursor3) { + metadata.seq = metadataSeq; + return onGetMetadataSeq(); + } + var seq = cursor3.primaryKey; + if (seq > metadataSeq) { + metadataSeq = seq; + } + cursor3.continue(); + }; + } + function onGetMetadataSeq() { + var metadataToStore = encodeMetadata( + metadata, + metadata.winningRev, + metadata.deleted + ); + var req2 = docStore.put(metadataToStore); + req2.onsuccess = function() { + cursor2.continue(); + }; + } + if (metadata.seq) { + return onGetMetadataSeq(); + } + fetchMetadataSeq(); + }; + } + api._remote = false; + api.type = function() { + return "idb"; + }; + api._id = toPromise(function(callback2) { + callback2(null, api._meta.instanceId); + }); + api._bulkDocs = function idb_bulkDocs(req2, reqOpts, callback2) { + idbBulkDocs(opts, req2, reqOpts, api, idb, enrichCallbackError(callback2)); + }; + api._get = function idb_get(id, opts2, callback2) { + var doc; + var metadata; + var err; + var txn = opts2.ctx; + if (!txn) { + var txnResult = openTransactionSafely( + idb, + [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], + "readonly" + ); + if (txnResult.error) { + return callback2(txnResult.error); + } + txn = txnResult.txn; + } + function finish() { + callback2(err, { doc, metadata, ctx: txn }); + } + txn.objectStore(DOC_STORE).get(id).onsuccess = function(e2) { + metadata = decodeMetadata(e2.target.result); + if (!metadata) { + err = createError(MISSING_DOC, "missing"); + return finish(); + } + var rev2; + if (!opts2.rev) { + rev2 = metadata.winningRev; + var deleted = isDeleted(metadata); + if (deleted) { + err = createError(MISSING_DOC, "deleted"); + return finish(); + } + } else { + rev2 = opts2.latest ? latest(opts2.rev, metadata) : opts2.rev; + } + var objectStore = txn.objectStore(BY_SEQ_STORE); + var key = metadata.id + "::" + rev2; + objectStore.index("_doc_id_rev").get(key).onsuccess = function(e3) { + doc = e3.target.result; + if (doc) { + doc = decodeDoc(doc); + } + if (!doc) { + err = createError(MISSING_DOC, "missing"); + return finish(); + } + finish(); + }; + }; + }; + api._getAttachment = function(docId, attachId, attachment, opts2, callback2) { + var txn; + if (opts2.ctx) { + txn = opts2.ctx; + } else { + var txnResult = openTransactionSafely( + idb, + [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], + "readonly" + ); + if (txnResult.error) { + return callback2(txnResult.error); + } + txn = txnResult.txn; + } + var digest = attachment.digest; + var type = attachment.content_type; + txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function(e2) { + var body = e2.target.result.body; + readBlobData(body, type, opts2.binary, function(blobData) { + callback2(null, blobData); + }); + }; + }; + api._info = function idb_info(callback2) { + var updateSeq; + var docCount; + var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], "readonly"); + if (txnResult.error) { + return callback2(txnResult.error); + } + var txn = txnResult.txn; + txn.objectStore(META_STORE).get(META_STORE).onsuccess = function(e2) { + docCount = e2.target.result.docCount; + }; + txn.objectStore(BY_SEQ_STORE).openCursor(null, "prev").onsuccess = function(e2) { + var cursor = e2.target.result; + updateSeq = cursor ? cursor.key : 0; + }; + txn.oncomplete = function() { + callback2(null, { + doc_count: docCount, + update_seq: updateSeq, + idb_attachment_format: api._meta.blobSupport ? "binary" : "base64" + }); + }; + }; + api._allDocs = function idb_allDocs(opts2, callback2) { + idbAllDocs(opts2, idb, enrichCallbackError(callback2)); + }; + api._changes = function idbChanges2(opts2) { + return changes(opts2, api, dbName, idb); + }; + api._close = function(callback2) { + idb.close(); + cachedDBs.delete(dbName); + callback2(); + }; + api._getRevisionTree = function(docId, callback2) { + var txnResult = openTransactionSafely(idb, [DOC_STORE], "readonly"); + if (txnResult.error) { + return callback2(txnResult.error); + } + var txn = txnResult.txn; + var req2 = txn.objectStore(DOC_STORE).get(docId); + req2.onsuccess = function(event) { + var doc = decodeMetadata(event.target.result); + if (!doc) { + callback2(createError(MISSING_DOC)); + } else { + callback2(null, doc.rev_tree); + } + }; + }; + api._doCompaction = function(docId, revs, callback2) { + var stores = [ + DOC_STORE, + BY_SEQ_STORE, + ATTACH_STORE, + ATTACH_AND_SEQ_STORE + ]; + var txnResult = openTransactionSafely(idb, stores, "readwrite"); + if (txnResult.error) { + return callback2(txnResult.error); + } + var txn = txnResult.txn; + var docStore = txn.objectStore(DOC_STORE); + docStore.get(docId).onsuccess = function(event) { + var metadata = decodeMetadata(event.target.result); + traverseRevTree(metadata.rev_tree, function(isLeaf, pos, revHash, ctx, opts2) { + var rev2 = pos + "-" + revHash; + if (revs.indexOf(rev2) !== -1) { + opts2.status = "missing"; + } + }); + compactRevs(revs, docId, txn); + var winningRev$$1 = metadata.winningRev; + var deleted = metadata.deleted; + txn.objectStore(DOC_STORE).put( + encodeMetadata(metadata, winningRev$$1, deleted) + ); + }; + txn.onabort = idbError(callback2); + txn.oncomplete = function() { + callback2(); + }; + }; + api._getLocal = function(id, callback2) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], "readonly"); + if (txnResult.error) { + return callback2(txnResult.error); + } + var tx = txnResult.txn; + var req2 = tx.objectStore(LOCAL_STORE).get(id); + req2.onerror = idbError(callback2); + req2.onsuccess = function(e2) { + var doc = e2.target.result; + if (!doc) { + callback2(createError(MISSING_DOC)); + } else { + delete doc["_doc_id_rev"]; + callback2(null, doc); + } + }; + }; + api._putLocal = function(doc, opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + delete doc._revisions; + var oldRev = doc._rev; + var id = doc._id; + if (!oldRev) { + doc._rev = "0-1"; + } else { + doc._rev = "0-" + (parseInt(oldRev.split("-")[1], 10) + 1); + } + var tx = opts2.ctx; + var ret; + if (!tx) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], "readwrite"); + if (txnResult.error) { + return callback2(txnResult.error); + } + tx = txnResult.txn; + tx.onerror = idbError(callback2); + tx.oncomplete = function() { + if (ret) { + callback2(null, ret); + } + }; + } + var oStore = tx.objectStore(LOCAL_STORE); + var req2; + if (oldRev) { + req2 = oStore.get(id); + req2.onsuccess = function(e2) { + var oldDoc = e2.target.result; + if (!oldDoc || oldDoc._rev !== oldRev) { + callback2(createError(REV_CONFLICT)); + } else { + var req3 = oStore.put(doc); + req3.onsuccess = function() { + ret = { ok: true, id: doc._id, rev: doc._rev }; + if (opts2.ctx) { + callback2(null, ret); + } + }; + } + }; + } else { + req2 = oStore.add(doc); + req2.onerror = function(e2) { + callback2(createError(REV_CONFLICT)); + e2.preventDefault(); + e2.stopPropagation(); + }; + req2.onsuccess = function() { + ret = { ok: true, id: doc._id, rev: doc._rev }; + if (opts2.ctx) { + callback2(null, ret); + } + }; + } + }; + api._removeLocal = function(doc, opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + var tx = opts2.ctx; + if (!tx) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], "readwrite"); + if (txnResult.error) { + return callback2(txnResult.error); + } + tx = txnResult.txn; + tx.oncomplete = function() { + if (ret) { + callback2(null, ret); + } + }; + } + var ret; + var id = doc._id; + var oStore = tx.objectStore(LOCAL_STORE); + var req2 = oStore.get(id); + req2.onerror = idbError(callback2); + req2.onsuccess = function(e2) { + var oldDoc = e2.target.result; + if (!oldDoc || oldDoc._rev !== doc._rev) { + callback2(createError(MISSING_DOC)); + } else { + oStore.delete(id); + ret = { ok: true, id, rev: "0-0" }; + if (opts2.ctx) { + callback2(null, ret); + } + } + }; + }; + api._destroy = function(opts2, callback2) { + changesHandler$1.removeAllListeners(dbName); + var openReq = openReqList.get(dbName); + if (openReq && openReq.result) { + openReq.result.close(); + cachedDBs.delete(dbName); + } + var req2 = indexedDB.deleteDatabase(dbName); + req2.onsuccess = function() { + openReqList.delete(dbName); + if (hasLocalStorage() && dbName in localStorage) { + delete localStorage[dbName]; + } + callback2(null, { "ok": true }); + }; + req2.onerror = idbError(callback2); + }; + var cached = cachedDBs.get(dbName); + if (cached) { + idb = cached.idb; + api._meta = cached.global; + return (0, import_immediate.default)(function() { + callback(null, api); + }); + } + var req = indexedDB.open(dbName, ADAPTER_VERSION); + openReqList.set(dbName, req); + req.onupgradeneeded = function(e2) { + var db = e2.target.result; + if (e2.oldVersion < 1) { + return createSchema(db); + } + var txn = e2.currentTarget.transaction; + if (e2.oldVersion < 3) { + createLocalStoreSchema(db); + } + if (e2.oldVersion < 4) { + addAttachAndSeqStore(db); + } + var migrations = [ + addDeletedOrLocalIndex, + migrateLocalStore, + migrateAttsAndSeqs, + migrateMetadata + ]; + var i = e2.oldVersion; + function next() { + var migration = migrations[i - 1]; + i++; + if (migration) { + migration(txn, next); + } + } + next(); + }; + req.onsuccess = function(e2) { + idb = e2.target.result; + idb.onversionchange = function() { + idb.close(); + cachedDBs.delete(dbName); + }; + idb.onabort = function(e3) { + guardedConsole("error", "Database has a global failure", e3.target.error); + idbGlobalFailureError = e3.target.error; + idb.close(); + cachedDBs.delete(dbName); + }; + var txn = idb.transaction([ + META_STORE, + DETECT_BLOB_SUPPORT_STORE, + DOC_STORE + ], "readwrite"); + var storedMetaDoc = false; + var metaDoc; + var docCount; + var blobSupport; + var instanceId; + function completeSetup() { + if (typeof blobSupport === "undefined" || !storedMetaDoc) { + return; + } + api._meta = { + name: dbName, + instanceId, + blobSupport + }; + cachedDBs.set(dbName, { + idb, + global: api._meta + }); + callback(null, api); + } + function storeMetaDocIfReady() { + if (typeof docCount === "undefined" || typeof metaDoc === "undefined") { + return; + } + var instanceKey = dbName + "_id"; + if (instanceKey in metaDoc) { + instanceId = metaDoc[instanceKey]; + } else { + metaDoc[instanceKey] = instanceId = uuid(); + } + metaDoc.docCount = docCount; + txn.objectStore(META_STORE).put(metaDoc); + } + txn.objectStore(META_STORE).get(META_STORE).onsuccess = function(e3) { + metaDoc = e3.target.result || { id: META_STORE }; + storeMetaDocIfReady(); + }; + countDocs(txn, function(count) { + docCount = count; + storeMetaDocIfReady(); + }); + if (!blobSupportPromise) { + blobSupportPromise = checkBlobSupport(txn); + } + blobSupportPromise.then(function(val) { + blobSupport = val; + completeSetup(); + }); + txn.oncomplete = function() { + storedMetaDoc = true; + completeSetup(); + }; + txn.onabort = idbError(callback); + }; + req.onerror = function(e2) { + var msg = e2.target.error && e2.target.error.message; + if (!msg) { + msg = "Failed to open indexedDB, are you in private browsing mode?"; + } else if (msg.indexOf("stored database is a higher version") !== -1) { + msg = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter'); + } + guardedConsole("error", msg); + callback(createError(IDB_ERROR, msg)); + }; +} +IdbPouch.valid = function() { + try { + return typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined"; + } catch (e2) { + return false; + } +}; +function index(PouchDB2) { + PouchDB2.adapter("idb", IdbPouch, true); +} +var index_es_default2 = index; + +// node_modules/pouchdb-adapter-indexeddb/lib/index.es.js +var IDB_NULL = Number.MIN_SAFE_INTEGER; +var IDB_FALSE = Number.MIN_SAFE_INTEGER + 1; +var IDB_TRUE = Number.MIN_SAFE_INTEGER + 2; +var TEST_KEY_INVALID = /^[^a-zA-Z_$]|[^a-zA-Z0-9_$]+/; +var TEST_PATH_INVALID = /\\.|(^|\.)[^a-zA-Z_$]|[^a-zA-Z0-9_$.]+/; +function needsSanitise(name, isPath) { + if (isPath) { + return TEST_PATH_INVALID.test(name); + } else { + return TEST_KEY_INVALID.test(name); + } +} +var KEY_INVALID = new RegExp(TEST_KEY_INVALID.source, "g"); +var PATH_INVALID = new RegExp(TEST_PATH_INVALID.source, "g"); +var SLASH = "\\".charCodeAt(0); +var IS_DOT = ".".charCodeAt(0); +function sanitise(name, isPath) { + var correctCharacters = function(match2) { + var good = ""; + for (var i = 0; i < match2.length; i++) { + var code = match2.charCodeAt(i); + if (code === IS_DOT && isPath && i === 0) { + good += "."; + } else if (code === SLASH && isPath) { + continue; + } else { + good += "_c" + code + "_"; + } + } + return good; + }; + if (isPath) { + return name.replace(PATH_INVALID, correctCharacters); + } else { + return name.replace(KEY_INVALID, correctCharacters); + } +} +function needsRewrite(data) { + for (var key of Object.keys(data)) { + if (needsSanitise(key)) { + return true; + } else if (data[key] === null || typeof data[key] === "boolean") { + return true; + } else if (typeof data[key] === "object") { + return needsRewrite(data[key]); + } + } +} +function rewrite(data) { + if (!needsRewrite(data)) { + return false; + } + var isArray2 = Array.isArray(data); + var clone2 = isArray2 ? [] : {}; + Object.keys(data).forEach(function(key) { + var safeKey = isArray2 ? key : sanitise(key); + if (data[key] === null) { + clone2[safeKey] = IDB_NULL; + } else if (typeof data[key] === "boolean") { + clone2[safeKey] = data[key] ? IDB_TRUE : IDB_FALSE; + } else if (typeof data[key] === "object") { + clone2[safeKey] = rewrite(data[key]); + } else { + clone2[safeKey] = data[key]; + } + }); + return clone2; +} +var DOC_STORE2 = "docs"; +var META_STORE2 = "meta"; +function idbError2(callback) { + return function(evt) { + var message = "unknown_error"; + if (evt.target && evt.target.error) { + message = evt.target.error.name || evt.target.error.message; + } + callback(createError(IDB_ERROR, message, evt.type)); + }; +} +function processAttachment(name, src, doc, isBinary) { + delete doc._attachments[name].stub; + if (isBinary) { + doc._attachments[name].data = src.attachments[doc._attachments[name].digest].data; + return Promise.resolve(); + } + return new Promise(function(resolve) { + var data = src.attachments[doc._attachments[name].digest].data; + readAsBinaryString(data, function(binString) { + doc._attachments[name].data = thisBtoa(binString); + delete doc._attachments[name].length; + resolve(); + }); + }); +} +function rawIndexFields(ddoc, viewName) { + var fields = ddoc.views[viewName].options && ddoc.views[viewName].options.def && ddoc.views[viewName].options.def.fields || []; + return fields.map(function(field) { + if (typeof field === "string") { + return field; + } else { + return Object.keys(field)[0]; + } + }); +} +function isPartialFilterView(ddoc, viewName) { + return viewName in ddoc.views && ddoc.views[viewName].options && ddoc.views[viewName].options.def && ddoc.views[viewName].options.def.partial_filter_selector; +} +function naturalIndexName(fields) { + return "_find_idx/" + fields.join("/"); +} +function correctIndexFields(fields) { + return ["deleted"].concat( + fields.map(function(field) { + if (["_id", "_rev", "_deleted", "_attachments"].includes(field)) { + return field.substr(1); + } else { + return "data." + sanitise(field, true); + } + }) + ); +} +var POUCHDB_IDB_VERSION = 1; +var versionMultiplier = Math.pow(10, 13); +function createIdbVersion() { + return versionMultiplier * POUCHDB_IDB_VERSION + new Date().getTime(); +} +function getPouchDbVersion(version2) { + return Math.floor(version2 / versionMultiplier); +} +function maintainNativeIndexes(openReq, reject) { + var docStore = openReq.transaction.objectStore(DOC_STORE2); + var ddocsReq = docStore.getAll(IDBKeyRange.bound("_design/", "_design/\uFFFF")); + ddocsReq.onsuccess = function(e2) { + var results = e2.target.result; + var existingIndexNames = Array.from(docStore.indexNames); + var expectedIndexes = results.filter(function(row) { + return row.deleted === 0 && row.revs[row.rev].data.views; + }).map(function(row) { + return row.revs[row.rev].data; + }).reduce(function(indexes, ddoc) { + return Object.keys(ddoc.views).reduce(function(acc, viewName) { + var fields = rawIndexFields(ddoc, viewName); + if (fields && fields.length > 0) { + acc[naturalIndexName(fields)] = correctIndexFields(fields); + } + return acc; + }, indexes); + }, {}); + var expectedIndexNames = Object.keys(expectedIndexes); + var systemIndexNames = ["seq"]; + existingIndexNames.forEach(function(index5) { + if (systemIndexNames.indexOf(index5) === -1 && expectedIndexNames.indexOf(index5) === -1) { + docStore.deleteIndex(index5); + } + }); + var newIndexNames = expectedIndexNames.filter(function(ei) { + return existingIndexNames.indexOf(ei) === -1; + }); + try { + newIndexNames.forEach(function(indexName) { + docStore.createIndex(indexName, expectedIndexes[indexName]); + }); + } catch (err) { + reject(err); + } + }; +} +function upgradePouchDbSchema(db, pouchdbVersion) { + if (pouchdbVersion < 1) { + var docStore = db.createObjectStore(DOC_STORE2, { keyPath: "id" }); + docStore.createIndex("seq", "seq", { unique: true }); + db.createObjectStore(META_STORE2, { keyPath: "id" }); + } +} +function openDatabase(openDatabases2, api, opts, resolve, reject) { + var openReq = opts.versionchanged ? indexedDB.open(opts.name) : indexedDB.open(opts.name, createIdbVersion()); + openReq.onupgradeneeded = function(e2) { + if (e2.oldVersion > 0 && e2.oldVersion < versionMultiplier) { + throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB'); + } else if (e2.oldVersion === 0 && e2.newVersion < versionMultiplier) { + indexedDB.deleteDatabase(opts.name); + throw new Error("Database was deleted while open"); + } + var db = e2.target.result; + var pouchdbVersion = getPouchDbVersion(e2.oldVersion); + upgradePouchDbSchema(db, pouchdbVersion); + maintainNativeIndexes(openReq, reject); + }; + openReq.onblocked = function(e2) { + console.error("onblocked, this should never happen", e2); + }; + openReq.onsuccess = function(e2) { + var idb = e2.target.result; + idb.onabort = function(e3) { + console.error("Database has a global failure", e3.target.error); + delete openDatabases2[opts.name]; + idb.close(); + }; + idb.onversionchange = function() { + console.log("Database was made stale, closing handle"); + openDatabases2[opts.name].versionchanged = true; + idb.close(); + }; + idb.onclose = function() { + console.log("Database was made stale, closing handle"); + if (opts.name in openDatabases2) { + openDatabases2[opts.name].versionchanged = true; + } + }; + var metadata = { id: META_STORE2 }; + var txn = idb.transaction([META_STORE2], "readwrite"); + txn.oncomplete = function() { + resolve({ idb, metadata }); + }; + var metaStore = txn.objectStore(META_STORE2); + metaStore.get(META_STORE2).onsuccess = function(e3) { + metadata = e3.target.result || metadata; + var changed = false; + if (!("doc_count" in metadata)) { + changed = true; + metadata.doc_count = 0; + } + if (!("seq" in metadata)) { + changed = true; + metadata.seq = 0; + } + if (!("db_uuid" in metadata)) { + changed = true; + metadata.db_uuid = uuid(); + } + if (changed) { + metaStore.put(metadata); + } + }; + }; + openReq.onerror = function(e2) { + reject(e2.target.error); + }; +} +function setup(openDatabases2, api, opts) { + if (!openDatabases2[opts.name] || openDatabases2[opts.name].versionchanged) { + opts.versionchanged = openDatabases2[opts.name] && openDatabases2[opts.name].versionchanged; + openDatabases2[opts.name] = new Promise(function(resolve, reject) { + openDatabase(openDatabases2, api, opts, resolve, reject); + }); + } + return openDatabases2[opts.name]; +} +function info(metadata, callback) { + callback(null, { + doc_count: metadata.doc_count, + update_seq: metadata.seq + }); +} +function get(txn, id, opts, callback) { + if (txn.error) { + return callback(txn.error); + } + txn.txn.objectStore(DOC_STORE2).get(id).onsuccess = function(e2) { + var doc = e2.target.result; + var rev2; + if (!opts.rev) { + rev2 = doc && doc.rev; + } else { + rev2 = opts.latest ? latest(opts.rev, doc) : opts.rev; + } + if (!doc || doc.deleted && !opts.rev || !(rev2 in doc.revs)) { + callback(createError(MISSING_DOC, "missing")); + return; + } + var result = doc.revs[rev2].data; + result._id = doc.id; + result._rev = rev2; + callback(null, { + doc: result, + metadata: doc, + ctx: txn + }); + }; +} +function parseAttachment(attachment, opts, cb) { + if (opts.binary) { + return cb(null, attachment); + } else { + readAsBinaryString(attachment, function(binString) { + cb(null, thisBtoa(binString)); + }); + } +} +function getAttachment(txn, docId, attachId, _, opts, cb) { + if (txn.error) { + return cb(txn.error); + } + var attachment; + txn.txn.objectStore(DOC_STORE2).get(docId).onsuccess = function(e2) { + var doc = e2.target.result; + var rev2 = doc.revs[opts.rev || doc.rev].data; + var digest = rev2._attachments[attachId].digest; + attachment = doc.attachments[digest].data; + }; + txn.txn.oncomplete = function() { + parseAttachment(attachment, opts, cb); + }; + txn.txn.onabort = cb; +} +function bulkDocs(api, req, opts, metadata, dbOpts, idbChanges2, callback) { + var txn; + var error; + var results = []; + var docs = []; + var lastWriteIndex; + var revsLimit = dbOpts.revs_limit || 1e3; + var rewriteEnabled = dbOpts.name.indexOf("-mrview-") === -1; + const autoCompaction = dbOpts.auto_compaction; + function docsRevsLimit(doc) { + return /^_local/.test(doc.id) ? 1 : revsLimit; + } + function rootIsMissing2(doc) { + return doc.rev_tree[0].ids[1].status === "missing"; + } + function parseBase642(data) { + try { + return atob(data); + } catch (e2) { + return { + error: createError(BAD_ARG, "Attachment is not a valid base64 string") + }; + } + } + function fetchExistingDocs(txn2, docs2) { + var fetched = 0; + var oldDocs = {}; + function readDone(e2) { + if (e2.target.result) { + oldDocs[e2.target.result.id] = e2.target.result; + } + if (++fetched === docs2.length) { + processDocs2(txn2, docs2, oldDocs); + } + } + docs2.forEach(function(doc) { + txn2.objectStore(DOC_STORE2).get(doc.id).onsuccess = readDone; + }); + } + function revHasAttachment(doc, rev2, digest) { + return doc.revs[rev2] && doc.revs[rev2].data._attachments && Object.values(doc.revs[rev2].data._attachments).find(function(att) { + return att.digest === digest; + }); + } + function processDocs2(txn2, docs2, oldDocs) { + docs2.forEach(function(doc, i2) { + var newDoc; + if ("was_delete" in opts && !Object.prototype.hasOwnProperty.call(oldDocs, doc.id)) { + newDoc = createError(MISSING_DOC, "deleted"); + } else if (opts.new_edits && !Object.prototype.hasOwnProperty.call(oldDocs, doc.id) && rootIsMissing2(doc)) { + newDoc = createError(REV_CONFLICT); + } else if (Object.prototype.hasOwnProperty.call(oldDocs, doc.id)) { + newDoc = update2(txn2, doc, oldDocs[doc.id]); + if (newDoc == false) { + return; + } + } else { + var merged = merge([], doc.rev_tree[0], docsRevsLimit(doc)); + doc.rev_tree = merged.tree; + doc.stemmedRevs = merged.stemmedRevs; + newDoc = doc; + newDoc.isNewDoc = true; + newDoc.wasDeleted = doc.revs[doc.rev].deleted ? 1 : 0; + } + if (newDoc.error) { + results[i2] = newDoc; + } else { + oldDocs[newDoc.id] = newDoc; + lastWriteIndex = i2; + write(txn2, newDoc, i2); + } + }); + } + function convertDocFormat(doc) { + var newDoc = { + id: doc.metadata.id, + rev: doc.metadata.rev, + rev_tree: doc.metadata.rev_tree, + revs: doc.metadata.revs || {} + }; + newDoc.revs[newDoc.rev] = { + data: doc.data, + deleted: doc.metadata.deleted + }; + return newDoc; + } + function update2(txn2, doc, oldDoc) { + if (doc.rev in oldDoc.revs && !opts.new_edits) { + return false; + } + var isRoot = /^1-/.test(doc.rev); + if (oldDoc.deleted && !doc.deleted && opts.new_edits && isRoot) { + var tmp = doc.revs[doc.rev].data; + tmp._rev = oldDoc.rev; + tmp._id = oldDoc.id; + doc = convertDocFormat(parseDoc(tmp, opts.new_edits, dbOpts)); + } + var merged = merge(oldDoc.rev_tree, doc.rev_tree[0], docsRevsLimit(doc)); + doc.stemmedRevs = merged.stemmedRevs; + doc.rev_tree = merged.tree; + var revs = oldDoc.revs; + revs[doc.rev] = doc.revs[doc.rev]; + doc.revs = revs; + doc.attachments = oldDoc.attachments; + var inConflict = opts.new_edits && (oldDoc.deleted && doc.deleted || !oldDoc.deleted && merged.conflicts !== "new_leaf" || oldDoc.deleted && !doc.deleted && merged.conflicts === "new_branch" || oldDoc.rev === doc.rev); + if (inConflict) { + return createError(REV_CONFLICT); + } + doc.wasDeleted = oldDoc.deleted; + return doc; + } + function write(txn2, doc, i2) { + var winningRev$$1 = winningRev(doc); + var writtenRev = doc.rev; + var isLocal = /^_local/.test(doc.id); + var theDoc = doc.revs[winningRev$$1].data; + const isNewDoc = doc.isNewDoc; + if (rewriteEnabled) { + var result2 = rewrite(theDoc); + if (result2) { + doc.data = result2; + delete doc.data._attachments; + } else { + doc.data = theDoc; + } + } else { + doc.data = theDoc; + } + doc.rev = winningRev$$1; + doc.deleted = doc.revs[winningRev$$1].deleted ? 1 : 0; + if (!isLocal) { + doc.seq = ++metadata.seq; + var delta = 0; + if (doc.isNewDoc) { + delta = doc.deleted ? 0 : 1; + } else if (doc.wasDeleted !== doc.deleted) { + delta = doc.deleted ? -1 : 1; + } + metadata.doc_count += delta; + } + delete doc.isNewDoc; + delete doc.wasDeleted; + let revsToDelete = doc.stemmedRevs || []; + if (autoCompaction && !isNewDoc) { + const result3 = compactTree(doc); + if (result3.length) { + revsToDelete = revsToDelete.concat(result3); + } + } + if (revsToDelete.length) { + revsToDelete.forEach(function(rev2) { + delete doc.revs[rev2]; + }); + } + delete doc.stemmedRevs; + if (!("attachments" in doc)) { + doc.attachments = {}; + } + if (theDoc._attachments) { + for (var k in theDoc._attachments) { + var attachment = theDoc._attachments[k]; + if (attachment.stub) { + if (!(attachment.digest in doc.attachments)) { + error = createError(MISSING_STUB); + txn2.abort(); + return; + } + if (revHasAttachment(doc, writtenRev, attachment.digest)) { + doc.attachments[attachment.digest].revs[writtenRev] = true; + } + } else { + doc.attachments[attachment.digest] = attachment; + doc.attachments[attachment.digest].revs = {}; + doc.attachments[attachment.digest].revs[writtenRev] = true; + theDoc._attachments[k] = { + stub: true, + digest: attachment.digest, + content_type: attachment.content_type, + length: attachment.length, + revpos: parseInt(writtenRev, 10) + }; + } + } + } + if (isLocal && doc.deleted) { + txn2.objectStore(DOC_STORE2).delete(doc.id).onsuccess = function() { + results[i2] = { + ok: true, + id: doc.id, + rev: "0-0" + }; + }; + updateSeq(i2); + return; + } + txn2.objectStore(DOC_STORE2).put(doc).onsuccess = function() { + results[i2] = { + ok: true, + id: doc.id, + rev: writtenRev + }; + updateSeq(i2); + }; + } + function updateSeq(i2) { + if (i2 === lastWriteIndex) { + txn.objectStore(META_STORE2).put(metadata); + } + } + function preProcessAttachment(attachment) { + if (attachment.stub) { + return Promise.resolve(attachment); + } + var binData; + if (typeof attachment.data === "string") { + binData = parseBase642(attachment.data); + if (binData.error) { + return Promise.reject(binData.error); + } + attachment.data = binStringToBluffer(binData, attachment.content_type); + } else { + binData = attachment.data; + } + return new Promise(function(resolve) { + binaryMd5(binData, function(result2) { + attachment.digest = "md5-" + result2; + attachment.length = binData.size || binData.length || 0; + resolve(attachment); + }); + }); + } + function preProcessAttachments() { + var promises = docs.map(function(doc) { + var data = doc.revs[doc.rev].data; + if (!data._attachments) { + return Promise.resolve(data); + } + var attachments = Object.keys(data._attachments).map(function(k) { + data._attachments[k].name = k; + return preProcessAttachment(data._attachments[k]); + }); + return Promise.all(attachments).then(function(newAttachments) { + var processed = {}; + newAttachments.forEach(function(attachment) { + processed[attachment.name] = attachment; + delete attachment.name; + }); + data._attachments = processed; + return data; + }); + }); + return Promise.all(promises); + } + for (var i = 0, len = req.docs.length; i < len; i++) { + var result; + try { + result = parseDoc(req.docs[i], opts.new_edits, dbOpts); + } catch (err) { + result = err; + } + if (result.error) { + return callback(result); + } + docs.push(convertDocFormat(result)); + } + preProcessAttachments().then(function() { + api._openTransactionSafely([DOC_STORE2, META_STORE2], "readwrite", function(err, _txn) { + if (err) { + return callback(err); + } + txn = _txn; + txn.onabort = function() { + callback(error || createError(UNKNOWN_ERROR, "transaction was aborted")); + }; + txn.ontimeout = idbError2(callback); + txn.oncomplete = function() { + idbChanges2.notify(dbOpts.name); + callback(null, results); + }; + fetchExistingDocs(txn, docs); + }); + }).catch(function(err) { + callback(err); + }); +} +function allDocsKeys2(keys2, docStore, allDocsInner) { + var valuesBatch = new Array(keys2.length); + var count = 0; + keys2.forEach(function(key, index5) { + docStore.get(key).onsuccess = function(event) { + if (event.target.result) { + valuesBatch[index5] = event.target.result; + } else { + valuesBatch[index5] = { key, error: "not_found" }; + } + count++; + if (count === keys2.length) { + valuesBatch.forEach(function(doc) { + allDocsInner(doc); + }); + } + }; + }); +} +function createKeyRange2(start, end, inclusiveEnd, key, descending) { + try { + if (start && end) { + if (descending) { + return IDBKeyRange.bound(end, start, !inclusiveEnd, false); + } else { + return IDBKeyRange.bound(start, end, false, !inclusiveEnd); + } + } else if (start) { + if (descending) { + return IDBKeyRange.upperBound(start); + } else { + return IDBKeyRange.lowerBound(start); + } + } else if (end) { + if (descending) { + return IDBKeyRange.lowerBound(end, !inclusiveEnd); + } else { + return IDBKeyRange.upperBound(end, !inclusiveEnd); + } + } else if (key) { + return IDBKeyRange.only(key); + } + } catch (e2) { + return { error: e2 }; + } + return null; +} +function handleKeyRangeError(opts, metadata, err, callback) { + if (err.name === "DataError" && err.code === 0) { + var returnVal = { + total_rows: metadata.doc_count, + offset: opts.skip, + rows: [] + }; + if (opts.update_seq) { + returnVal.update_seq = metadata.seq; + } + return callback(null, returnVal); + } + callback(createError(IDB_ERROR, err.name, err.message)); +} +function allDocs(txn, metadata, opts, callback) { + if (txn.error) { + return callback(txn.error); + } + if (opts.limit === 0) { + var returnVal = { + total_rows: metadata.doc_count, + offset: opts.skip, + rows: [] + }; + if (opts.update_seq) { + returnVal.update_seq = metadata.seq; + } + return callback(null, returnVal); + } + var results = []; + var processing = []; + var start = "startkey" in opts ? opts.startkey : false; + var end = "endkey" in opts ? opts.endkey : false; + var key = "key" in opts ? opts.key : false; + var keys2 = "keys" in opts ? opts.keys : false; + var skip = opts.skip || 0; + var limit = typeof opts.limit === "number" ? opts.limit : -1; + var inclusiveEnd = opts.inclusive_end !== false; + var descending = "descending" in opts && opts.descending ? "prev" : null; + var keyRange; + if (!keys2) { + keyRange = createKeyRange2(start, end, inclusiveEnd, key, descending); + if (keyRange && keyRange.error) { + return handleKeyRangeError(opts, metadata, keyRange.error, callback); + } + } + var docStore = txn.txn.objectStore(DOC_STORE2); + txn.txn.oncomplete = onTxnComplete; + if (keys2) { + return allDocsKeys2(opts.keys, docStore, allDocsInner); + } + function include_doc(row, doc) { + var docData = doc.revs[doc.rev].data; + row.doc = docData; + row.doc._id = doc.id; + row.doc._rev = doc.rev; + if (opts.conflicts) { + var conflicts = collectConflicts(doc); + if (conflicts.length) { + row.doc._conflicts = conflicts; + } + } + if (opts.attachments && docData._attachments) { + for (var name in docData._attachments) { + processing.push(processAttachment(name, doc, row.doc, opts.binary)); + } + } + } + function allDocsInner(doc) { + if (doc.error && keys2) { + results.push(doc); + return true; + } + var row = { + id: doc.id, + key: doc.id, + value: { + rev: doc.rev + } + }; + var deleted = doc.deleted; + if (deleted) { + if (keys2) { + results.push(row); + row.value.deleted = true; + row.doc = null; + } + } else if (skip-- <= 0) { + results.push(row); + if (opts.include_docs) { + include_doc(row, doc); + } + if (--limit === 0) { + return false; + } + } + return true; + } + function onTxnComplete() { + Promise.all(processing).then(function() { + var returnVal2 = { + total_rows: metadata.doc_count, + offset: 0, + rows: results + }; + if (opts.update_seq) { + returnVal2.update_seq = metadata.seq; + } + callback(null, returnVal2); + }); + } + var cursor = descending ? docStore.openCursor(keyRange, descending) : docStore.openCursor(keyRange); + cursor.onsuccess = function(e2) { + var doc = e2.target.result && e2.target.result.value; + if (!doc) { + return; + } + if (/^_local/.test(doc.id)) { + return e2.target.result.continue(); + } + var continueCursor = allDocsInner(doc); + if (continueCursor) { + e2.target.result.continue(); + } + }; +} +function changes2(txn, idbChanges2, api, dbOpts, opts) { + if (txn.error) { + return opts.complete(txn.error); + } + if (opts.continuous) { + var id = dbOpts.name + ":" + uuid(); + idbChanges2.addListener(dbOpts.name, id, api, opts); + idbChanges2.notify(dbOpts.name); + return { + cancel: function() { + idbChanges2.removeListener(dbOpts.name, id); + } + }; + } + var limit = "limit" in opts ? opts.limit : -1; + if (limit === 0) { + limit = 1; + } + var store = txn.txn.objectStore(DOC_STORE2).index("seq"); + var filter2 = filterChange(opts); + var received = 0; + var lastSeq = opts.since || 0; + var results = []; + var processing = []; + function onReqSuccess(e2) { + if (!e2.target.result) { + return; + } + var cursor = e2.target.result; + var doc = cursor.value; + doc.data = doc.revs[doc.rev].data; + doc.data._id = doc.id; + doc.data._rev = doc.rev; + if (doc.deleted) { + doc.data._deleted = true; + } + if (opts.doc_ids && opts.doc_ids.indexOf(doc.id) === -1) { + return cursor.continue(); + } + var change = opts.processChange(doc.data, doc, opts); + change.seq = doc.seq; + lastSeq = doc.seq; + var filtered = filter2(change); + if (typeof filtered === "object") { + return opts.complete(filtered); + } + if (filtered) { + received++; + if (opts.return_docs) { + results.push(change); + } + if (opts.include_docs && opts.attachments && doc.data._attachments) { + var promises = []; + for (var name in doc.data._attachments) { + var p = processAttachment(name, doc, change.doc, opts.binary); + promises.push(p); + processing.push(p); + } + Promise.all(promises).then(function() { + opts.onChange(change); + }); + } else { + opts.onChange(change); + } + } + if (received !== limit) { + cursor.continue(); + } + } + function onTxnComplete() { + Promise.all(processing).then(function() { + opts.complete(null, { + results, + last_seq: lastSeq + }); + }); + } + var req; + if (opts.descending) { + req = store.openCursor(null, "prev"); + } else { + req = store.openCursor(IDBKeyRange.lowerBound(opts.since, true)); + } + txn.txn.oncomplete = onTxnComplete; + req.onsuccess = onReqSuccess; +} +function getRevisionTree(txn, id, callback) { + if (txn.error) { + return callback(txn.error); + } + var req = txn.txn.objectStore(DOC_STORE2).get(id); + req.onsuccess = function(e2) { + if (!e2.target.result) { + callback(createError(MISSING_DOC)); + } else { + callback(null, e2.target.result.rev_tree); + } + }; +} +function doCompaction(txn, id, revs, callback) { + if (txn.error) { + return callback(txn.error); + } + var docStore = txn.txn.objectStore(DOC_STORE2); + docStore.get(id).onsuccess = function(e2) { + var doc = e2.target.result; + traverseRevTree(doc.rev_tree, function(isLeaf, pos, revHash, ctx, opts) { + var rev2 = pos + "-" + revHash; + if (revs.indexOf(rev2) !== -1) { + opts.status = "missing"; + } + }); + var attachments = []; + revs.forEach(function(rev2) { + if (rev2 in doc.revs) { + if (doc.revs[rev2].data._attachments) { + for (var k in doc.revs[rev2].data._attachments) { + attachments.push(doc.revs[rev2].data._attachments[k].digest); + } + } + delete doc.revs[rev2]; + } + }); + attachments.forEach(function(digest) { + revs.forEach(function(rev2) { + delete doc.attachments[digest].revs[rev2]; + }); + if (!Object.keys(doc.attachments[digest].revs).length) { + delete doc.attachments[digest]; + } + }); + docStore.put(doc); + }; + txn.txn.oncomplete = function() { + callback(); + }; +} +function destroy(dbOpts, openDatabases2, idbChanges2, callback) { + idbChanges2.removeAllListeners(dbOpts.name); + function doDestroy() { + var req = indexedDB.deleteDatabase(dbOpts.name); + req.onsuccess = function() { + delete openDatabases2[dbOpts.name]; + callback(null, { ok: true }); + }; + } + if (dbOpts.name in openDatabases2) { + openDatabases2[dbOpts.name].then(function(res2) { + res2.idb.close(); + doDestroy(); + }); + } else { + doDestroy(); + } +} +var COUCH_COLLATE_LO = null; +var COUCH_COLLATE_HI = "\uFFFF"; +var IDB_COLLATE_LO = Number.NEGATIVE_INFINITY; +var IDB_COLLATE_HI = [[[[[[[[[[[[]]]]]]]]]]]]; +function externaliseRecord(idbDoc) { + var doc = idbDoc.revs[idbDoc.rev].data; + doc._id = idbDoc.id; + doc._rev = idbDoc.rev; + if (idbDoc.deleted) { + doc._deleted = true; + } + return doc; +} +function generateKeyRange(opts) { + function defined(obj, k) { + return obj[k] !== void 0; + } + function convert(key, exact) { + var filterDeleted = [0].concat(key); + return filterDeleted.map(function(k) { + if (k === null && exact) { + return IDB_NULL; + } else if (k === true) { + return IDB_TRUE; + } else if (k === false) { + return IDB_FALSE; + } + if (!exact) { + if (k === COUCH_COLLATE_LO) { + return IDB_COLLATE_LO; + } else if (Object.prototype.hasOwnProperty.call(k, COUCH_COLLATE_HI)) { + return IDB_COLLATE_HI; + } + } + return k; + }); + } + if (!defined(opts, "inclusive_end")) { + opts.inclusive_end = true; + } + if (!defined(opts, "inclusive_start")) { + opts.inclusive_start = true; + } + if (opts.descending) { + var realEndkey = opts.startkey, realInclusiveEnd = opts.inclusive_start; + opts.startkey = opts.endkey; + opts.endkey = realEndkey; + opts.inclusive_start = opts.inclusive_end; + opts.inclusive_end = realInclusiveEnd; + } + try { + if (defined(opts, "key")) { + return IDBKeyRange.only(convert(opts.key, true)); + } + if (defined(opts, "startkey") && !defined(opts, "endkey")) { + return IDBKeyRange.bound( + convert(opts.startkey), + [1], + !opts.inclusive_start, + true + ); + } + if (!defined(opts, "startkey") && defined(opts, "endkey")) { + return IDBKeyRange.upperBound(convert(opts.endkey), !opts.inclusive_end); + } + if (defined(opts, "startkey") && defined(opts, "endkey")) { + return IDBKeyRange.bound( + convert(opts.startkey), + convert(opts.endkey), + !opts.inclusive_start, + !opts.inclusive_end + ); + } + return IDBKeyRange.only([0]); + } catch (err) { + console.error("Could not generate keyRange", err, opts); + throw Error("Could not generate key range with " + JSON.stringify(opts)); + } +} +function getIndexHandle(pdb, fields, reject) { + var indexName = naturalIndexName(fields); + return new Promise(function(resolve) { + pdb._openTransactionSafely([DOC_STORE2], "readonly", function(err, txn) { + if (err) { + return idbError2(reject)(err); + } + txn.onabort = idbError2(reject); + txn.ontimeout = idbError2(reject); + var existingIndexNames = Array.from(txn.objectStore(DOC_STORE2).indexNames); + if (existingIndexNames.indexOf(indexName) === -1) { + pdb._freshen().then(function() { + return getIndexHandle(pdb, fields, reject); + }).then(resolve); + } else { + resolve(txn.objectStore(DOC_STORE2).index(indexName)); + } + }); + }); +} +function query(idb, signature, opts, fallback) { + var pdb = this; + var parts = signature.split("/"); + return new Promise(function(resolve, reject) { + pdb.get("_design/" + parts[0]).then(function(ddoc) { + if (isPartialFilterView(ddoc, parts[1])) { + return fallback(signature, opts).then(resolve, reject); + } + var fields = rawIndexFields(ddoc, parts[1]); + if (!fields) { + throw new Error("ddoc " + ddoc._id + " with view " + parts[1] + " does not have map.options.def.fields defined."); + } + var skip = opts.skip; + var limit = Number.isInteger(opts.limit) && opts.limit; + return getIndexHandle(pdb, fields, reject).then(function(indexHandle) { + var keyRange = generateKeyRange(opts); + var req = indexHandle.openCursor(keyRange, opts.descending ? "prev" : "next"); + var rows = []; + req.onerror = idbError2(reject); + req.onsuccess = function(e2) { + var cursor = e2.target.result; + if (!cursor || limit === 0) { + return resolve({ + rows + }); + } + if (skip) { + cursor.advance(skip); + skip = false; + return; + } + if (limit) { + limit = limit - 1; + } + rows.push({ doc: externaliseRecord(cursor.value) }); + cursor.continue(); + }; + }); + }).catch(reject); + }); +} +function viewCleanup(idb, fallback) { + return fallback(); +} +function purgeAttachments(doc, revs) { + if (!doc.attachments) { + return {}; + } + for (let key in doc.attachments) { + const attachment = doc.attachments[key]; + for (let rev2 of revs) { + if (attachment.revs[rev2]) { + delete attachment.revs[rev2]; + } + } + if (Object.keys(attachment.revs).length === 0) { + delete doc.attachments[key]; + } + } + return doc.attachments; +} +function purge(txn, docId, revs, callback) { + if (txn.error) { + return callback(txn.error); + } + const docStore = txn.txn.objectStore(DOC_STORE2); + const deletedRevs = []; + let documentWasRemovedCompletely = false; + docStore.get(docId).onsuccess = (e2) => { + const doc = e2.target.result; + for (const rev2 of revs) { + doc.rev_tree = removeLeafFromRevTree(doc.rev_tree, rev2); + delete doc.revs[rev2]; + deletedRevs.push(rev2); + } + if (doc.rev_tree.length === 0) { + docStore.delete(doc.id); + documentWasRemovedCompletely = true; + return; + } + doc.rev = winningRev(doc); + doc.data = doc.revs[doc.rev].data; + doc.attachments = purgeAttachments(doc, revs); + docStore.put(doc); + }; + txn.txn.oncomplete = function() { + callback(null, { + ok: true, + deletedRevs, + documentWasRemovedCompletely + }); + }; +} +var ADAPTER_NAME = "indexeddb"; +var idbChanges = new Changes(); +var openDatabases = {}; +function IdbPouch2(dbOpts, callback) { + if (dbOpts.view_adapter) { + console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter"); + } + var api = this; + var metadata = {}; + var $ = function(fun) { + return function() { + var args = Array.prototype.slice.call(arguments); + setup(openDatabases, api, dbOpts).then(function(res2) { + metadata = res2.metadata; + args.unshift(res2.idb); + fun.apply(api, args); + }).catch(function(err) { + var last = args.pop(); + if (typeof last === "function") { + last(err); + } else { + console.error(err); + } + }); + }; + }; + var $p = function(fun) { + return function() { + var args = Array.prototype.slice.call(arguments); + return setup(openDatabases, api, dbOpts).then(function(res2) { + metadata = res2.metadata; + args.unshift(res2.idb); + return fun.apply(api, args); + }); + }; + }; + var $t = function(fun, stores, mode) { + stores = stores || [DOC_STORE2]; + mode = mode || "readonly"; + return function() { + var args = Array.prototype.slice.call(arguments); + var txn = {}; + setup(openDatabases, api, dbOpts).then(function(res2) { + metadata = res2.metadata; + txn.txn = res2.idb.transaction(stores, mode); + }).catch(function(err) { + console.error("Failed to establish transaction safely"); + console.error(err); + txn.error = err; + }).then(function() { + args.unshift(txn); + fun.apply(api, args); + }); + }; + }; + api._openTransactionSafely = function(stores, mode, callback2) { + $t(function(txn, callback3) { + callback3(txn.error, txn.txn); + }, stores, mode)(callback2); + }; + api._remote = false; + api.type = function() { + return ADAPTER_NAME; + }; + api._id = $(function(_, cb) { + cb(null, metadata.db_uuid); + }); + api._info = $(function(_, cb) { + return info(metadata, cb); + }); + api._get = $t(get); + api._bulkDocs = $(function(_, req, opts, callback2) { + bulkDocs(api, req, opts, metadata, dbOpts, idbChanges, callback2); + }); + api._allDocs = $t(function(txn, opts, cb) { + allDocs(txn, metadata, opts, cb); + }); + api._getAttachment = $t(getAttachment); + api._changes = $t(function(txn, opts) { + changes2(txn, idbChanges, api, dbOpts, opts); + }); + api._getRevisionTree = $t(getRevisionTree); + api._doCompaction = $t(doCompaction, [DOC_STORE2], "readwrite"); + api._customFindAbstractMapper = { + query: $p(query), + viewCleanup: $p(viewCleanup) + }; + api._destroy = function(opts, callback2) { + return destroy(dbOpts, openDatabases, idbChanges, callback2); + }; + api._close = $(function(db, cb) { + delete openDatabases[dbOpts.name]; + db.close(); + cb(); + }); + api._freshen = function() { + return new Promise(function(resolve) { + api._close(function() { + $(resolve)(); + }); + }); + }; + api._purge = $t(purge, [DOC_STORE2], "readwrite"); + setTimeout(function() { + callback(null, api); + }); +} +IdbPouch2.valid = function() { + return true; +}; +function index2(PouchDB2) { + PouchDB2.adapter(ADAPTER_NAME, IdbPouch2, true); +} +var index_es_default3 = index2; + +// node_modules/pouchdb-adapter-http/lib/index.es.js +function pool(promiseFactories, limit) { + return new Promise(function(resolve, reject) { + var running2 = 0; + var current = 0; + var done = 0; + var len = promiseFactories.length; + var err; + function runNext() { + running2++; + promiseFactories[current++]().then(onSuccess, onError); + } + function doNext() { + if (++done === len) { + if (err) { + reject(err); + } else { + resolve(); + } + } else { + runNextBatch(); + } + } + function onSuccess() { + running2--; + doNext(); + } + function onError(thisErr) { + running2--; + err = err || thisErr; + doNext(); + } + function runNextBatch() { + while (running2 < limit && current < len) { + runNext(); + } + } + runNextBatch(); + }); +} +var CHANGES_BATCH_SIZE = 25; +var MAX_SIMULTANEOUS_REVS = 50; +var CHANGES_TIMEOUT_BUFFER = 5e3; +var DEFAULT_HEARTBEAT = 1e4; +var supportsBulkGetMap = {}; +function readAttachmentsAsBlobOrBuffer(row) { + let doc = row.doc || row.ok; + let atts = doc && doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function(filename) { + let att = atts[filename]; + att.data = b64ToBluffer(att.data, att.content_type); + }); +} +function encodeDocId(id) { + if (/^_design/.test(id)) { + return "_design/" + encodeURIComponent(id.slice(8)); + } + if (/^_local/.test(id)) { + return "_local/" + encodeURIComponent(id.slice(7)); + } + return encodeURIComponent(id); +} +function preprocessAttachments2(doc) { + if (!doc._attachments || !Object.keys(doc._attachments)) { + return Promise.resolve(); + } + return Promise.all(Object.keys(doc._attachments).map(function(key) { + let attachment = doc._attachments[key]; + if (attachment.data && typeof attachment.data !== "string") { + return new Promise(function(resolve) { + blobToBase64(attachment.data, resolve); + }).then(function(b64) { + attachment.data = b64; + }); + } + })); +} +function hasUrlPrefix(opts) { + if (!opts.prefix) { + return false; + } + let protocol = parseUri(opts.prefix).protocol; + return protocol === "http" || protocol === "https"; +} +function getHost(name, opts) { + if (hasUrlPrefix(opts)) { + let dbName = opts.name.substr(opts.prefix.length); + let prefix = opts.prefix.replace(/\/?$/, "/"); + name = prefix + encodeURIComponent(dbName); + } + let uri = parseUri(name); + if (uri.user || uri.password) { + uri.auth = { username: uri.user, password: uri.password }; + } + let parts = uri.path.replace(/(^\/|\/$)/g, "").split("/"); + uri.db = parts.pop(); + if (uri.db.indexOf("%") === -1) { + uri.db = encodeURIComponent(uri.db); + } + uri.path = parts.join("/"); + return uri; +} +function genDBUrl(opts, path) { + return genUrl(opts, opts.db + "/" + path); +} +function genUrl(opts, path) { + let pathDel = !opts.path ? "" : "/"; + return opts.protocol + "://" + opts.host + (opts.port ? ":" + opts.port : "") + "/" + opts.path + pathDel + path; +} +function paramsToStr(params) { + return "?" + Object.keys(params).map(function(k) { + return k + "=" + encodeURIComponent(params[k]); + }).join("&"); +} +function shouldCacheBust(opts) { + let ua = typeof navigator !== "undefined" && navigator.userAgent ? navigator.userAgent.toLowerCase() : ""; + let isIE = ua.indexOf("msie") !== -1; + let isTrident = ua.indexOf("trident") !== -1; + let isEdge = ua.indexOf("edge") !== -1; + let isGET = !("method" in opts) || opts.method === "GET"; + return (isIE || isTrident || isEdge) && isGET; +} +function HttpPouch(opts, callback) { + let api = this; + let host = getHost(opts.name, opts); + let dbUrl = genDBUrl(host, ""); + opts = clone(opts); + const ourFetch = async function(url, options) { + options = options || {}; + options.headers = options.headers || new h(); + options.credentials = "include"; + if (opts.auth || host.auth) { + let nAuth = opts.auth || host.auth; + let str = nAuth.username + ":" + nAuth.password; + let token = thisBtoa(unescape(encodeURIComponent(str))); + options.headers.set("Authorization", "Basic " + token); + } + let headers = opts.headers || {}; + Object.keys(headers).forEach(function(key) { + options.headers.append(key, headers[key]); + }); + if (shouldCacheBust(options)) { + url += (url.indexOf("?") === -1 ? "?" : "&") + "_nonce=" + Date.now(); + } + let fetchFun = opts.fetch || f2; + return await fetchFun(url, options); + }; + function adapterFun$$1(name, fun) { + return adapterFun(name, function(...args) { + setup2().then(function() { + return fun.apply(this, args); + }).catch(function(e2) { + let callback2 = args.pop(); + callback2(e2); + }); + }).bind(api); + } + async function fetchJSON(url, options) { + let result = {}; + options = options || {}; + options.headers = options.headers || new h(); + if (!options.headers.get("Content-Type")) { + options.headers.set("Content-Type", "application/json"); + } + if (!options.headers.get("Accept")) { + options.headers.set("Accept", "application/json"); + } + const response = await ourFetch(url, options); + result.ok = response.ok; + result.status = response.status; + const json = await response.json(); + result.data = json; + if (!result.ok) { + result.data.status = result.status; + let err = generateErrorFromResponse(result.data); + throw err; + } + if (Array.isArray(result.data)) { + result.data = result.data.map(function(v) { + if (v.error || v.missing) { + return generateErrorFromResponse(v); + } else { + return v; + } + }); + } + return result; + } + let setupPromise; + async function setup2() { + if (opts.skip_setup) { + return Promise.resolve(); + } + if (setupPromise) { + return setupPromise; + } + setupPromise = fetchJSON(dbUrl).catch(function(err) { + if (err && err.status && err.status === 404) { + explainError(404, "PouchDB is just detecting if the remote exists."); + return fetchJSON(dbUrl, { method: "PUT" }); + } else { + return Promise.reject(err); + } + }).catch(function(err) { + if (err && err.status && err.status === 412) { + return true; + } + return Promise.reject(err); + }); + setupPromise.catch(function() { + setupPromise = null; + }); + return setupPromise; + } + (0, import_immediate.default)(function() { + callback(null, api); + }); + api._remote = true; + api.type = function() { + return "http"; + }; + api.id = adapterFun$$1("id", async function(callback2) { + let result; + try { + const response = await ourFetch(genUrl(host, "")); + result = await response.json(); + } catch (err) { + result = {}; + } + let uuid2 = result && result.uuid ? result.uuid + host.db : genDBUrl(host, ""); + callback2(null, uuid2); + }); + api.compact = adapterFun$$1("compact", async function(opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + opts2 = clone(opts2); + await fetchJSON(genDBUrl(host, "_compact"), { method: "POST" }); + function ping() { + api.info(function(err, res2) { + if (res2 && !res2.compact_running) { + callback2(null, { ok: true }); + } else { + setTimeout(ping, opts2.interval || 200); + } + }); + } + ping(); + }); + api.bulkGet = adapterFun("bulkGet", function(opts2, callback2) { + let self2 = this; + async function doBulkGet(cb) { + let params = {}; + if (opts2.revs) { + params.revs = true; + } + if (opts2.attachments) { + params.attachments = true; + } + if (opts2.latest) { + params.latest = true; + } + try { + const result = await fetchJSON(genDBUrl(host, "_bulk_get" + paramsToStr(params)), { + method: "POST", + body: JSON.stringify({ docs: opts2.docs }) + }); + if (opts2.attachments && opts2.binary) { + result.data.results.forEach(function(res2) { + res2.docs.forEach(readAttachmentsAsBlobOrBuffer); + }); + } + cb(null, result.data); + } catch (error) { + cb(error); + } + } + function doBulkGetShim() { + let batchSize = MAX_SIMULTANEOUS_REVS; + let numBatches = Math.ceil(opts2.docs.length / batchSize); + let numDone = 0; + let results = new Array(numBatches); + function onResult(batchNum) { + return function(err, res2) { + results[batchNum] = res2.results; + if (++numDone === numBatches) { + callback2(null, { results: flatten(results) }); + } + }; + } + for (let i = 0; i < numBatches; i++) { + let subOpts = pick(opts2, ["revs", "attachments", "binary", "latest"]); + subOpts.docs = opts2.docs.slice( + i * batchSize, + Math.min(opts2.docs.length, (i + 1) * batchSize) + ); + bulkGet(self2, subOpts, onResult(i)); + } + } + let dbUrl2 = genUrl(host, ""); + let supportsBulkGet = supportsBulkGetMap[dbUrl2]; + if (typeof supportsBulkGet !== "boolean") { + doBulkGet(function(err, res2) { + if (err) { + supportsBulkGetMap[dbUrl2] = false; + explainError( + err.status, + "PouchDB is just detecting if the remote supports the _bulk_get API." + ); + doBulkGetShim(); + } else { + supportsBulkGetMap[dbUrl2] = true; + callback2(null, res2); + } + }); + } else if (supportsBulkGet) { + doBulkGet(callback2); + } else { + doBulkGetShim(); + } + }); + api._info = async function(callback2) { + try { + await setup2(); + const response = await ourFetch(genDBUrl(host, "")); + const info2 = await response.json(); + info2.host = genDBUrl(host, ""); + callback2(null, info2); + } catch (err) { + callback2(err); + } + }; + api.fetch = async function(path, options) { + await setup2(); + const url = path.substring(0, 1) === "/" ? genUrl(host, path.substring(1)) : genDBUrl(host, path); + return ourFetch(url, options); + }; + api.get = adapterFun$$1("get", async function(id, opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + opts2 = clone(opts2); + let params = {}; + if (opts2.revs) { + params.revs = true; + } + if (opts2.revs_info) { + params.revs_info = true; + } + if (opts2.latest) { + params.latest = true; + } + if (opts2.open_revs) { + if (opts2.open_revs !== "all") { + opts2.open_revs = JSON.stringify(opts2.open_revs); + } + params.open_revs = opts2.open_revs; + } + if (opts2.rev) { + params.rev = opts2.rev; + } + if (opts2.conflicts) { + params.conflicts = opts2.conflicts; + } + if (opts2.update_seq) { + params.update_seq = opts2.update_seq; + } + id = encodeDocId(id); + function fetchAttachments(doc) { + let atts = doc._attachments; + let filenames = atts && Object.keys(atts); + if (!atts || !filenames.length) { + return; + } + async function fetchData(filename) { + const att = atts[filename]; + const path = encodeDocId(doc._id) + "/" + encodeAttachmentId(filename) + "?rev=" + doc._rev; + const response = await ourFetch(genDBUrl(host, path)); + let blob; + if ("buffer" in response) { + blob = await response.buffer(); + } else { + blob = await response.blob(); + } + let data; + if (opts2.binary) { + let typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, "type"); + if (!typeFieldDescriptor || typeFieldDescriptor.set) { + blob.type = att.content_type; + } + data = blob; + } else { + data = await new Promise(function(resolve) { + blobToBase64(blob, resolve); + }); + } + delete att.stub; + delete att.length; + att.data = data; + } + let promiseFactories = filenames.map(function(filename) { + return function() { + return fetchData(filename); + }; + }); + return pool(promiseFactories, 5); + } + function fetchAllAttachments(docOrDocs) { + if (Array.isArray(docOrDocs)) { + return Promise.all(docOrDocs.map(function(doc) { + if (doc.ok) { + return fetchAttachments(doc.ok); + } + })); + } + return fetchAttachments(docOrDocs); + } + const url = genDBUrl(host, id + paramsToStr(params)); + try { + const res2 = await fetchJSON(url); + if (opts2.attachments) { + await fetchAllAttachments(res2.data); + } + callback2(null, res2.data); + } catch (error) { + error.docId = id; + callback2(error); + } + }); + api.remove = adapterFun$$1("remove", async function(docOrId, optsOrRev, opts2, cb) { + let doc; + if (typeof optsOrRev === "string") { + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts2 === "function") { + cb = opts2; + opts2 = {}; + } + } else { + doc = docOrId; + if (typeof optsOrRev === "function") { + cb = optsOrRev; + opts2 = {}; + } else { + cb = opts2; + opts2 = optsOrRev; + } + } + const rev2 = doc._rev || opts2.rev; + const url = genDBUrl(host, encodeDocId(doc._id)) + "?rev=" + rev2; + try { + const result = await fetchJSON(url, { method: "DELETE" }); + cb(null, result.data); + } catch (error) { + cb(error); + } + }); + function encodeAttachmentId(attachmentId) { + return attachmentId.split("/").map(encodeURIComponent).join("/"); + } + api.getAttachment = adapterFun$$1("getAttachment", async function(docId, attachmentId, opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + const params = opts2.rev ? "?rev=" + opts2.rev : ""; + const url = genDBUrl(host, encodeDocId(docId)) + "/" + encodeAttachmentId(attachmentId) + params; + let contentType; + try { + const response = await ourFetch(url, { method: "GET" }); + if (!response.ok) { + throw response; + } + contentType = response.headers.get("content-type"); + let blob; + if (typeof process !== "undefined" && !process.browser && typeof response.buffer === "function") { + blob = await response.buffer(); + } else { + blob = await response.blob(); + } + if (typeof process !== "undefined" && !process.browser) { + var typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, "type"); + if (!typeFieldDescriptor || typeFieldDescriptor.set) { + blob.type = contentType; + } + } + callback2(null, blob); + } catch (err) { + callback2(err); + } + }); + api.removeAttachment = adapterFun$$1("removeAttachment", async function(docId, attachmentId, rev2, callback2) { + const url = genDBUrl(host, encodeDocId(docId) + "/" + encodeAttachmentId(attachmentId)) + "?rev=" + rev2; + try { + const result = await fetchJSON(url, { method: "DELETE" }); + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }); + api.putAttachment = adapterFun$$1("putAttachment", async function(docId, attachmentId, rev2, blob, type, callback2) { + if (typeof type === "function") { + callback2 = type; + type = blob; + blob = rev2; + rev2 = null; + } + const id = encodeDocId(docId) + "/" + encodeAttachmentId(attachmentId); + let url = genDBUrl(host, id); + if (rev2) { + url += "?rev=" + rev2; + } + if (typeof blob === "string") { + let binary; + try { + binary = thisAtob(blob); + } catch (err) { + return callback2(createError( + BAD_ARG, + "Attachment is not a valid base64 string" + )); + } + blob = binary ? binStringToBluffer(binary, type) : ""; + } + try { + const result = await fetchJSON(url, { + headers: new h({ "Content-Type": type }), + method: "PUT", + body: blob + }); + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }); + api._bulkDocs = async function(req, opts2, callback2) { + req.new_edits = opts2.new_edits; + try { + await setup2(); + await Promise.all(req.docs.map(preprocessAttachments2)); + const result = await fetchJSON(genDBUrl(host, "_bulk_docs"), { + method: "POST", + body: JSON.stringify(req) + }); + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }; + api._put = async function(doc, opts2, callback2) { + try { + await setup2(); + await preprocessAttachments2(doc); + const result = await fetchJSON(genDBUrl(host, encodeDocId(doc._id)), { + method: "PUT", + body: JSON.stringify(doc) + }); + callback2(null, result.data); + } catch (error) { + error.docId = doc && doc._id; + callback2(error); + } + }; + api.allDocs = adapterFun$$1("allDocs", async function(opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + opts2 = clone(opts2); + let params = {}; + let body; + let method = "GET"; + if (opts2.conflicts) { + params.conflicts = true; + } + if (opts2.update_seq) { + params.update_seq = true; + } + if (opts2.descending) { + params.descending = true; + } + if (opts2.include_docs) { + params.include_docs = true; + } + if (opts2.attachments) { + params.attachments = true; + } + if (opts2.key) { + params.key = JSON.stringify(opts2.key); + } + if (opts2.start_key) { + opts2.startkey = opts2.start_key; + } + if (opts2.startkey) { + params.startkey = JSON.stringify(opts2.startkey); + } + if (opts2.end_key) { + opts2.endkey = opts2.end_key; + } + if (opts2.endkey) { + params.endkey = JSON.stringify(opts2.endkey); + } + if (typeof opts2.inclusive_end !== "undefined") { + params.inclusive_end = !!opts2.inclusive_end; + } + if (typeof opts2.limit !== "undefined") { + params.limit = opts2.limit; + } + if (typeof opts2.skip !== "undefined") { + params.skip = opts2.skip; + } + let paramStr = paramsToStr(params); + if (typeof opts2.keys !== "undefined") { + method = "POST"; + body = { keys: opts2.keys }; + } + try { + const result = await fetchJSON(genDBUrl(host, "_all_docs" + paramStr), { + method, + body: JSON.stringify(body) + }); + if (opts2.include_docs && opts2.attachments && opts2.binary) { + result.data.rows.forEach(readAttachmentsAsBlobOrBuffer); + } + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }); + api._changes = function(opts2) { + let batchSize = "batch_size" in opts2 ? opts2.batch_size : CHANGES_BATCH_SIZE; + opts2 = clone(opts2); + if (opts2.continuous && !("heartbeat" in opts2)) { + opts2.heartbeat = DEFAULT_HEARTBEAT; + } + let requestTimeout = "timeout" in opts2 ? opts2.timeout : 30 * 1e3; + if ("timeout" in opts2 && opts2.timeout && requestTimeout - opts2.timeout < CHANGES_TIMEOUT_BUFFER) { + requestTimeout = opts2.timeout + CHANGES_TIMEOUT_BUFFER; + } + if ("heartbeat" in opts2 && opts2.heartbeat && requestTimeout - opts2.heartbeat < CHANGES_TIMEOUT_BUFFER) { + requestTimeout = opts2.heartbeat + CHANGES_TIMEOUT_BUFFER; + } + let params = {}; + if ("timeout" in opts2 && opts2.timeout) { + params.timeout = opts2.timeout; + } + let limit = typeof opts2.limit !== "undefined" ? opts2.limit : false; + let leftToFetch = limit; + if (opts2.style) { + params.style = opts2.style; + } + if (opts2.include_docs || opts2.filter && typeof opts2.filter === "function") { + params.include_docs = true; + } + if (opts2.attachments) { + params.attachments = true; + } + if (opts2.continuous) { + params.feed = "longpoll"; + } + if (opts2.seq_interval) { + params.seq_interval = opts2.seq_interval; + } + if (opts2.conflicts) { + params.conflicts = true; + } + if (opts2.descending) { + params.descending = true; + } + if (opts2.update_seq) { + params.update_seq = true; + } + if ("heartbeat" in opts2) { + if (opts2.heartbeat) { + params.heartbeat = opts2.heartbeat; + } + } + if (opts2.filter && typeof opts2.filter === "string") { + params.filter = opts2.filter; + } + if (opts2.view && typeof opts2.view === "string") { + params.filter = "_view"; + params.view = opts2.view; + } + if (opts2.query_params && typeof opts2.query_params === "object") { + for (let param_name in opts2.query_params) { + if (Object.prototype.hasOwnProperty.call(opts2.query_params, param_name)) { + params[param_name] = opts2.query_params[param_name]; + } + } + } + let method = "GET"; + let body; + if (opts2.doc_ids) { + params.filter = "_doc_ids"; + method = "POST"; + body = { doc_ids: opts2.doc_ids }; + } else if (opts2.selector) { + params.filter = "_selector"; + method = "POST"; + body = { selector: opts2.selector }; + } + let controller = new a(); + let lastFetchedSeq; + const fetchData = async function(since, callback2) { + if (opts2.aborted) { + return; + } + params.since = since; + if (typeof params.since === "object") { + params.since = JSON.stringify(params.since); + } + if (opts2.descending) { + if (limit) { + params.limit = leftToFetch; + } + } else { + params.limit = !limit || leftToFetch > batchSize ? batchSize : leftToFetch; + } + let url = genDBUrl(host, "_changes" + paramsToStr(params)); + let fetchOpts = { + signal: controller.signal, + method, + body: JSON.stringify(body) + }; + lastFetchedSeq = since; + if (opts2.aborted) { + return; + } + try { + await setup2(); + const result = await fetchJSON(url, fetchOpts); + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }; + let results = { results: [] }; + const fetched = function(err, res2) { + if (opts2.aborted) { + return; + } + let raw_results_length = 0; + if (res2 && res2.results) { + raw_results_length = res2.results.length; + results.last_seq = res2.last_seq; + let pending = null; + let lastSeq = null; + if (typeof res2.pending === "number") { + pending = res2.pending; + } + if (typeof results.last_seq === "string" || typeof results.last_seq === "number") { + lastSeq = results.last_seq; + } + let req = {}; + req.query = opts2.query_params; + res2.results = res2.results.filter(function(c) { + leftToFetch--; + let ret = filterChange(opts2)(c); + if (ret) { + if (opts2.include_docs && opts2.attachments && opts2.binary) { + readAttachmentsAsBlobOrBuffer(c); + } + if (opts2.return_docs) { + results.results.push(c); + } + opts2.onChange(c, pending, lastSeq); + } + return ret; + }); + } else if (err) { + opts2.aborted = true; + opts2.complete(err); + return; + } + if (res2 && res2.last_seq) { + lastFetchedSeq = res2.last_seq; + } + let finished = limit && leftToFetch <= 0 || res2 && raw_results_length < batchSize || opts2.descending; + if (opts2.continuous && !(limit && leftToFetch <= 0) || !finished) { + (0, import_immediate.default)(function() { + fetchData(lastFetchedSeq, fetched); + }); + } else { + opts2.complete(null, results); + } + }; + fetchData(opts2.since || 0, fetched); + return { + cancel: function() { + opts2.aborted = true; + controller.abort(); + } + }; + }; + api.revsDiff = adapterFun$$1("revsDiff", async function(req, opts2, callback2) { + if (typeof opts2 === "function") { + callback2 = opts2; + opts2 = {}; + } + try { + const result = await fetchJSON(genDBUrl(host, "_revs_diff"), { + method: "POST", + body: JSON.stringify(req) + }); + callback2(null, result.data); + } catch (error) { + callback2(error); + } + }); + api._close = function(callback2) { + callback2(); + }; + api._destroy = async function(options, callback2) { + try { + const json = await fetchJSON(genDBUrl(host, ""), { method: "DELETE" }); + callback2(null, json); + } catch (error) { + if (error.status === 404) { + callback2(null, { ok: true }); + } else { + callback2(error); + } + } + }; +} +HttpPouch.valid = function() { + return true; +}; +function index3(PouchDB2) { + PouchDB2.adapter("http", HttpPouch, false); + PouchDB2.adapter("https", HttpPouch, false); +} +var index_es_default4 = index3; + +// node_modules/pouchdb-mapreduce-utils/lib/index.es.js +var QueryParseError = class extends Error { + constructor(message) { + super(); + this.status = 400; + this.name = "query_parse_error"; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e2) { + } + } +}; +var NotFoundError = class extends Error { + constructor(message) { + super(); + this.status = 404; + this.name = "not_found"; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError); + } catch (e2) { + } + } +}; +var BuiltInError = class extends Error { + constructor(message) { + super(); + this.status = 500; + this.name = "invalid_value"; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e2) { + } + } +}; +function promisedCallback(promise, callback) { + if (callback) { + promise.then(function(res2) { + (0, import_immediate.default)(function() { + callback(null, res2); + }); + }, function(reason) { + (0, import_immediate.default)(function() { + callback(reason); + }); + }); + } + return promise; +} +function callbackify(fun) { + return function(...args) { + var cb = args.pop(); + var promise = fun.apply(this, args); + if (typeof cb === "function") { + promisedCallback(promise, cb); + } + return promise; + }; +} +function fin(promise, finalPromiseFactory) { + return promise.then(function(res2) { + return finalPromiseFactory().then(function() { + return res2; + }); + }, function(reason) { + return finalPromiseFactory().then(function() { + throw reason; + }); + }); +} +function sequentialize(queue2, promiseFactory) { + return function() { + var args = arguments; + var that = this; + return queue2.add(function() { + return promiseFactory.apply(that, args); + }); + }; +} +function uniq(arr) { + var theSet = new ExportedSet(arr); + var result = new Array(theSet.size); + var index5 = -1; + theSet.forEach(function(value) { + result[++index5] = value; + }); + return result; +} +function mapToKeysArray(map) { + var result = new Array(map.size); + var index5 = -1; + map.forEach(function(value, key) { + result[++index5] = key; + }); + return result; +} + +// node_modules/pouchdb-abstract-mapreduce/lib/index.es.js +var TaskQueue2 = class { + constructor() { + this.promise = new Promise(function(fulfill) { + fulfill(); + }); + } + add(promiseFactory) { + this.promise = this.promise.catch(function() { + }).then(function() { + return promiseFactory(); + }); + return this.promise; + } + finish() { + return this.promise; + } +}; +function stringify2(input) { + if (!input) { + return "undefined"; + } + switch (typeof input) { + case "function": + return input.toString(); + case "string": + return input.toString(); + default: + return JSON.stringify(input); + } +} +function createViewSignature(mapFun, reduceFun) { + return stringify2(mapFun) + stringify2(reduceFun) + "undefined"; +} +async function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName2) { + const viewSignature = createViewSignature(mapFun, reduceFun); + let cachedViews; + if (!temporary) { + cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {}; + if (cachedViews[viewSignature]) { + return cachedViews[viewSignature]; + } + } + const promiseForView = sourceDB.info().then(async function(info2) { + const depDbName = info2.db_name + "-mrview-" + (temporary ? "temp" : stringMd5(viewSignature)); + function diffFunction(doc) { + doc.views = doc.views || {}; + let fullViewName = viewName; + if (fullViewName.indexOf("/") === -1) { + fullViewName = viewName + "/" + viewName; + } + const depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {}; + if (depDbs[depDbName]) { + return; + } + depDbs[depDbName] = true; + return doc; + } + await upsert(sourceDB, "_local/" + localDocName2, diffFunction); + const res2 = await sourceDB.registerDependentDatabase(depDbName); + const db = res2.db; + db.auto_compaction = true; + const view = { + name: depDbName, + db, + sourceDB, + adapter: sourceDB.adapter, + mapFun, + reduceFun + }; + let lastSeqDoc; + try { + lastSeqDoc = await view.db.get("_local/lastSeq"); + } catch (err) { + if (err.status !== 404) { + throw err; + } + } + view.seq = lastSeqDoc ? lastSeqDoc.seq : 0; + if (cachedViews) { + view.db.once("destroyed", function() { + delete cachedViews[viewSignature]; + }); + } + return view; + }); + if (cachedViews) { + cachedViews[viewSignature] = promiseForView; + } + return promiseForView; +} +var persistentQueues = {}; +var tempViewQueue = new TaskQueue2(); +var CHANGES_BATCH_SIZE2 = 50; +function parseViewName(name) { + return name.indexOf("/") === -1 ? [name, name] : name.split("/"); +} +function isGenOne(changes3) { + return changes3.length === 1 && /^1-/.test(changes3[0].rev); +} +function emitError(db, e2, data) { + try { + db.emit("error", e2); + } catch (err) { + guardedConsole( + "error", + "The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function." + ); + guardedConsole("error", e2, data); + } +} +function createAbstractMapReduce(localDocName2, mapper3, reducer3, ddocValidator3) { + function tryMap(db, fun, doc) { + try { + fun(doc); + } catch (e2) { + emitError(db, e2, { fun, doc }); + } + } + function tryReduce(db, fun, keys2, values, rereduce) { + try { + return { output: fun(keys2, values, rereduce) }; + } catch (e2) { + emitError(db, e2, { fun, keys: keys2, values, rereduce }); + return { error: e2 }; + } + } + function sortByKeyThenValue(x, y) { + const keyCompare = collate(x.key, y.key); + return keyCompare !== 0 ? keyCompare : collate(x.value, y.value); + } + function sliceResults(results, limit, skip) { + skip = skip || 0; + if (typeof limit === "number") { + return results.slice(skip, limit + skip); + } else if (skip > 0) { + return results.slice(skip); + } + return results; + } + function rowToDocId(row) { + const val = row.value; + const docId = val && typeof val === "object" && val._id || row.id; + return docId; + } + function readAttachmentsAsBlobOrBuffer2(res2) { + res2.rows.forEach(function(row) { + const atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function(filename) { + const att = atts[filename]; + atts[filename].data = b64ToBluffer(att.data, att.content_type); + }); + }); + } + function postprocessAttachments(opts) { + return function(res2) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer2(res2); + } + return res2; + }; + } + function addHttpParam(paramName, opts, params, asJson) { + let val = opts[paramName]; + if (typeof val !== "undefined") { + if (asJson) { + val = encodeURIComponent(JSON.stringify(val)); + } + params.push(paramName + "=" + val); + } + } + function coerceInteger(integerCandidate) { + if (typeof integerCandidate !== "undefined") { + const asNumber = Number(integerCandidate); + if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) { + return asNumber; + } else { + return integerCandidate; + } + } + } + function coerceOptions(opts) { + opts.group_level = coerceInteger(opts.group_level); + opts.limit = coerceInteger(opts.limit); + opts.skip = coerceInteger(opts.skip); + return opts; + } + function checkPositiveInteger(number) { + if (number) { + if (typeof number !== "number") { + return new QueryParseError(`Invalid value for integer: "${number}"`); + } + if (number < 0) { + return new QueryParseError(`Invalid value for positive integer: "${number}"`); + } + } + } + function checkQueryParseError(options, fun) { + const startkeyName = options.descending ? "endkey" : "startkey"; + const endkeyName = options.descending ? "startkey" : "endkey"; + if (typeof options[startkeyName] !== "undefined" && typeof options[endkeyName] !== "undefined" && collate(options[startkeyName], options[endkeyName]) > 0) { + throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); + } else if (fun.reduce && options.reduce !== false) { + if (options.include_docs) { + throw new QueryParseError("{include_docs:true} is invalid for reduce"); + } else if (options.keys && options.keys.length > 1 && !options.group && !options.group_level) { + throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}"); + } + } + ["group_level", "limit", "skip"].forEach(function(optionName) { + const error = checkPositiveInteger(options[optionName]); + if (error) { + throw error; + } + }); + } + async function httpQuery(db, fun, opts) { + let params = []; + let body; + let method = "GET"; + let ok; + addHttpParam("reduce", opts, params); + addHttpParam("include_docs", opts, params); + addHttpParam("attachments", opts, params); + addHttpParam("limit", opts, params); + addHttpParam("descending", opts, params); + addHttpParam("group", opts, params); + addHttpParam("group_level", opts, params); + addHttpParam("skip", opts, params); + addHttpParam("stale", opts, params); + addHttpParam("conflicts", opts, params); + addHttpParam("startkey", opts, params, true); + addHttpParam("start_key", opts, params, true); + addHttpParam("endkey", opts, params, true); + addHttpParam("end_key", opts, params, true); + addHttpParam("inclusive_end", opts, params); + addHttpParam("key", opts, params, true); + addHttpParam("update_seq", opts, params); + params = params.join("&"); + params = params === "" ? "" : "?" + params; + if (typeof opts.keys !== "undefined") { + const MAX_URL_LENGTH = 2e3; + const keysAsString = `keys=${encodeURIComponent(JSON.stringify(opts.keys))}`; + if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) { + params += (params[0] === "?" ? "&" : "?") + keysAsString; + } else { + method = "POST"; + if (typeof fun === "string") { + body = { keys: opts.keys }; + } else { + fun.keys = opts.keys; + } + } + } + if (typeof fun === "string") { + const parts = parseViewName(fun); + const response2 = await db.fetch("_design/" + parts[0] + "/_view/" + parts[1] + params, { + headers: new h({ "Content-Type": "application/json" }), + method, + body: JSON.stringify(body) + }); + ok = response2.ok; + const result2 = await response2.json(); + if (!ok) { + result2.status = response2.status; + throw generateErrorFromResponse(result2); + } + result2.rows.forEach(function(row) { + if (row.value && row.value.error && row.value.error === "builtin_reduce_error") { + throw new Error(row.reason); + } + }); + return new Promise(function(resolve) { + resolve(result2); + }).then(postprocessAttachments(opts)); + } + body = body || {}; + Object.keys(fun).forEach(function(key) { + if (Array.isArray(fun[key])) { + body[key] = fun[key]; + } else { + body[key] = fun[key].toString(); + } + }); + const response = await db.fetch("_temp_view" + params, { + headers: new h({ "Content-Type": "application/json" }), + method: "POST", + body: JSON.stringify(body) + }); + ok = response.ok; + const result = await response.json(); + if (!ok) { + result.status = response.status; + throw generateErrorFromResponse(result); + } + return new Promise(function(resolve) { + resolve(result); + }).then(postprocessAttachments(opts)); + } + function customQuery(db, fun, opts) { + return new Promise(function(resolve, reject) { + db._query(fun, opts, function(err, res2) { + if (err) { + return reject(err); + } + resolve(res2); + }); + }); + } + function customViewCleanup(db) { + return new Promise(function(resolve, reject) { + db._viewCleanup(function(err, res2) { + if (err) { + return reject(err); + } + resolve(res2); + }); + }); + } + function defaultsTo(value) { + return function(reason) { + if (reason.status === 404) { + return value; + } else { + throw reason; + } + }; + } + async function getDocsToPersist(docId, view, docIdsToChangesAndEmits) { + const metaDocId = "_local/doc_" + docId; + const defaultMetaDoc = { _id: metaDocId, keys: [] }; + const docData = docIdsToChangesAndEmits.get(docId); + const indexableKeysToKeyValues = docData[0]; + const changes3 = docData[1]; + function getMetaDoc() { + if (isGenOne(changes3)) { + return Promise.resolve(defaultMetaDoc); + } + return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc)); + } + function getKeyValueDocs(metaDoc2) { + if (!metaDoc2.keys.length) { + return Promise.resolve({ rows: [] }); + } + return view.db.allDocs({ + keys: metaDoc2.keys, + include_docs: true + }); + } + function processKeyValueDocs(metaDoc2, kvDocsRes) { + const kvDocs = []; + const oldKeys = new ExportedSet(); + for (let i = 0, len = kvDocsRes.rows.length; i < len; i++) { + const row = kvDocsRes.rows[i]; + const doc = row.doc; + if (!doc) { + continue; + } + kvDocs.push(doc); + oldKeys.add(doc._id); + doc._deleted = !indexableKeysToKeyValues.has(doc._id); + if (!doc._deleted) { + const keyValue = indexableKeysToKeyValues.get(doc._id); + if ("value" in keyValue) { + doc.value = keyValue.value; + } + } + } + const newKeys = mapToKeysArray(indexableKeysToKeyValues); + newKeys.forEach(function(key) { + if (!oldKeys.has(key)) { + const kvDoc = { + _id: key + }; + const keyValue = indexableKeysToKeyValues.get(key); + if ("value" in keyValue) { + kvDoc.value = keyValue.value; + } + kvDocs.push(kvDoc); + } + }); + metaDoc2.keys = uniq(newKeys.concat(metaDoc2.keys)); + kvDocs.push(metaDoc2); + return kvDocs; + } + const metaDoc = await getMetaDoc(); + const keyValueDocs = await getKeyValueDocs(metaDoc); + return processKeyValueDocs(metaDoc, keyValueDocs); + } + function updatePurgeSeq(view) { + return view.sourceDB.get("_local/purges").then(function(res2) { + const purgeSeq = res2.purgeSeq; + return view.db.get("_local/purgeSeq").then(function(res3) { + return res3._rev; + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return void 0; + }).then(function(rev2) { + return view.db.put({ + _id: "_local/purgeSeq", + _rev: rev2, + purgeSeq + }); + }); + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + }); + } + function saveKeyValues(view, docIdsToChangesAndEmits, seq) { + var seqDocId = "_local/lastSeq"; + return view.db.get(seqDocId).catch(defaultsTo({ _id: seqDocId, seq: 0 })).then(function(lastSeqDoc) { + var docIds = mapToKeysArray(docIdsToChangesAndEmits); + return Promise.all(docIds.map(function(docId) { + return getDocsToPersist(docId, view, docIdsToChangesAndEmits); + })).then(function(listOfDocsToPersist) { + var docsToPersist = flatten(listOfDocsToPersist); + lastSeqDoc.seq = seq; + docsToPersist.push(lastSeqDoc); + return view.db.bulkDocs({ docs: docsToPersist }); + }).then(() => updatePurgeSeq(view)); + }); + } + function getQueue(view) { + const viewName = typeof view === "string" ? view : view.name; + let queue2 = persistentQueues[viewName]; + if (!queue2) { + queue2 = persistentQueues[viewName] = new TaskQueue2(); + } + return queue2; + } + async function updateView(view, opts) { + return sequentialize(getQueue(view), function() { + return updateViewInQueue(view, opts); + })(); + } + async function updateViewInQueue(view, opts) { + let mapResults; + let doc; + let taskId; + function emit(key, value) { + const output = { id: doc._id, key: normalizeKey(key) }; + if (typeof value !== "undefined" && value !== null) { + output.value = normalizeKey(value); + } + mapResults.push(output); + } + const mapFun = mapper3(view.mapFun, emit); + let currentSeq = view.seq || 0; + function createTask() { + return view.sourceDB.info().then(function(info2) { + taskId = view.sourceDB.activeTasks.add({ + name: "view_indexing", + total_items: info2.update_seq - currentSeq + }); + }); + } + function processChange2(docIdsToChangesAndEmits, seq) { + return function() { + return saveKeyValues(view, docIdsToChangesAndEmits, seq); + }; + } + let indexed_docs = 0; + const progress = { + view: view.name, + indexed_docs + }; + view.sourceDB.emit("indexing", progress); + const queue2 = new TaskQueue2(); + async function processNextBatch() { + const response = await view.sourceDB.changes({ + return_docs: true, + conflicts: true, + include_docs: true, + style: "all_docs", + since: currentSeq, + limit: opts.changes_batch_size + }); + const purges = await getRecentPurges(); + return processBatch(response, purges); + } + function getRecentPurges() { + return view.db.get("_local/purgeSeq").then(function(res2) { + return res2.purgeSeq; + }).catch(function(err) { + if (err && err.status !== 404) { + throw err; + } + return -1; + }).then(function(purgeSeq) { + return view.sourceDB.get("_local/purges").then(function(res2) { + const recentPurges = res2.purges.filter(function(purge2, index5) { + return index5 > purgeSeq; + }).map((purge2) => purge2.docId); + const uniquePurges = recentPurges.filter(function(docId, index5) { + return recentPurges.indexOf(docId) === index5; + }); + return Promise.all(uniquePurges.map(function(docId) { + return view.sourceDB.get(docId).then(function(doc2) { + return { docId, doc: doc2 }; + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return { docId }; + }); + })); + }).catch(function(err) { + if (err && err.status !== 404) { + throw err; + } + return []; + }); + }); + } + function processBatch(response, purges) { + var results = response.results; + if (!results.length && !purges.length) { + return; + } + for (let purge2 of purges) { + const index5 = results.findIndex(function(change) { + return change.id === purge2.docId; + }); + if (index5 < 0) { + const entry = { + _id: purge2.docId, + doc: { + _id: purge2.docId, + _deleted: 1 + }, + changes: [] + }; + if (purge2.doc) { + entry.doc = purge2.doc; + entry.changes.push({ rev: purge2.doc._rev }); + } + results.push(entry); + } + } + var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results); + queue2.add(processChange2(docIdsToChangesAndEmits, currentSeq)); + indexed_docs = indexed_docs + results.length; + const progress2 = { + view: view.name, + last_seq: response.last_seq, + results_count: results.length, + indexed_docs + }; + view.sourceDB.emit("indexing", progress2); + view.sourceDB.activeTasks.update(taskId, { completed_items: indexed_docs }); + if (results.length < opts.changes_batch_size) { + return; + } + return processNextBatch(); + } + function createDocIdsToChangesAndEmits(results) { + const docIdsToChangesAndEmits = new ExportedMap(); + for (let i = 0, len = results.length; i < len; i++) { + const change = results[i]; + if (change.doc._id[0] !== "_") { + mapResults = []; + doc = change.doc; + if (!doc._deleted) { + tryMap(view.sourceDB, mapFun, doc); + } + mapResults.sort(sortByKeyThenValue); + const indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults); + docIdsToChangesAndEmits.set(change.doc._id, [ + indexableKeysToKeyValues, + change.changes + ]); + } + currentSeq = change.seq; + } + return docIdsToChangesAndEmits; + } + function createIndexableKeysToKeyValues(mapResults2) { + const indexableKeysToKeyValues = new ExportedMap(); + let lastKey; + for (let i = 0, len = mapResults2.length; i < len; i++) { + const emittedKeyValue = mapResults2[i]; + const complexKey = [emittedKeyValue.key, emittedKeyValue.id]; + if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) { + complexKey.push(i); + } + indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue); + lastKey = emittedKeyValue.key; + } + return indexableKeysToKeyValues; + } + try { + await createTask(); + await processNextBatch(); + await queue2.finish(); + view.seq = currentSeq; + view.sourceDB.activeTasks.remove(taskId); + } catch (error) { + view.sourceDB.activeTasks.remove(taskId, error); + } + } + function reduceView(view, results, options) { + if (options.group_level === 0) { + delete options.group_level; + } + const shouldGroup = options.group || options.group_level; + const reduceFun = reducer3(view.reduceFun); + const groups = []; + const lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY : options.group_level; + results.forEach(function(e2) { + const last = groups[groups.length - 1]; + let groupKey = shouldGroup ? e2.key : null; + if (shouldGroup && Array.isArray(groupKey)) { + groupKey = groupKey.slice(0, lvl); + } + if (last && collate(last.groupKey, groupKey) === 0) { + last.keys.push([e2.key, e2.id]); + last.values.push(e2.value); + return; + } + groups.push({ + keys: [[e2.key, e2.id]], + values: [e2.value], + groupKey + }); + }); + results = []; + for (let i = 0, len = groups.length; i < len; i++) { + const e2 = groups[i]; + const reduceTry = tryReduce(view.sourceDB, reduceFun, e2.keys, e2.values, false); + if (reduceTry.error && reduceTry.error instanceof BuiltInError) { + throw reduceTry.error; + } + results.push({ + value: reduceTry.error ? null : reduceTry.output, + key: e2.groupKey + }); + } + return { rows: sliceResults(results, options.limit, options.skip) }; + } + function queryView(view, opts) { + return sequentialize(getQueue(view), function() { + return queryViewInQueue(view, opts); + })(); + } + async function queryViewInQueue(view, opts) { + let totalRows; + const shouldReduce = view.reduceFun && opts.reduce !== false; + const skip = opts.skip || 0; + if (typeof opts.keys !== "undefined" && !opts.keys.length) { + opts.limit = 0; + delete opts.keys; + } + async function fetchFromView(viewOpts) { + viewOpts.include_docs = true; + const res2 = await view.db.allDocs(viewOpts); + totalRows = res2.total_rows; + return res2.rows.map(function(result) { + if ("value" in result.doc && typeof result.doc.value === "object" && result.doc.value !== null) { + const keys2 = Object.keys(result.doc.value).sort(); + const expectedKeys = ["id", "key", "value"]; + if (!(keys2 < expectedKeys || keys2 > expectedKeys)) { + return result.doc.value; + } + } + const parsedKeyAndDocId = parseIndexableString(result.doc._id); + return { + key: parsedKeyAndDocId[0], + id: parsedKeyAndDocId[1], + value: "value" in result.doc ? result.doc.value : null + }; + }); + } + async function onMapResultsReady(rows) { + let finalResults; + if (shouldReduce) { + finalResults = reduceView(view, rows, opts); + } else if (typeof opts.keys === "undefined") { + finalResults = { + total_rows: totalRows, + offset: skip, + rows + }; + } else { + finalResults = { + total_rows: totalRows, + offset: skip, + rows: sliceResults(rows, opts.limit, opts.skip) + }; + } + if (opts.update_seq) { + finalResults.update_seq = view.seq; + } + if (opts.include_docs) { + const docIds = uniq(rows.map(rowToDocId)); + const allDocsRes = await view.sourceDB.allDocs({ + keys: docIds, + include_docs: true, + conflicts: opts.conflicts, + attachments: opts.attachments, + binary: opts.binary + }); + var docIdsToDocs = new ExportedMap(); + allDocsRes.rows.forEach(function(row) { + docIdsToDocs.set(row.id, row.doc); + }); + rows.forEach(function(row) { + var docId = rowToDocId(row); + var doc = docIdsToDocs.get(docId); + if (doc) { + row.doc = doc; + } + }); + return finalResults; + } else { + return finalResults; + } + } + if (typeof opts.keys !== "undefined") { + const keys2 = opts.keys; + const fetchPromises = keys2.map(function(key) { + const viewOpts = { + startkey: toIndexableString([key]), + endkey: toIndexableString([key, {}]) + }; + if (opts.update_seq) { + viewOpts.update_seq = true; + } + return fetchFromView(viewOpts); + }); + const result = await Promise.all(fetchPromises); + const flattenedResult = flatten(result); + return onMapResultsReady(flattenedResult); + } else { + const viewOpts = { + descending: opts.descending + }; + if (opts.update_seq) { + viewOpts.update_seq = true; + } + let startkey; + let endkey; + if ("start_key" in opts) { + startkey = opts.start_key; + } + if ("startkey" in opts) { + startkey = opts.startkey; + } + if ("end_key" in opts) { + endkey = opts.end_key; + } + if ("endkey" in opts) { + endkey = opts.endkey; + } + if (typeof startkey !== "undefined") { + viewOpts.startkey = opts.descending ? toIndexableString([startkey, {}]) : toIndexableString([startkey]); + } + if (typeof endkey !== "undefined") { + let inclusiveEnd = opts.inclusive_end !== false; + if (opts.descending) { + inclusiveEnd = !inclusiveEnd; + } + viewOpts.endkey = toIndexableString( + inclusiveEnd ? [endkey, {}] : [endkey] + ); + } + if (typeof opts.key !== "undefined") { + const keyStart = toIndexableString([opts.key]); + const keyEnd = toIndexableString([opts.key, {}]); + if (viewOpts.descending) { + viewOpts.endkey = keyStart; + viewOpts.startkey = keyEnd; + } else { + viewOpts.startkey = keyStart; + viewOpts.endkey = keyEnd; + } + } + if (!shouldReduce) { + if (typeof opts.limit === "number") { + viewOpts.limit = opts.limit; + } + viewOpts.skip = skip; + } + const result = await fetchFromView(viewOpts); + return onMapResultsReady(result); + } + } + async function httpViewCleanup(db) { + const response = await db.fetch("_view_cleanup", { + headers: new h({ "Content-Type": "application/json" }), + method: "POST" + }); + return response.json(); + } + async function localViewCleanup(db) { + try { + const metaDoc = await db.get("_local/" + localDocName2); + const docsToViews = new ExportedMap(); + Object.keys(metaDoc.views).forEach(function(fullViewName) { + const parts = parseViewName(fullViewName); + const designDocName = "_design/" + parts[0]; + const viewName = parts[1]; + let views = docsToViews.get(designDocName); + if (!views) { + views = new ExportedSet(); + docsToViews.set(designDocName, views); + } + views.add(viewName); + }); + const opts = { + keys: mapToKeysArray(docsToViews), + include_docs: true + }; + const res2 = await db.allDocs(opts); + const viewsToStatus = {}; + res2.rows.forEach(function(row) { + const ddocName = row.key.substring(8); + docsToViews.get(row.key).forEach(function(viewName) { + let fullViewName = ddocName + "/" + viewName; + if (!metaDoc.views[fullViewName]) { + fullViewName = viewName; + } + const viewDBNames = Object.keys(metaDoc.views[fullViewName]); + const statusIsGood = row.doc && row.doc.views && row.doc.views[viewName]; + viewDBNames.forEach(function(viewDBName) { + viewsToStatus[viewDBName] = viewsToStatus[viewDBName] || statusIsGood; + }); + }); + }); + const dbsToDelete = Object.keys(viewsToStatus).filter(function(viewDBName) { + return !viewsToStatus[viewDBName]; + }); + const destroyPromises = dbsToDelete.map(function(viewDBName) { + return sequentialize(getQueue(viewDBName), function() { + return new db.constructor(viewDBName, db.__opts).destroy(); + })(); + }); + return Promise.all(destroyPromises).then(function() { + return { ok: true }; + }); + } catch (err) { + if (err.status === 404) { + return { ok: true }; + } else { + throw err; + } + } + } + async function queryPromised(db, fun, opts) { + if (typeof db._query === "function") { + return customQuery(db, fun, opts); + } + if (isRemote(db)) { + return httpQuery(db, fun, opts); + } + const updateViewOpts = { + changes_batch_size: db.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE2 + }; + if (typeof fun !== "string") { + checkQueryParseError(opts, fun); + tempViewQueue.add(async function() { + const view = await createView( + db, + "temp_view/temp_view", + fun.map, + fun.reduce, + true, + localDocName2 + ); + return fin( + updateView(view, updateViewOpts).then( + function() { + return queryView(view, opts); + } + ), + function() { + return view.db.destroy(); + } + ); + }); + return tempViewQueue.finish(); + } else { + const fullViewName = fun; + const parts = parseViewName(fullViewName); + const designDocName = parts[0]; + const viewName = parts[1]; + const doc = await db.get("_design/" + designDocName); + fun = doc.views && doc.views[viewName]; + if (!fun) { + throw new NotFoundError(`ddoc ${doc._id} has no view named ${viewName}`); + } + ddocValidator3(doc, viewName); + checkQueryParseError(opts, fun); + const view = await createView( + db, + fullViewName, + fun.map, + fun.reduce, + false, + localDocName2 + ); + if (opts.stale === "ok" || opts.stale === "update_after") { + if (opts.stale === "update_after") { + (0, import_immediate.default)(function() { + updateView(view, updateViewOpts); + }); + } + return queryView(view, opts); + } else { + await updateView(view, updateViewOpts); + return queryView(view, opts); + } + } + } + function abstractQuery(fun, opts, callback) { + const db = this; + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts = opts ? coerceOptions(opts) : {}; + if (typeof fun === "function") { + fun = { map: fun }; + } + const promise = Promise.resolve().then(function() { + return queryPromised(db, fun, opts); + }); + promisedCallback(promise, callback); + return promise; + } + const abstractViewCleanup = callbackify(function() { + const db = this; + if (typeof db._viewCleanup === "function") { + return customViewCleanup(db); + } + if (isRemote(db)) { + return httpViewCleanup(db); + } + return localViewCleanup(db); + }); + return { + query: abstractQuery, + viewCleanup: abstractViewCleanup + }; +} +var index_es_default5 = createAbstractMapReduce; + +// node_modules/pouchdb-mapreduce/lib/index-browser.es.js +function createBuiltInError(name) { + var message = "builtin " + name + " function requires map values to be numbers or number arrays"; + return new BuiltInError(message); +} +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== "number") { + if (Array.isArray(num)) { + result = typeof result === "number" ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== "number") { + throw createBuiltInError("_sum"); + } else if (typeof result[j] === "undefined") { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { + throw createBuiltInError("_sum"); + } + } else if (typeof result === "number") { + result += num; + } else { + result[0] += num; + } + } + return result; +} +var log = guardedConsole.bind(null, "log"); +var isArray = Array.isArray; +var toJSON = JSON.parse; +function evalFunctionWithEval(func, emit) { + return scopeEval( + "return (" + func.replace(/;\s*$/, "") + ");", + { + emit, + sum, + log, + isArray, + toJSON + } + ); +} +var builtInReduce = { + _sum: function(keys2, values) { + return sum(values); + }, + _count: function(keys2, values) { + return values.length; + }, + _stats: function(keys2, values) { + function sumsqr(values2) { + var _sumsqr = 0; + for (var i = 0, len = values2.length; i < len; i++) { + var num = values2[i]; + _sumsqr += num * num; + } + return _sumsqr; + } + return { + sum: sum(values), + min: Math.min.apply(null, values), + max: Math.max.apply(null, values), + count: values.length, + sumsqr: sumsqr(values) + }; + } +}; +function getBuiltIn(reduceFunString) { + if (/^_sum/.test(reduceFunString)) { + return builtInReduce._sum; + } else if (/^_count/.test(reduceFunString)) { + return builtInReduce._count; + } else if (/^_stats/.test(reduceFunString)) { + return builtInReduce._stats; + } else if (/^_/.test(reduceFunString)) { + throw new Error(reduceFunString + " is not a supported reduce function."); + } +} +function mapper(mapFun, emit) { + if (typeof mapFun === "function" && mapFun.length === 2) { + var origMap = mapFun; + return function(doc) { + return origMap(doc, emit); + }; + } else { + return evalFunctionWithEval(mapFun.toString(), emit); + } +} +function reducer(reduceFun) { + var reduceFunString = reduceFun.toString(); + var builtIn = getBuiltIn(reduceFunString); + if (builtIn) { + return builtIn; + } else { + return evalFunctionWithEval(reduceFunString); + } +} +function ddocValidator(ddoc, viewName) { + var fun = ddoc.views && ddoc.views[viewName]; + if (typeof fun.map !== "string") { + throw new NotFoundError("ddoc " + ddoc._id + " has no string view named " + viewName + ", instead found object of type: " + typeof fun.map); + } +} +var localDocName = "mrviews"; +var abstract = index_es_default5(localDocName, mapper, reducer, ddocValidator); +function query2(fun, opts, callback) { + return abstract.query.call(this, fun, opts, callback); +} +function viewCleanup2(callback) { + return abstract.viewCleanup.call(this, callback); +} +var index4 = { + query: query2, + viewCleanup: viewCleanup2 +}; +var index_browser_es_default2 = index4; + +// node_modules/pouchdb-checkpointer/lib/index.es.js +var CHECKPOINT_VERSION = 1; +var REPLICATOR = "pouchdb"; +var CHECKPOINT_HISTORY_SIZE = 5; +var LOWEST_SEQ = 0; +function updateCheckpoint(db, id, checkpoint, session, returnValue) { + return db.get(id).catch(function(err) { + if (err.status === 404) { + if (db.adapter === "http" || db.adapter === "https") { + explainError( + 404, + "PouchDB is just checking if a remote checkpoint exists." + ); + } + return { + session_id: session, + _id: id, + history: [], + replicator: REPLICATOR, + version: CHECKPOINT_VERSION + }; + } + throw err; + }).then(function(doc) { + if (returnValue.cancelled) { + return; + } + if (doc.last_seq === checkpoint) { + return; + } + doc.history = (doc.history || []).filter(function(item) { + return item.session_id !== session; + }); + doc.history.unshift({ + last_seq: checkpoint, + session_id: session + }); + doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE); + doc.version = CHECKPOINT_VERSION; + doc.replicator = REPLICATOR; + doc.session_id = session; + doc.last_seq = checkpoint; + return db.put(doc).catch(function(err) { + if (err.status === 409) { + return updateCheckpoint(db, id, checkpoint, session, returnValue); + } + throw err; + }); + }); +} +var CheckpointerInternal = class { + constructor(src, target, id, returnValue, opts) { + this.src = src; + this.target = target; + this.id = id; + this.returnValue = returnValue; + this.opts = opts || {}; + } + writeCheckpoint(checkpoint, session) { + var self2 = this; + return this.updateTarget(checkpoint, session).then(function() { + return self2.updateSource(checkpoint, session); + }); + } + updateTarget(checkpoint, session) { + if (this.opts.writeTargetCheckpoint) { + return updateCheckpoint( + this.target, + this.id, + checkpoint, + session, + this.returnValue + ); + } else { + return Promise.resolve(true); + } + } + updateSource(checkpoint, session) { + if (this.opts.writeSourceCheckpoint) { + var self2 = this; + return updateCheckpoint( + this.src, + this.id, + checkpoint, + session, + this.returnValue + ).catch(function(err) { + if (isForbiddenError(err)) { + self2.opts.writeSourceCheckpoint = false; + return true; + } + throw err; + }); + } else { + return Promise.resolve(true); + } + } + getCheckpoint() { + var self2 = this; + if (self2.opts && self2.opts.writeSourceCheckpoint && !self2.opts.writeTargetCheckpoint) { + return self2.src.get(self2.id).then(function(sourceDoc) { + return sourceDoc.last_seq || LOWEST_SEQ; + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return LOWEST_SEQ; + }); + } + return self2.target.get(self2.id).then(function(targetDoc) { + if (self2.opts && self2.opts.writeTargetCheckpoint && !self2.opts.writeSourceCheckpoint) { + return targetDoc.last_seq || LOWEST_SEQ; + } + return self2.src.get(self2.id).then(function(sourceDoc) { + if (targetDoc.version !== sourceDoc.version) { + return LOWEST_SEQ; + } + var version2; + if (targetDoc.version) { + version2 = targetDoc.version.toString(); + } else { + version2 = "undefined"; + } + if (version2 in comparisons) { + return comparisons[version2](targetDoc, sourceDoc); + } + return LOWEST_SEQ; + }, function(err) { + if (err.status === 404 && targetDoc.last_seq) { + return self2.src.put({ + _id: self2.id, + last_seq: LOWEST_SEQ + }).then(function() { + return LOWEST_SEQ; + }, function(err2) { + if (isForbiddenError(err2)) { + self2.opts.writeSourceCheckpoint = false; + return targetDoc.last_seq; + } + return LOWEST_SEQ; + }); + } + throw err; + }); + }).catch(function(err) { + if (err.status !== 404) { + throw err; + } + return LOWEST_SEQ; + }); + } +}; +var comparisons = { + "undefined": function(targetDoc, sourceDoc) { + if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) { + return sourceDoc.last_seq; + } + return 0; + }, + "1": function(targetDoc, sourceDoc) { + return compareReplicationLogs(sourceDoc, targetDoc).last_seq; + } +}; +function compareReplicationLogs(srcDoc, tgtDoc) { + if (srcDoc.session_id === tgtDoc.session_id) { + return { + last_seq: srcDoc.last_seq, + history: srcDoc.history + }; + } + return compareReplicationHistory(srcDoc.history, tgtDoc.history); +} +function compareReplicationHistory(sourceHistory, targetHistory) { + var S = sourceHistory[0]; + var sourceRest = sourceHistory.slice(1); + var T = targetHistory[0]; + var targetRest = targetHistory.slice(1); + if (!S || targetHistory.length === 0) { + return { + last_seq: LOWEST_SEQ, + history: [] + }; + } + var sourceId = S.session_id; + if (hasSessionId(sourceId, targetHistory)) { + return { + last_seq: S.last_seq, + history: sourceHistory + }; + } + var targetId = T.session_id; + if (hasSessionId(targetId, sourceRest)) { + return { + last_seq: T.last_seq, + history: targetRest + }; + } + return compareReplicationHistory(sourceRest, targetRest); +} +function hasSessionId(sessionId, history) { + var props = history[0]; + var rest = history.slice(1); + if (!sessionId || history.length === 0) { + return false; + } + if (sessionId === props.session_id) { + return true; + } + return hasSessionId(sessionId, rest); +} +function isForbiddenError(err) { + return typeof err.status === "number" && Math.floor(err.status / 100) === 4; +} +function Checkpointer(src, target, id, returnValue, opts) { + if (!(this instanceof CheckpointerInternal)) { + return new CheckpointerInternal(src, target, id, returnValue, opts); + } + return Checkpointer; +} +var index_es_default6 = Checkpointer; + +// node_modules/pouchdb-generate-replication-id/lib/index.es.js +function sortObjectPropertiesByKey(queryParams) { + return Object.keys(queryParams).sort(collate).reduce(function(result, key) { + result[key] = queryParams[key]; + return result; + }, {}); +} +function generateReplicationId(src, target, opts) { + var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : ""; + var filterFun = opts.filter ? opts.filter.toString() : ""; + var queryParams = ""; + var filterViewName = ""; + var selector = ""; + if (opts.selector) { + selector = JSON.stringify(opts.selector); + } + if (opts.filter && opts.query_params) { + queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params)); + } + if (opts.filter && opts.filter === "_view") { + filterViewName = opts.view.toString(); + } + return Promise.all([src.id(), target.id()]).then(function(res2) { + var queryData = res2[0] + res2[1] + filterFun + filterViewName + queryParams + docIds + selector; + return new Promise(function(resolve) { + binaryMd5(queryData, resolve); + }); + }).then(function(md5sum) { + md5sum = md5sum.replace(/\//g, ".").replace(/\+/g, "_"); + return "_local/" + md5sum; + }); +} +var index_es_default7 = generateReplicationId; + +// node_modules/pouchdb-replication/lib/index.es.js +var import_events3 = __toESM(require_events()); +function fileHasChanged(localDoc, remoteDoc, filename) { + return !localDoc._attachments || !localDoc._attachments[filename] || localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest; +} +function getDocAttachments(db, doc) { + var filenames = Object.keys(doc._attachments); + return Promise.all(filenames.map(function(filename) { + return db.getAttachment(doc._id, filename, { rev: doc._rev }); + })); +} +function getDocAttachmentsFromTargetOrSource(target, src, doc) { + var doCheckForLocalAttachments = isRemote(src) && !isRemote(target); + var filenames = Object.keys(doc._attachments); + if (!doCheckForLocalAttachments) { + return getDocAttachments(src, doc); + } + return target.get(doc._id).then(function(localDoc) { + return Promise.all(filenames.map(function(filename) { + if (fileHasChanged(localDoc, doc, filename)) { + return src.getAttachment(doc._id, filename); + } + return target.getAttachment(localDoc._id, filename); + })); + }).catch(function(error) { + if (error.status !== 404) { + throw error; + } + return getDocAttachments(src, doc); + }); +} +function createBulkGetOpts(diffs) { + var requests = []; + Object.keys(diffs).forEach(function(id) { + var missingRevs = diffs[id].missing; + missingRevs.forEach(function(missingRev) { + requests.push({ + id, + rev: missingRev + }); + }); + }); + return { + docs: requests, + revs: true, + latest: true + }; +} +function getDocs(src, target, diffs, state) { + diffs = clone(diffs); + var resultDocs = [], ok = true; + function getAllDocs() { + var bulkGetOpts = createBulkGetOpts(diffs); + if (!bulkGetOpts.docs.length) { + return; + } + return src.bulkGet(bulkGetOpts).then(function(bulkGetResponse) { + if (state.cancelled) { + throw new Error("cancelled"); + } + return Promise.all(bulkGetResponse.results.map(function(bulkGetInfo) { + return Promise.all(bulkGetInfo.docs.map(function(doc) { + var remoteDoc = doc.ok; + if (doc.error) { + ok = false; + } + if (!remoteDoc || !remoteDoc._attachments) { + return remoteDoc; + } + return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc).then(function(attachments) { + var filenames = Object.keys(remoteDoc._attachments); + attachments.forEach(function(attachment, i) { + var att = remoteDoc._attachments[filenames[i]]; + delete att.stub; + delete att.length; + att.data = attachment; + }); + return remoteDoc; + }); + })); + })).then(function(results) { + resultDocs = resultDocs.concat(flatten(results).filter(Boolean)); + }); + }); + } + function returnResult() { + return { ok, docs: resultDocs }; + } + return Promise.resolve().then(getAllDocs).then(returnResult); +} +var STARTING_BACK_OFF = 0; +function backOff(opts, returnValue, error, callback) { + if (opts.retry === false) { + returnValue.emit("error", error); + returnValue.removeAllListeners(); + return; + } + if (typeof opts.back_off_function !== "function") { + opts.back_off_function = defaultBackOff; + } + returnValue.emit("requestError", error); + if (returnValue.state === "active" || returnValue.state === "pending") { + returnValue.emit("paused", error); + returnValue.state = "stopped"; + var backOffSet = function backoffTimeSet() { + opts.current_back_off = STARTING_BACK_OFF; + }; + var removeBackOffSetter = function removeBackOffTimeSet() { + returnValue.removeListener("active", backOffSet); + }; + returnValue.once("paused", removeBackOffSetter); + returnValue.once("active", backOffSet); + } + opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF; + opts.current_back_off = opts.back_off_function(opts.current_back_off); + setTimeout(callback, opts.current_back_off); +} +function replicate(src, target, opts, returnValue, result) { + var batches = []; + var currentBatch; + var pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + var writingCheckpoint = false; + var changesCompleted = false; + var replicationCompleted = false; + var initial_last_seq = 0; + var last_seq = 0; + var continuous = opts.continuous || opts.live || false; + var batch_size = opts.batch_size || 100; + var batches_limit = opts.batches_limit || 10; + var style = opts.style || "all_docs"; + var changesPending = false; + var doc_ids = opts.doc_ids; + var selector = opts.selector; + var repId; + var checkpointer; + var changedDocs = []; + var session = uuid(); + var taskId; + result = result || { + ok: true, + start_time: new Date().toISOString(), + docs_read: 0, + docs_written: 0, + doc_write_failures: 0, + errors: [] + }; + var changesOpts = {}; + returnValue.ready(src, target); + function initCheckpointer() { + if (checkpointer) { + return Promise.resolve(); + } + return index_es_default7(src, target, opts).then(function(res2) { + repId = res2; + var checkpointOpts = {}; + if (opts.checkpoint === false) { + checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false }; + } else if (opts.checkpoint === "source") { + checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false }; + } else if (opts.checkpoint === "target") { + checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true }; + } else { + checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true }; + } + checkpointer = new index_es_default6(src, target, repId, returnValue, checkpointOpts); + }); + } + function writeDocs() { + changedDocs = []; + if (currentBatch.docs.length === 0) { + return; + } + var docs = currentBatch.docs; + var bulkOpts = { timeout: opts.timeout }; + return target.bulkDocs({ docs, new_edits: false }, bulkOpts).then(function(res2) { + if (returnValue.cancelled) { + completeReplication(); + throw new Error("cancelled"); + } + var errorsById = /* @__PURE__ */ Object.create(null); + res2.forEach(function(res3) { + if (res3.error) { + errorsById[res3.id] = res3; + } + }); + var errorsNo = Object.keys(errorsById).length; + result.doc_write_failures += errorsNo; + result.docs_written += docs.length - errorsNo; + docs.forEach(function(doc) { + var error = errorsById[doc._id]; + if (error) { + result.errors.push(error); + var errorName = (error.name || "").toLowerCase(); + if (errorName === "unauthorized" || errorName === "forbidden") { + returnValue.emit("denied", clone(error)); + } else { + throw error; + } + } else { + changedDocs.push(doc); + } + }); + }, function(err) { + result.doc_write_failures += docs.length; + throw err; + }); + } + function finishBatch() { + if (currentBatch.error) { + throw new Error("There was a problem getting docs."); + } + result.last_seq = last_seq = currentBatch.seq; + var outResult = clone(result); + if (changedDocs.length) { + outResult.docs = changedDocs; + if (typeof currentBatch.pending === "number") { + outResult.pending = currentBatch.pending; + delete currentBatch.pending; + } + returnValue.emit("change", outResult); + } + writingCheckpoint = true; + src.info().then(function(info2) { + var task = src.activeTasks.get(taskId); + if (!currentBatch || !task) { + return; + } + var completed = task.completed_items || 0; + var total_items = parseInt(info2.update_seq, 10) - parseInt(initial_last_seq, 10); + src.activeTasks.update(taskId, { + completed_items: completed + currentBatch.changes.length, + total_items + }); + }); + return checkpointer.writeCheckpoint( + currentBatch.seq, + session + ).then(function() { + returnValue.emit("checkpoint", { "checkpoint": currentBatch.seq }); + writingCheckpoint = false; + if (returnValue.cancelled) { + completeReplication(); + throw new Error("cancelled"); + } + currentBatch = void 0; + getChanges(); + }).catch(function(err) { + onCheckpointError(err); + throw err; + }); + } + function getDiffs() { + var diff = {}; + currentBatch.changes.forEach(function(change) { + returnValue.emit("checkpoint", { "revs_diff": change }); + if (change.id === "_user/") { + return; + } + diff[change.id] = change.changes.map(function(x) { + return x.rev; + }); + }); + return target.revsDiff(diff).then(function(diffs) { + if (returnValue.cancelled) { + completeReplication(); + throw new Error("cancelled"); + } + currentBatch.diffs = diffs; + }); + } + function getBatchDocs() { + return getDocs(src, target, currentBatch.diffs, returnValue).then(function(got) { + currentBatch.error = !got.ok; + got.docs.forEach(function(doc) { + delete currentBatch.diffs[doc._id]; + result.docs_read++; + currentBatch.docs.push(doc); + }); + }); + } + function startNextBatch() { + if (returnValue.cancelled || currentBatch) { + return; + } + if (batches.length === 0) { + processPendingBatch(true); + return; + } + currentBatch = batches.shift(); + returnValue.emit("checkpoint", { "start_next_batch": currentBatch.seq }); + getDiffs().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch(function(err) { + abortReplication("batch processing terminated with error", err); + }); + } + function processPendingBatch(immediate2) { + if (pendingBatch.changes.length === 0) { + if (batches.length === 0 && !currentBatch) { + if (continuous && changesOpts.live || changesCompleted) { + returnValue.state = "pending"; + returnValue.emit("paused"); + } + if (changesCompleted) { + completeReplication(); + } + } + return; + } + if (immediate2 || changesCompleted || pendingBatch.changes.length >= batch_size) { + batches.push(pendingBatch); + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + if (returnValue.state === "pending" || returnValue.state === "stopped") { + returnValue.state = "active"; + returnValue.emit("active"); + } + startNextBatch(); + } + } + function abortReplication(reason, err) { + if (replicationCompleted) { + return; + } + if (!err.message) { + err.message = reason; + } + result.ok = false; + result.status = "aborting"; + batches = []; + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + completeReplication(err); + } + function completeReplication(fatalError) { + if (replicationCompleted) { + return; + } + if (returnValue.cancelled) { + result.status = "cancelled"; + if (writingCheckpoint) { + return; + } + } + result.status = result.status || "complete"; + result.end_time = new Date().toISOString(); + result.last_seq = last_seq; + replicationCompleted = true; + src.activeTasks.remove(taskId, fatalError); + if (fatalError) { + fatalError = createError(fatalError); + fatalError.result = result; + var errorName = (fatalError.name || "").toLowerCase(); + if (errorName === "unauthorized" || errorName === "forbidden") { + returnValue.emit("error", fatalError); + returnValue.removeAllListeners(); + } else { + backOff(opts, returnValue, fatalError, function() { + replicate(src, target, opts, returnValue); + }); + } + } else { + returnValue.emit("complete", result); + returnValue.removeAllListeners(); + } + } + function onChange(change, pending, lastSeq) { + if (returnValue.cancelled) { + return completeReplication(); + } + if (typeof pending === "number") { + pendingBatch.pending = pending; + } + var filter2 = filterChange(opts)(change); + if (!filter2) { + var task = src.activeTasks.get(taskId); + if (task) { + var completed = task.completed_items || 0; + src.activeTasks.update(taskId, { completed_items: ++completed }); + } + return; + } + pendingBatch.seq = change.seq || lastSeq; + pendingBatch.changes.push(change); + returnValue.emit("checkpoint", { "pending_batch": pendingBatch.seq }); + (0, import_immediate.default)(function() { + processPendingBatch(batches.length === 0 && changesOpts.live); + }); + } + function onChangesComplete(changes3) { + changesPending = false; + if (returnValue.cancelled) { + return completeReplication(); + } + if (changes3.results.length > 0) { + changesOpts.since = changes3.results[changes3.results.length - 1].seq; + getChanges(); + processPendingBatch(true); + } else { + var complete = function() { + if (continuous) { + changesOpts.live = true; + getChanges(); + } else { + changesCompleted = true; + } + processPendingBatch(true); + }; + if (!currentBatch && changes3.results.length === 0) { + writingCheckpoint = true; + checkpointer.writeCheckpoint( + changes3.last_seq, + session + ).then(function() { + writingCheckpoint = false; + result.last_seq = last_seq = changes3.last_seq; + if (returnValue.cancelled) { + completeReplication(); + throw new Error("cancelled"); + } else { + complete(); + } + }).catch(onCheckpointError); + } else { + complete(); + } + } + } + function onChangesError(err) { + changesPending = false; + if (returnValue.cancelled) { + return completeReplication(); + } + abortReplication("changes rejected", err); + } + function getChanges() { + if (!(!changesPending && !changesCompleted && batches.length < batches_limit)) { + return; + } + changesPending = true; + function abortChanges() { + changes3.cancel(); + } + function removeListener() { + returnValue.removeListener("cancel", abortChanges); + } + if (returnValue._changes) { + returnValue.removeListener("cancel", returnValue._abortChanges); + returnValue._changes.cancel(); + } + returnValue.once("cancel", abortChanges); + var changes3 = src.changes(changesOpts).on("change", onChange); + changes3.then(removeListener, removeListener); + changes3.then(onChangesComplete).catch(onChangesError); + if (opts.retry) { + returnValue._changes = changes3; + returnValue._abortChanges = abortChanges; + } + } + function createTask(checkpoint) { + return src.info().then(function(info2) { + var total_items = typeof opts.since === "undefined" ? parseInt(info2.update_seq, 10) - parseInt(checkpoint, 10) : parseInt(info2.update_seq, 10); + taskId = src.activeTasks.add({ + name: `${continuous ? "continuous " : ""}replication from ${info2.db_name}`, + total_items + }); + return checkpoint; + }); + } + function startChanges() { + initCheckpointer().then(function() { + if (returnValue.cancelled) { + completeReplication(); + return; + } + return checkpointer.getCheckpoint().then(createTask).then(function(checkpoint) { + last_seq = checkpoint; + initial_last_seq = checkpoint; + changesOpts = { + since: last_seq, + limit: batch_size, + batch_size, + style, + doc_ids, + selector, + return_docs: true + }; + if (opts.filter) { + if (typeof opts.filter !== "string") { + changesOpts.include_docs = true; + } else { + changesOpts.filter = opts.filter; + } + } + if ("heartbeat" in opts) { + changesOpts.heartbeat = opts.heartbeat; + } + if ("timeout" in opts) { + changesOpts.timeout = opts.timeout; + } + if (opts.query_params) { + changesOpts.query_params = opts.query_params; + } + if (opts.view) { + changesOpts.view = opts.view; + } + getChanges(); + }); + }).catch(function(err) { + abortReplication("getCheckpoint rejected with ", err); + }); + } + function onCheckpointError(err) { + writingCheckpoint = false; + abortReplication("writeCheckpoint completed with error", err); + } + if (returnValue.cancelled) { + completeReplication(); + return; + } + if (!returnValue._addedListeners) { + returnValue.once("cancel", completeReplication); + if (typeof opts.complete === "function") { + returnValue.once("error", opts.complete); + returnValue.once("complete", function(result2) { + opts.complete(null, result2); + }); + } + returnValue._addedListeners = true; + } + if (typeof opts.since === "undefined") { + startChanges(); + } else { + initCheckpointer().then(function() { + writingCheckpoint = true; + return checkpointer.writeCheckpoint(opts.since, session); + }).then(function() { + writingCheckpoint = false; + if (returnValue.cancelled) { + completeReplication(); + return; + } + last_seq = opts.since; + startChanges(); + }).catch(onCheckpointError); + } +} +var Replication = class extends import_events3.default { + constructor() { + super(); + this.cancelled = false; + this.state = "pending"; + const promise = new Promise((fulfill, reject) => { + this.once("complete", fulfill); + this.once("error", reject); + }); + this.then = function(resolve, reject) { + return promise.then(resolve, reject); + }; + this.catch = function(reject) { + return promise.catch(reject); + }; + this.catch(function() { + }); + } + cancel() { + this.cancelled = true; + this.state = "cancelled"; + this.emit("cancel"); + } + ready(src, target) { + if (this._readyCalled) { + return; + } + this._readyCalled = true; + const onDestroy2 = () => { + this.cancel(); + }; + src.once("destroyed", onDestroy2); + target.once("destroyed", onDestroy2); + function cleanup() { + src.removeListener("destroyed", onDestroy2); + target.removeListener("destroyed", onDestroy2); + } + this.once("complete", cleanup); + this.once("error", cleanup); + } +}; +function toPouch(db, opts) { + var PouchConstructor = opts.PouchConstructor; + if (typeof db === "string") { + return new PouchConstructor(db, opts); + } else { + return db; + } +} +function replicateWrapper(src, target, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + if (typeof opts === "undefined") { + opts = {}; + } + if (opts.doc_ids && !Array.isArray(opts.doc_ids)) { + throw createError( + BAD_REQUEST, + "`doc_ids` filter parameter is not a list." + ); + } + opts.complete = callback; + opts = clone(opts); + opts.continuous = opts.continuous || opts.live; + opts.retry = "retry" in opts ? opts.retry : false; + opts.PouchConstructor = opts.PouchConstructor || this; + var replicateRet = new Replication(opts); + var srcPouch = toPouch(src, opts); + var targetPouch = toPouch(target, opts); + replicate(srcPouch, targetPouch, opts, replicateRet); + return replicateRet; +} +function sync(src, target, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + if (typeof opts === "undefined") { + opts = {}; + } + opts = clone(opts); + opts.PouchConstructor = opts.PouchConstructor || this; + src = toPouch(src, opts); + target = toPouch(target, opts); + return new Sync(src, target, opts, callback); +} +var Sync = class extends import_events3.default { + constructor(src, target, opts, callback) { + super(); + this.canceled = false; + const optsPush = opts.push ? assign$2({}, opts, opts.push) : opts; + const optsPull = opts.pull ? assign$2({}, opts, opts.pull) : opts; + this.push = replicateWrapper(src, target, optsPush); + this.pull = replicateWrapper(target, src, optsPull); + this.pushPaused = true; + this.pullPaused = true; + const pullChange = (change) => { + this.emit("change", { + direction: "pull", + change + }); + }; + const pushChange = (change) => { + this.emit("change", { + direction: "push", + change + }); + }; + const pushDenied = (doc) => { + this.emit("denied", { + direction: "push", + doc + }); + }; + const pullDenied = (doc) => { + this.emit("denied", { + direction: "pull", + doc + }); + }; + const pushPaused = () => { + this.pushPaused = true; + if (this.pullPaused) { + this.emit("paused"); + } + }; + const pullPaused = () => { + this.pullPaused = true; + if (this.pushPaused) { + this.emit("paused"); + } + }; + const pushActive = () => { + this.pushPaused = false; + if (this.pullPaused) { + this.emit("active", { + direction: "push" + }); + } + }; + const pullActive = () => { + this.pullPaused = false; + if (this.pushPaused) { + this.emit("active", { + direction: "pull" + }); + } + }; + let removed = {}; + const removeAll = (type) => { + return (event, func) => { + const isChange = event === "change" && (func === pullChange || func === pushChange); + const isDenied = event === "denied" && (func === pullDenied || func === pushDenied); + const isPaused = event === "paused" && (func === pullPaused || func === pushPaused); + const isActive = event === "active" && (func === pullActive || func === pushActive); + if (isChange || isDenied || isPaused || isActive) { + if (!(event in removed)) { + removed[event] = {}; + } + removed[event][type] = true; + if (Object.keys(removed[event]).length === 2) { + this.removeAllListeners(event); + } + } + }; + }; + if (opts.live) { + this.push.on("complete", this.pull.cancel.bind(this.pull)); + this.pull.on("complete", this.push.cancel.bind(this.push)); + } + function addOneListener(ee, event, listener) { + if (ee.listeners(event).indexOf(listener) == -1) { + ee.on(event, listener); + } + } + this.on("newListener", function(event) { + if (event === "change") { + addOneListener(this.pull, "change", pullChange); + addOneListener(this.push, "change", pushChange); + } else if (event === "denied") { + addOneListener(this.pull, "denied", pullDenied); + addOneListener(this.push, "denied", pushDenied); + } else if (event === "active") { + addOneListener(this.pull, "active", pullActive); + addOneListener(this.push, "active", pushActive); + } else if (event === "paused") { + addOneListener(this.pull, "paused", pullPaused); + addOneListener(this.push, "paused", pushPaused); + } + }); + this.on("removeListener", function(event) { + if (event === "change") { + this.pull.removeListener("change", pullChange); + this.push.removeListener("change", pushChange); + } else if (event === "denied") { + this.pull.removeListener("denied", pullDenied); + this.push.removeListener("denied", pushDenied); + } else if (event === "active") { + this.pull.removeListener("active", pullActive); + this.push.removeListener("active", pushActive); + } else if (event === "paused") { + this.pull.removeListener("paused", pullPaused); + this.push.removeListener("paused", pushPaused); + } + }); + this.pull.on("removeListener", removeAll("pull")); + this.push.on("removeListener", removeAll("push")); + const promise = Promise.all([ + this.push, + this.pull + ]).then((resp) => { + const out = { + push: resp[0], + pull: resp[1] + }; + this.emit("complete", out); + if (callback) { + callback(null, out); + } + this.removeAllListeners(); + return out; + }, (err) => { + this.cancel(); + if (callback) { + callback(err); + } else { + this.emit("error", err); + } + this.removeAllListeners(); + if (callback) { + throw err; + } + }); + this.then = function(success, err) { + return promise.then(success, err); + }; + this.catch = function(err) { + return promise.catch(err); + }; + } + cancel() { + if (!this.canceled) { + this.canceled = true; + this.push.cancel(); + this.pull.cancel(); + } + } +}; +function replication(PouchDB2) { + PouchDB2.replicate = replicateWrapper; + PouchDB2.sync = sync; + Object.defineProperty(PouchDB2.prototype, "replicate", { + get: function() { + var self2 = this; + if (typeof this.replicateMethods === "undefined") { + this.replicateMethods = { + from: function(other, opts, callback) { + return self2.constructor.replicate(other, self2, opts, callback); + }, + to: function(other, opts, callback) { + return self2.constructor.replicate(self2, other, opts, callback); + } + }; + } + return this.replicateMethods; + } + }); + PouchDB2.prototype.sync = function(dbName, opts, callback) { + return this.constructor.sync(this, dbName, opts, callback); + }; +} +var index_es_default8 = replication; + +// node_modules/pouchdb-find/lib/index-browser.es.js +function massageCreateIndexRequest(requestDef) { + requestDef = clone(requestDef); + if (!requestDef.index) { + requestDef.index = {}; + } + ["type", "name", "ddoc"].forEach(function(key) { + if (requestDef.index[key]) { + requestDef[key] = requestDef.index[key]; + delete requestDef.index[key]; + } + }); + if (requestDef.fields) { + requestDef.index.fields = requestDef.fields; + delete requestDef.fields; + } + if (!requestDef.type) { + requestDef.type = "json"; + } + return requestDef; +} +function checkFieldValueType(name, value, isHttp) { + var message = ""; + var received = value; + var addReceived = true; + if (["$in", "$nin", "$or", "$and", "$mod", "$nor", "$all"].indexOf(name) !== -1) { + if (!Array.isArray(value)) { + message = "Query operator " + name + " must be an array."; + } + } + if (["$not", "$elemMatch", "$allMatch"].indexOf(name) !== -1) { + if (!(!Array.isArray(value) && typeof value === "object" && value !== null)) { + message = "Query operator " + name + " must be an object."; + } + } + if (name === "$mod" && Array.isArray(value)) { + if (value.length !== 2) { + message = "Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers."; + } else { + var divisor = value[0]; + var mod = value[1]; + if (divisor === 0) { + message = "Query operator $mod's divisor cannot be 0, cannot divide by zero."; + addReceived = false; + } + if (typeof divisor !== "number" || parseInt(divisor, 10) !== divisor) { + message = "Query operator $mod's divisor is not an integer."; + received = divisor; + } + if (parseInt(mod, 10) !== mod) { + message = "Query operator $mod's remainder is not an integer."; + received = mod; + } + } + } + if (name === "$exists") { + if (typeof value !== "boolean") { + message = "Query operator $exists must be a boolean."; + } + } + if (name === "$type") { + var allowed = ["null", "boolean", "number", "string", "array", "object"]; + var allowedStr = '"' + allowed.slice(0, allowed.length - 1).join('", "') + '", or "' + allowed[allowed.length - 1] + '"'; + if (typeof value !== "string") { + message = "Query operator $type must be a string. Supported values: " + allowedStr + "."; + } else if (allowed.indexOf(value) == -1) { + message = "Query operator $type must be a string. Supported values: " + allowedStr + "."; + } + } + if (name === "$size") { + if (parseInt(value, 10) !== value) { + message = "Query operator $size must be a integer."; + } + } + if (name === "$regex") { + if (typeof value !== "string") { + if (isHttp) { + message = "Query operator $regex must be a string."; + } else if (!(value instanceof RegExp)) { + message = "Query operator $regex must be a string or an instance of a javascript regular expression."; + } + } + } + if (message) { + if (addReceived) { + var type = received === null ? " " : Array.isArray(received) ? " array" : " " + typeof received; + var receivedStr = typeof received === "object" && received !== null ? JSON.stringify(received, null, " ") : received; + message += " Received" + type + ": " + receivedStr; + } + throw new Error(message); + } +} +var requireValidation = ["$all", "$allMatch", "$and", "$elemMatch", "$exists", "$in", "$mod", "$nin", "$nor", "$not", "$or", "$regex", "$size", "$type"]; +var arrayTypeComparisonOperators = ["$in", "$nin", "$mod", "$all"]; +var equalityOperators = ["$eq", "$gt", "$gte", "$lt", "$lte"]; +function validateSelector(input, isHttp) { + if (Array.isArray(input)) { + for (var entry of input) { + if (typeof entry === "object" && value !== null) { + validateSelector(entry, isHttp); + } + } + } else { + var fields = Object.keys(input); + for (var i = 0; i < fields.length; i++) { + var key = fields[i]; + var value = input[key]; + if (requireValidation.indexOf(key) !== -1) { + checkFieldValueType(key, value, isHttp); + } + if (equalityOperators.indexOf(key) !== -1) { + continue; + } + if (arrayTypeComparisonOperators.indexOf(key) !== -1) { + continue; + } + if (typeof value === "object" && value !== null) { + validateSelector(value, isHttp); + } + } + } +} +function dbFetch(db, path, opts, callback) { + var status, ok; + opts.headers = new h({ "Content-type": "application/json" }); + db.fetch(path, opts).then(function(response) { + status = response.status; + ok = response.ok; + return response.json(); + }).then(function(json) { + if (!ok) { + json.status = status; + var err = generateErrorFromResponse(json); + callback(err); + } else { + callback(null, json); + } + }).catch(callback); +} +function createIndex(db, requestDef, callback) { + requestDef = massageCreateIndexRequest(requestDef); + dbFetch(db, "_index", { + method: "POST", + body: JSON.stringify(requestDef) + }, callback); +} +function find(db, requestDef, callback) { + validateSelector(requestDef.selector, true); + dbFetch(db, "_find", { + method: "POST", + body: JSON.stringify(requestDef) + }, callback); +} +function explain(db, requestDef, callback) { + dbFetch(db, "_explain", { + method: "POST", + body: JSON.stringify(requestDef) + }, callback); +} +function getIndexes(db, callback) { + dbFetch(db, "_index", { + method: "GET" + }, callback); +} +function deleteIndex(db, indexDef, callback) { + var ddoc = indexDef.ddoc; + var type = indexDef.type || "json"; + var name = indexDef.name; + if (!ddoc) { + return callback(new Error("you must provide an index's ddoc")); + } + if (!name) { + return callback(new Error("you must provide an index's name")); + } + var url = "_index/" + [ddoc, type, name].map(encodeURIComponent).join("/"); + dbFetch(db, url, { method: "DELETE" }, callback); +} +function callbackify2(fun) { + return function(...args) { + var cb = args.pop(); + var promise = fun.apply(this, args); + promisedCallback2(promise, cb); + return promise; + }; +} +function promisedCallback2(promise, callback) { + promise.then(function(res2) { + (0, import_immediate.default)(function() { + callback(null, res2); + }); + }, function(reason) { + (0, import_immediate.default)(function() { + callback(reason); + }); + }); + return promise; +} +var flatten2 = function(...args) { + var res2 = []; + for (var i = 0, len = args.length; i < len; i++) { + var subArr = args[i]; + if (Array.isArray(subArr)) { + res2 = res2.concat(flatten2.apply(null, subArr)); + } else { + res2.push(subArr); + } + } + return res2; +}; +function mergeObjects(arr) { + var res2 = {}; + for (var i = 0, len = arr.length; i < len; i++) { + res2 = assign$2(res2, arr[i]); + } + return res2; +} +function pick2(obj, arr) { + var res2 = {}; + for (var i = 0, len = arr.length; i < len; i++) { + var parsedField = parseField(arr[i]); + var value = getFieldFromDoc(obj, parsedField); + if (typeof value !== "undefined") { + setFieldInDoc(res2, parsedField, value); + } + } + return res2; +} +function oneArrayIsSubArrayOfOther(left, right) { + for (var i = 0, len = Math.min(left.length, right.length); i < len; i++) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} +function oneArrayIsStrictSubArrayOfOther(left, right) { + if (left.length > right.length) { + return false; + } + return oneArrayIsSubArrayOfOther(left, right); +} +function oneSetIsSubArrayOfOther(left, right) { + left = left.slice(); + for (var i = 0, len = right.length; i < len; i++) { + var field = right[i]; + if (!left.length) { + break; + } + var leftIdx = left.indexOf(field); + if (leftIdx === -1) { + return false; + } else { + left.splice(leftIdx, 1); + } + } + return true; +} +function arrayToObject(arr) { + var res2 = {}; + for (var i = 0, len = arr.length; i < len; i++) { + res2[arr[i]] = true; + } + return res2; +} +function max(arr, fun) { + var max2 = null; + var maxScore = -1; + for (var i = 0, len = arr.length; i < len; i++) { + var element2 = arr[i]; + var score = fun(element2); + if (score > maxScore) { + maxScore = score; + max2 = element2; + } + } + return max2; +} +function arrayEquals(arr1, arr2) { + if (arr1.length !== arr2.length) { + return false; + } + for (var i = 0, len = arr1.length; i < len; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} +function uniq2(arr) { + var obj = {}; + for (var i = 0; i < arr.length; i++) { + obj["$" + arr[i]] = true; + } + return Object.keys(obj).map(function(key) { + return key.substring(1); + }); +} +function createDeepMultiMapper(fields, emit, selector) { + return function(doc) { + if (selector && !matchesSelector(doc, selector)) { + return; + } + var toEmit = []; + for (var i = 0, iLen = fields.length; i < iLen; i++) { + var parsedField = parseField(fields[i]); + var value = doc; + for (var j = 0, jLen = parsedField.length; j < jLen; j++) { + var key = parsedField[j]; + value = value[key]; + if (typeof value === "undefined") { + return; + } + } + toEmit.push(value); + } + emit(toEmit); + }; +} +function createDeepSingleMapper(field, emit, selector) { + var parsedField = parseField(field); + return function(doc) { + if (selector && !matchesSelector(doc, selector)) { + return; + } + var value = doc; + for (var i = 0, len = parsedField.length; i < len; i++) { + var key = parsedField[i]; + value = value[key]; + if (typeof value === "undefined") { + return; + } + } + emit(value); + }; +} +function createShallowSingleMapper(field, emit, selector) { + return function(doc) { + if (selector && !matchesSelector(doc, selector)) { + return; + } + emit(doc[field]); + }; +} +function createShallowMultiMapper(fields, emit, selector) { + return function(doc) { + if (selector && !matchesSelector(doc, selector)) { + return; + } + var toEmit = []; + for (var i = 0, len = fields.length; i < len; i++) { + toEmit.push(doc[fields[i]]); + } + emit(toEmit); + }; +} +function checkShallow(fields) { + for (var i = 0, len = fields.length; i < len; i++) { + var field = fields[i]; + if (field.indexOf(".") !== -1) { + return false; + } + } + return true; +} +function createMapper(fields, emit, selector) { + var isShallow = checkShallow(fields); + var isSingle = fields.length === 1; + if (isShallow) { + if (isSingle) { + return createShallowSingleMapper(fields[0], emit, selector); + } else { + return createShallowMultiMapper(fields, emit, selector); + } + } else { + if (isSingle) { + return createDeepSingleMapper(fields[0], emit, selector); + } else { + return createDeepMultiMapper(fields, emit, selector); + } + } +} +function mapper2(mapFunDef, emit) { + const fields = Object.keys(mapFunDef.fields); + const partialSelector = mapFunDef.partial_filter_selector; + return createMapper(fields, emit, partialSelector); +} +function reducer2() { + throw new Error("reduce not supported"); +} +function ddocValidator2(ddoc, viewName) { + var view = ddoc.views[viewName]; + if (!view.map || !view.map.fields) { + throw new Error("ddoc " + ddoc._id + " with view " + viewName + " doesn't have map.fields defined. maybe it wasn't created by this plugin?"); + } +} +var abstractMapper = index_es_default5( + "indexes", + mapper2, + reducer2, + ddocValidator2 +); +function abstractMapper$1(db) { + if (db._customFindAbstractMapper) { + return { + query: function addQueryFallback(signature, opts) { + var fallback = abstractMapper.query.bind(this); + return db._customFindAbstractMapper.query.call(this, signature, opts, fallback); + }, + viewCleanup: function addViewCleanupFallback() { + var fallback = abstractMapper.viewCleanup.bind(this); + return db._customFindAbstractMapper.viewCleanup.call(this, fallback); + } + }; + } + return abstractMapper; +} +function massageSort(sort) { + if (!Array.isArray(sort)) { + throw new Error("invalid sort json - should be an array"); + } + return sort.map(function(sorting) { + if (typeof sorting === "string") { + var obj = {}; + obj[sorting] = "asc"; + return obj; + } else { + return sorting; + } + }); +} +function massageUseIndex(useIndex) { + var cleanedUseIndex = []; + if (typeof useIndex === "string") { + cleanedUseIndex.push(useIndex); + } else { + cleanedUseIndex = useIndex; + } + return cleanedUseIndex.map(function(name) { + return name.replace("_design/", ""); + }); +} +function massageIndexDef(indexDef) { + indexDef.fields = indexDef.fields.map(function(field) { + if (typeof field === "string") { + var obj = {}; + obj[field] = "asc"; + return obj; + } + return field; + }); + if (indexDef.partial_filter_selector) { + indexDef.partial_filter_selector = massageSelector( + indexDef.partial_filter_selector + ); + } + return indexDef; +} +function getKeyFromDoc(doc, index5) { + var res2 = []; + for (var i = 0; i < index5.def.fields.length; i++) { + var field = getKey(index5.def.fields[i]); + res2.push(getFieldFromDoc(doc, parseField(field))); + } + return res2; +} +function filterInclusiveStart(rows, targetValue, index5) { + var indexFields = index5.def.fields; + for (var i = 0, len = rows.length; i < len; i++) { + var row = rows[i]; + var docKey = getKeyFromDoc(row.doc, index5); + if (indexFields.length === 1) { + docKey = docKey[0]; + } else { + while (docKey.length > targetValue.length) { + docKey.pop(); + } + } + if (Math.abs(collate(docKey, targetValue)) > 0) { + break; + } + } + return i > 0 ? rows.slice(i) : rows; +} +function reverseOptions(opts) { + var newOpts = clone(opts); + delete newOpts.startkey; + delete newOpts.endkey; + delete newOpts.inclusive_start; + delete newOpts.inclusive_end; + if ("endkey" in opts) { + newOpts.startkey = opts.endkey; + } + if ("startkey" in opts) { + newOpts.endkey = opts.startkey; + } + if ("inclusive_start" in opts) { + newOpts.inclusive_end = opts.inclusive_start; + } + if ("inclusive_end" in opts) { + newOpts.inclusive_start = opts.inclusive_end; + } + return newOpts; +} +function validateIndex(index5) { + var ascFields = index5.fields.filter(function(field) { + return getValue(field) === "asc"; + }); + if (ascFields.length !== 0 && ascFields.length !== index5.fields.length) { + throw new Error("unsupported mixed sorting"); + } +} +function validateSort(requestDef, index5) { + if (index5.defaultUsed && requestDef.sort) { + var noneIdSorts = requestDef.sort.filter(function(sortItem) { + return Object.keys(sortItem)[0] !== "_id"; + }).map(function(sortItem) { + return Object.keys(sortItem)[0]; + }); + if (noneIdSorts.length > 0) { + throw new Error('Cannot sort on field(s) "' + noneIdSorts.join(",") + '" when using the default index'); + } + } + if (index5.defaultUsed) { + return; + } +} +function validateFindRequest(requestDef) { + if (typeof requestDef.selector !== "object") { + throw new Error("you must provide a selector when you find()"); + } +} +function getUserFields(selector, sort) { + var selectorFields = Object.keys(selector); + var sortFields = sort ? sort.map(getKey) : []; + var userFields; + if (selectorFields.length >= sortFields.length) { + userFields = selectorFields; + } else { + userFields = sortFields; + } + if (sortFields.length === 0) { + return { + fields: userFields + }; + } + userFields = userFields.sort(function(left, right) { + var leftIdx = sortFields.indexOf(left); + if (leftIdx === -1) { + leftIdx = Number.MAX_VALUE; + } + var rightIdx = sortFields.indexOf(right); + if (rightIdx === -1) { + rightIdx = Number.MAX_VALUE; + } + return leftIdx < rightIdx ? -1 : leftIdx > rightIdx ? 1 : 0; + }); + return { + fields: userFields, + sortOrder: sort.map(getKey) + }; +} +function createIndex$1(db, requestDef) { + requestDef = massageCreateIndexRequest(requestDef); + var originalIndexDef = clone(requestDef.index); + requestDef.index = massageIndexDef(requestDef.index); + validateIndex(requestDef.index); + var md5; + function getMd5() { + return md5 || (md5 = stringMd5(JSON.stringify(requestDef))); + } + var viewName = requestDef.name || "idx-" + getMd5(); + var ddocName = requestDef.ddoc || "idx-" + getMd5(); + var ddocId = "_design/" + ddocName; + var hasInvalidLanguage = false; + var viewExists = false; + function updateDdoc(doc) { + if (doc._rev && doc.language !== "query") { + hasInvalidLanguage = true; + } + doc.language = "query"; + doc.views = doc.views || {}; + viewExists = !!doc.views[viewName]; + if (viewExists) { + return false; + } + doc.views[viewName] = { + map: { + fields: mergeObjects(requestDef.index.fields), + partial_filter_selector: requestDef.index.partial_filter_selector + }, + reduce: "_count", + options: { + def: originalIndexDef + } + }; + return doc; + } + db.constructor.emit("debug", ["find", "creating index", ddocId]); + return upsert(db, ddocId, updateDdoc).then(function() { + if (hasInvalidLanguage) { + throw new Error('invalid language for ddoc with id "' + ddocId + '" (should be "query")'); + } + }).then(function() { + var signature = ddocName + "/" + viewName; + return abstractMapper$1(db).query.call(db, signature, { + limit: 0, + reduce: false + }).then(function() { + return { + id: ddocId, + name: viewName, + result: viewExists ? "exists" : "created" + }; + }); + }); +} +function getIndexes$1(db) { + return db.allDocs({ + startkey: "_design/", + endkey: "_design/\uFFFF", + include_docs: true + }).then(function(allDocsRes) { + var res2 = { + indexes: [{ + ddoc: null, + name: "_all_docs", + type: "special", + def: { + fields: [{ _id: "asc" }] + } + }] + }; + res2.indexes = flatten2(res2.indexes, allDocsRes.rows.filter(function(row) { + return row.doc.language === "query"; + }).map(function(row) { + var viewNames = row.doc.views !== void 0 ? Object.keys(row.doc.views) : []; + return viewNames.map(function(viewName) { + var view = row.doc.views[viewName]; + return { + ddoc: row.id, + name: viewName, + type: "json", + def: massageIndexDef(view.options.def) + }; + }); + })); + res2.indexes.sort(function(left, right) { + return compare(left.name, right.name); + }); + res2.total_rows = res2.indexes.length; + return res2; + }); +} +var COLLATE_LO = null; +var COLLATE_HI = { "\uFFFF": {} }; +var SHORT_CIRCUIT_QUERY = { + queryOpts: { limit: 0, startkey: COLLATE_HI, endkey: COLLATE_LO }, + inMemoryFields: [] +}; +function checkFieldInIndex(index5, field) { + var indexFields = index5.def.fields.map(getKey); + for (var i = 0, len = indexFields.length; i < len; i++) { + var indexField = indexFields[i]; + if (field === indexField) { + return true; + } + } + return false; +} +function userOperatorLosesPrecision(selector, field) { + var matcher = selector[field]; + var userOperator = getKey(matcher); + return userOperator !== "$eq"; +} +function sortFieldsByIndex(userFields, index5) { + var indexFields = index5.def.fields.map(getKey); + return userFields.slice().sort(function(a2, b) { + var aIdx = indexFields.indexOf(a2); + var bIdx = indexFields.indexOf(b); + if (aIdx === -1) { + aIdx = Number.MAX_VALUE; + } + if (bIdx === -1) { + bIdx = Number.MAX_VALUE; + } + return compare(aIdx, bIdx); + }); +} +function getBasicInMemoryFields(index5, selector, userFields) { + userFields = sortFieldsByIndex(userFields, index5); + var needToFilterInMemory = false; + for (var i = 0, len = userFields.length; i < len; i++) { + var field = userFields[i]; + if (needToFilterInMemory || !checkFieldInIndex(index5, field)) { + return userFields.slice(i); + } + if (i < len - 1 && userOperatorLosesPrecision(selector, field)) { + needToFilterInMemory = true; + } + } + return []; +} +function getInMemoryFieldsFromNe(selector) { + var fields = []; + Object.keys(selector).forEach(function(field) { + var matcher = selector[field]; + Object.keys(matcher).forEach(function(operator) { + if (operator === "$ne") { + fields.push(field); + } + }); + }); + return fields; +} +function getInMemoryFields(coreInMemoryFields, index5, selector, userFields) { + var result = flatten2( + coreInMemoryFields, + getBasicInMemoryFields(index5, selector, userFields), + getInMemoryFieldsFromNe(selector) + ); + return sortFieldsByIndex(uniq2(result), index5); +} +function checkIndexFieldsMatch(indexFields, sortOrder, fields) { + if (sortOrder) { + var sortMatches = oneArrayIsStrictSubArrayOfOther(sortOrder, indexFields); + var selectorMatches = oneArrayIsSubArrayOfOther(fields, indexFields); + return sortMatches && selectorMatches; + } + return oneSetIsSubArrayOfOther(fields, indexFields); +} +var logicalMatchers = ["$eq", "$gt", "$gte", "$lt", "$lte"]; +function isNonLogicalMatcher(matcher) { + return logicalMatchers.indexOf(matcher) === -1; +} +function checkFieldsLogicallySound(indexFields, selector) { + var firstField = indexFields[0]; + var matcher = selector[firstField]; + if (typeof matcher === "undefined") { + return true; + } + var isInvalidNe = Object.keys(matcher).length === 1 && getKey(matcher) === "$ne"; + return !isInvalidNe; +} +function checkIndexMatches(index5, sortOrder, fields, selector) { + var indexFields = index5.def.fields.map(getKey); + var fieldsMatch = checkIndexFieldsMatch(indexFields, sortOrder, fields); + if (!fieldsMatch) { + return false; + } + return checkFieldsLogicallySound(indexFields, selector); +} +function findMatchingIndexes(selector, userFields, sortOrder, indexes) { + return indexes.filter(function(index5) { + return checkIndexMatches(index5, sortOrder, userFields, selector); + }); +} +function findBestMatchingIndex(selector, userFields, sortOrder, indexes, useIndex) { + var matchingIndexes = findMatchingIndexes(selector, userFields, sortOrder, indexes); + if (matchingIndexes.length === 0) { + if (useIndex) { + throw { + error: "no_usable_index", + message: "There is no index available for this selector." + }; + } + var defaultIndex = indexes[0]; + defaultIndex.defaultUsed = true; + return defaultIndex; + } + if (matchingIndexes.length === 1 && !useIndex) { + return matchingIndexes[0]; + } + var userFieldsMap = arrayToObject(userFields); + function scoreIndex(index6) { + var indexFields = index6.def.fields.map(getKey); + var score = 0; + for (var i = 0, len = indexFields.length; i < len; i++) { + var indexField = indexFields[i]; + if (userFieldsMap[indexField]) { + score++; + } + } + return score; + } + if (useIndex) { + var useIndexDdoc = "_design/" + useIndex[0]; + var useIndexName = useIndex.length === 2 ? useIndex[1] : false; + var index5 = matchingIndexes.find(function(index6) { + if (useIndexName && index6.ddoc === useIndexDdoc && useIndexName === index6.name) { + return true; + } + if (index6.ddoc === useIndexDdoc) { + return true; + } + return false; + }); + if (!index5) { + throw { + error: "unknown_error", + message: "Could not find that index or could not use that index for the query" + }; + } + return index5; + } + return max(matchingIndexes, scoreIndex); +} +function getSingleFieldQueryOptsFor(userOperator, userValue) { + switch (userOperator) { + case "$eq": + return { key: userValue }; + case "$lte": + return { endkey: userValue }; + case "$gte": + return { startkey: userValue }; + case "$lt": + return { + endkey: userValue, + inclusive_end: false + }; + case "$gt": + return { + startkey: userValue, + inclusive_start: false + }; + } + return { + startkey: COLLATE_LO + }; +} +function getSingleFieldCoreQueryPlan(selector, index5) { + var field = getKey(index5.def.fields[0]); + var matcher = selector[field] || {}; + var inMemoryFields = []; + var userOperators = Object.keys(matcher); + var combinedOpts; + userOperators.forEach(function(userOperator) { + if (isNonLogicalMatcher(userOperator)) { + inMemoryFields.push(field); + } + var userValue = matcher[userOperator]; + var newQueryOpts = getSingleFieldQueryOptsFor(userOperator, userValue); + if (combinedOpts) { + combinedOpts = mergeObjects([combinedOpts, newQueryOpts]); + } else { + combinedOpts = newQueryOpts; + } + }); + return { + queryOpts: combinedOpts, + inMemoryFields + }; +} +function getMultiFieldCoreQueryPlan(userOperator, userValue) { + switch (userOperator) { + case "$eq": + return { + startkey: userValue, + endkey: userValue + }; + case "$lte": + return { + endkey: userValue + }; + case "$gte": + return { + startkey: userValue + }; + case "$lt": + return { + endkey: userValue, + inclusive_end: false + }; + case "$gt": + return { + startkey: userValue, + inclusive_start: false + }; + } +} +function getMultiFieldQueryOpts(selector, index5) { + var indexFields = index5.def.fields.map(getKey); + var inMemoryFields = []; + var startkey = []; + var endkey = []; + var inclusiveStart; + var inclusiveEnd; + function finish(i2) { + if (inclusiveStart !== false) { + startkey.push(COLLATE_LO); + } + if (inclusiveEnd !== false) { + endkey.push(COLLATE_HI); + } + inMemoryFields = indexFields.slice(i2); + } + for (var i = 0, len = indexFields.length; i < len; i++) { + var indexField = indexFields[i]; + var matcher = selector[indexField]; + if (!matcher || !Object.keys(matcher).length) { + finish(i); + break; + } else if (Object.keys(matcher).some(isNonLogicalMatcher)) { + finish(i); + break; + } else if (i > 0) { + var usingGtlt = "$gt" in matcher || "$gte" in matcher || "$lt" in matcher || "$lte" in matcher; + var previousKeys = Object.keys(selector[indexFields[i - 1]]); + var previousWasEq = arrayEquals(previousKeys, ["$eq"]); + var previousWasSame = arrayEquals(previousKeys, Object.keys(matcher)); + var gtltLostSpecificity = usingGtlt && !previousWasEq && !previousWasSame; + if (gtltLostSpecificity) { + finish(i); + break; + } + } + var userOperators = Object.keys(matcher); + var combinedOpts = null; + for (var j = 0; j < userOperators.length; j++) { + var userOperator = userOperators[j]; + var userValue = matcher[userOperator]; + var newOpts = getMultiFieldCoreQueryPlan(userOperator, userValue); + if (combinedOpts) { + combinedOpts = mergeObjects([combinedOpts, newOpts]); + } else { + combinedOpts = newOpts; + } + } + startkey.push("startkey" in combinedOpts ? combinedOpts.startkey : COLLATE_LO); + endkey.push("endkey" in combinedOpts ? combinedOpts.endkey : COLLATE_HI); + if ("inclusive_start" in combinedOpts) { + inclusiveStart = combinedOpts.inclusive_start; + } + if ("inclusive_end" in combinedOpts) { + inclusiveEnd = combinedOpts.inclusive_end; + } + } + var res2 = { + startkey, + endkey + }; + if (typeof inclusiveStart !== "undefined") { + res2.inclusive_start = inclusiveStart; + } + if (typeof inclusiveEnd !== "undefined") { + res2.inclusive_end = inclusiveEnd; + } + return { + queryOpts: res2, + inMemoryFields + }; +} +function shouldShortCircuit(selector) { + const values = Object.keys(selector).map(function(key) { + return selector[key]; + }); + return values.some(function(val) { + return typeof val === "object" && Object.keys(val).length === 0; + }); +} +function getDefaultQueryPlan(selector) { + return { + queryOpts: { startkey: null }, + inMemoryFields: [Object.keys(selector)] + }; +} +function getCoreQueryPlan(selector, index5) { + if (index5.defaultUsed) { + return getDefaultQueryPlan(selector, index5); + } + if (index5.def.fields.length === 1) { + return getSingleFieldCoreQueryPlan(selector, index5); + } + return getMultiFieldQueryOpts(selector, index5); +} +function planQuery(request, indexes) { + var selector = request.selector; + var sort = request.sort; + if (shouldShortCircuit(selector)) { + return assign$2({}, SHORT_CIRCUIT_QUERY, { index: indexes[0] }); + } + var userFieldsRes = getUserFields(selector, sort); + var userFields = userFieldsRes.fields; + var sortOrder = userFieldsRes.sortOrder; + var index5 = findBestMatchingIndex(selector, userFields, sortOrder, indexes, request.use_index); + var coreQueryPlan = getCoreQueryPlan(selector, index5); + var queryOpts = coreQueryPlan.queryOpts; + var coreInMemoryFields = coreQueryPlan.inMemoryFields; + var inMemoryFields = getInMemoryFields(coreInMemoryFields, index5, selector, userFields); + var res2 = { + queryOpts, + index: index5, + inMemoryFields + }; + return res2; +} +function indexToSignature(index5) { + return index5.ddoc.substring(8) + "/" + index5.name; +} +function doAllDocs(db, originalOpts) { + var opts = clone(originalOpts); + if (opts.descending) { + if ("endkey" in opts && typeof opts.endkey !== "string") { + opts.endkey = ""; + } + if ("startkey" in opts && typeof opts.startkey !== "string") { + opts.limit = 0; + } + } else { + if ("startkey" in opts && typeof opts.startkey !== "string") { + opts.startkey = ""; + } + if ("endkey" in opts && typeof opts.endkey !== "string") { + opts.limit = 0; + } + } + if ("key" in opts && typeof opts.key !== "string") { + opts.limit = 0; + } + if (opts.limit > 0 && opts.indexes_count) { + opts.original_limit = opts.limit; + opts.limit += opts.indexes_count; + } + return db.allDocs(opts).then(function(res2) { + res2.rows = res2.rows.filter(function(row) { + return !/^_design\//.test(row.id); + }); + if (opts.original_limit) { + opts.limit = opts.original_limit; + } + res2.rows = res2.rows.slice(0, opts.limit); + return res2; + }); +} +function find$1(db, requestDef, explain2) { + if (requestDef.selector) { + validateSelector(requestDef.selector, false); + requestDef.selector = massageSelector(requestDef.selector); + } + if (requestDef.sort) { + requestDef.sort = massageSort(requestDef.sort); + } + if (requestDef.use_index) { + requestDef.use_index = massageUseIndex(requestDef.use_index); + } + validateFindRequest(requestDef); + return getIndexes$1(db).then(function(getIndexesRes) { + db.constructor.emit("debug", ["find", "planning query", requestDef]); + var queryPlan = planQuery(requestDef, getIndexesRes.indexes); + db.constructor.emit("debug", ["find", "query plan", queryPlan]); + var indexToUse = queryPlan.index; + validateSort(requestDef, indexToUse); + var opts = assign$2({ + include_docs: true, + reduce: false, + indexes_count: getIndexesRes.total_rows + }, queryPlan.queryOpts); + if ("startkey" in opts && "endkey" in opts && collate(opts.startkey, opts.endkey) > 0) { + return { docs: [] }; + } + var isDescending = requestDef.sort && typeof requestDef.sort[0] !== "string" && getValue(requestDef.sort[0]) === "desc"; + if (isDescending) { + opts.descending = true; + opts = reverseOptions(opts); + } + if (!queryPlan.inMemoryFields.length) { + if ("limit" in requestDef) { + opts.limit = requestDef.limit; + } + if ("skip" in requestDef) { + opts.skip = requestDef.skip; + } + } + if (explain2) { + return Promise.resolve(queryPlan, opts); + } + return Promise.resolve().then(function() { + if (indexToUse.name === "_all_docs") { + return doAllDocs(db, opts); + } else { + var signature = indexToSignature(indexToUse); + return abstractMapper$1(db).query.call(db, signature, opts); + } + }).then(function(res2) { + if (opts.inclusive_start === false) { + res2.rows = filterInclusiveStart(res2.rows, opts.startkey, indexToUse); + } + if (queryPlan.inMemoryFields.length) { + res2.rows = filterInMemoryFields(res2.rows, requestDef, queryPlan.inMemoryFields); + } + var resp = { + docs: res2.rows.map(function(row) { + var doc = row.doc; + if (requestDef.fields) { + return pick2(doc, requestDef.fields); + } + return doc; + }) + }; + if (indexToUse.defaultUsed) { + resp.warning = "No matching index found, create an index to optimize query time."; + } + return resp; + }); + }); +} +function explain$1(db, requestDef) { + return find$1(db, requestDef, true).then(function(queryPlan) { + return { + dbname: db.name, + index: queryPlan.index, + selector: requestDef.selector, + range: { + start_key: queryPlan.queryOpts.startkey, + end_key: queryPlan.queryOpts.endkey + }, + opts: { + use_index: requestDef.use_index || [], + bookmark: "nil", + limit: requestDef.limit, + skip: requestDef.skip, + sort: requestDef.sort || {}, + fields: requestDef.fields, + conflicts: false, + r: [49] + }, + limit: requestDef.limit, + skip: requestDef.skip || 0, + fields: requestDef.fields + }; + }); +} +function deleteIndex$1(db, index5) { + if (!index5.ddoc) { + throw new Error("you must supply an index.ddoc when deleting"); + } + if (!index5.name) { + throw new Error("you must supply an index.name when deleting"); + } + var docId = index5.ddoc; + var viewName = index5.name; + function deltaFun(doc) { + if (Object.keys(doc.views).length === 1 && doc.views[viewName]) { + return { _id: docId, _deleted: true }; + } + delete doc.views[viewName]; + return doc; + } + return upsert(db, docId, deltaFun).then(function() { + return abstractMapper$1(db).viewCleanup.apply(db); + }).then(function() { + return { ok: true }; + }); +} +var createIndexAsCallback = callbackify2(createIndex$1); +var findAsCallback = callbackify2(find$1); +var explainAsCallback = callbackify2(explain$1); +var getIndexesAsCallback = callbackify2(getIndexes$1); +var deleteIndexAsCallback = callbackify2(deleteIndex$1); +var plugin = {}; +plugin.createIndex = toPromise(function(requestDef, callback) { + if (typeof requestDef !== "object") { + return callback(new Error("you must provide an index to create")); + } + var createIndex$$1 = isRemote(this) ? createIndex : createIndexAsCallback; + createIndex$$1(this, requestDef, callback); +}); +plugin.find = toPromise(function(requestDef, callback) { + if (typeof callback === "undefined") { + callback = requestDef; + requestDef = void 0; + } + if (typeof requestDef !== "object") { + return callback(new Error("you must provide search parameters to find()")); + } + var find$$1 = isRemote(this) ? find : findAsCallback; + find$$1(this, requestDef, callback); +}); +plugin.explain = toPromise(function(requestDef, callback) { + if (typeof callback === "undefined") { + callback = requestDef; + requestDef = void 0; + } + if (typeof requestDef !== "object") { + return callback(new Error("you must provide search parameters to explain()")); + } + var find$$1 = isRemote(this) ? explain : explainAsCallback; + find$$1(this, requestDef, callback); +}); +plugin.getIndexes = toPromise(function(callback) { + var getIndexes$$1 = isRemote(this) ? getIndexes : getIndexesAsCallback; + getIndexes$$1(this, callback); +}); +plugin.deleteIndex = toPromise(function(indexDef, callback) { + if (typeof indexDef !== "object") { + return callback(new Error("you must provide an index to delete")); + } + var deleteIndex$$1 = isRemote(this) ? deleteIndex : deleteIndexAsCallback; + deleteIndex$$1(this, indexDef, callback); +}); +var index_browser_es_default3 = plugin; + +// src/lib/src/pouchdb-browser.ts +var import_transform_pouch = __toESM(require_transform_pouch(), 1); +index_es_default.plugin(index_es_default2).plugin(index_es_default3).plugin(index_es_default4).plugin(index_browser_es_default2).plugin(index_es_default8).plugin(index_browser_es_default3).plugin(import_transform_pouch.default); + +// src/LogDisplayModal.ts +var LogDisplayModal = class extends import_obsidian.Modal { + constructor(app2, plugin2) { + super(app2); + this.plugin = plugin2; + } + 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.unsubscribe = logMessageStore.observe((e2) => { + let msg = ""; + for (const v of e2) { + msg += escapeStringToHTML(v) + "
    "; + } + this.logEl.innerHTML = msg; + }); + logMessageStore.invalidate(); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + if (this.unsubscribe) + this.unsubscribe(); + } +}; + +// src/ConflictResolveModal.ts +var import_diff_match_patch = __toESM(require_diff_match_patch(), 1); +var ConflictResolveModal = class extends import_obsidian.Modal { + constructor(app2, filename, diff, callback) { + super(app2); + this.result = diff; + this.callback = callback; + this.filename = filename; + } + onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "This document has conflicted changes." }); + contentEl.createEl("span", { text: this.filename }); + 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" }, (e2) => { + e2.addEventListener("click", async () => { + await this.callback(this.result.right.rev); + this.callback = null; + this.close(); + }); + }); + contentEl.createEl("button", { text: "Keep B" }, (e2) => { + e2.addEventListener("click", async () => { + await this.callback(this.result.left.rev); + this.callback = null; + this.close(); + }); + }); + contentEl.createEl("button", { text: "Concat both" }, (e2) => { + e2.addEventListener("click", async () => { + await this.callback(""); + this.callback = null; + this.close(); + }); + }); + contentEl.createEl("button", { text: "Not now" }, (e2) => { + e2.addEventListener("click", () => { + this.close(); + }); + }); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + if (this.callback != null) { + this.callback(null); + } + } +}; + +// src/lib/src/path.ts +function isValidFilenameInWidows(filename) { + const regex = /[\u0000-\u001f]|[\\":?<>|*#]/g; + if (regex.test(filename)) + return false; + const win = /(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi; + if (win.test(filename)) + return false; + return true; +} +function isValidFilenameInDarwin(filename) { + const regex = /[\u0000-\u001f]|[:]/g; + return !regex.test(filename); +} +function isValidFilenameInLinux(filename) { + const regex = /[\u0000-\u001f]/g; + return !regex.test(filename); +} +function isValidFilenameInAndroid(filename) { + const regex = /[\u0000-\u001f]|[\\":?<>|*#]/g; + return !regex.test(filename); +} +function path2id_base(filename) { + let x = filename; + if (x.startsWith("_")) + x = "/" + x; + return x; +} +function id2path_base(filename) { + return filename; +} +function shouldBeIgnored(filename) { + if (filename == FLAGMD_REDFLAG) { + return true; + } + if (filename == FLAGMD_REDFLAG2) { + return true; + } + if (filename == FLAGMD_REDFLAG3) { + return true; + } + if (filename.startsWith(PREFIXMD_LOGFILE)) { + return true; + } + return false; +} +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; + if (filename.endsWith(".canvas")) + return true; + return false; +} +function shouldSplitAsPlainText(filename) { + if (filename.endsWith(".md")) + return true; + if (filename.endsWith(".txt")) + return true; + if (filename.endsWith(".canvas")) + return true; + return false; +} + +// node_modules/svelte/internal/index.mjs +function noop() { +} +function run(fn) { + return fn(); +} +function blank_object() { + return /* @__PURE__ */ Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === "function"; +} +function safe_not_equal(a2, b) { + return a2 != a2 ? b == b : a2 !== b || (a2 && typeof a2 === "object" || typeof a2 === "function"); +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} +function null_to_empty(value) { + return value == null ? "" : value; +} +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); + return style.sheet; +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].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 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 = /* @__PURE__ */ new Set(); +var flushidx = 0; +function flush() { + if (flushidx !== 0) { + return; + } + const saved_component = current_component; + do { + try { + while (flushidx < dirty_components.length) { + const component = dirty_components[flushidx]; + flushidx++; + set_current_component(component); + update(component.$$); + } + } catch (e2) { + dirty_components.length = 0; + flushidx = 0; + throw e2; + } + set_current_component(null); + dirty_components.length = 0; + flushidx = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + 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 = /* @__PURE__ */ new Set(); +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function mount_component(component, target, anchor, customElement) { + const { fragment, after_update } = component.$$; + fragment && fragment.m(target, anchor); + if (!customElement) { + add_render_callback(() => { + const new_on_destroy = component.$$.on_mount.map(run).filter(is_function); + if (component.$$.on_destroy) { + component.$$.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, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[i / 31 | 0] |= 1 << i % 31; +} +function init2(component, options, instance3, create_fragment3, not_equal, props, append_styles2, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: [], + 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 = instance3 ? instance3(component, options.props || {}, (i, ret, ...rest) => { + const value = rest.length ? rest[0] : ret; + if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { + if (!$$.skip_bound && $$.bound[i]) + $$.bound[i](value); + if (ready) + make_dirty(component, i); + } + return ret; + }) : []; + $$.update(); + ready = true; + run_all($$.before_update); + $$.fragment = create_fragment3 ? create_fragment3($$.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) { + if (!is_function(callback)) { + return noop; + } + const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); + callbacks.push(callback); + return () => { + const index5 = callbacks.indexOf(callback); + if (index5 !== -1) + callbacks.splice(index5, 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) { + if (!is_function(callback)) { + return noop; + } + const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); + callbacks.push(callback); + return () => { + const index5 = callbacks.indexOf(callback); + if (index5 !== -1) + callbacks.splice(index5, 1); + }; + } + $set($$props) { + if (this.$$set && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +}; + +// src/lib/src/wrapper.ts +var WrappedNotice = class { + constructor(message, timeout) { + var _a; + let strMessage = ""; + if (message instanceof DocumentFragment) { + strMessage = (_a = message.textContent) != null ? _a : ""; + } else { + strMessage = message; + } + Logger(strMessage, LOG_LEVEL.NOTICE); + } + setMessage(message) { + var _a; + let strMessage = ""; + if (message instanceof DocumentFragment) { + strMessage = (_a = message.textContent) != null ? _a : ""; + } 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); +} + +// src/lib/src/semaphore.ts +function makeUniqueString() { + const randomStrSrc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + const temp = [...Array(30)].map(() => Math.floor(Math.random() * randomStrSrc.length)).map((e2) => randomStrSrc[e2]).join(""); + return `${Date.now()}-${temp}`; +} +function Semaphore(limit, onRelease) { + const _limit = limit; + let currentProcesses = 0; + let queue2 = []; + function execProcess() { + queue2 = queue2.filter((e2) => e2.state != "DONE"); + for (const queueItem2 of queue2) { + if (queueItem2.state != "NONE") + continue; + if (queueItem2.quantity + currentProcesses > _limit) { + break; + } + queueItem2.state = "RUNNING"; + currentProcesses += queueItem2.quantity; + if (queueItem2 == null ? void 0 : queueItem2.timer) { + clearTimeout(queueItem2.timer); + } + queueItem2.notify(true); + } + } + function release(key) { + const finishedTask = queue2.find((e2) => e2.key == key); + if (!finishedTask) { + throw new Error("Missing locked semaphore!"); + } + if (finishedTask.state == "RUNNING") { + currentProcesses -= finishedTask.quantity; + } + finishedTask.state = "DONE"; + if (onRelease) + onRelease(queue2.filter((e2) => e2.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((res2) => { + notify = (result) => { + if (result) { + res2(() => { + release(key); + }); + } else { + res2(false); + } + }; + }); + const notifier = { + key, + notify, + semaphoreStopper, + quantity, + memo, + state: "NONE" + }; + if (timeout) + notifier.timer = setTimeout(() => { + release(key); + notify(false); + }, timeout); + queue2.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 queue2; + } + }; +} + +// src/lib/src/lock.ts +var externalNotifier = () => { +}; +var notifyTimer = null; +function notifyLock() { + if (notifyTimer != null) { + clearTimeout(notifyTimer); + } + notifyTimer = setTimeout(() => { + externalNotifier(); + }, 100); +} +var Mutexes = {}; +function updateStore() { + const allLocks = [...Object.values(Mutexes).map((e2) => e2.peekQueues())].flat(); + lockStore.apply((v) => ({ + ...v, + count: allLocks.length, + pending: allLocks.filter((e2) => e2.state == "NONE").map((e2) => { + var _a; + return (_a = e2.memo) != null ? _a : ""; + }), + running: allLocks.filter((e2) => e2.state == "RUNNING").map((e2) => { + var _a; + return (_a = e2.memo) != null ? _a : ""; + }) + })); +} +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, (queue2) => { + if (queue2.length == 0) + semaphoreReleasedCount++; + }); + } + const timeout = ignoreWhenRunning ? 1 : 0; + const releaser = await Mutexes[key].tryAcquire(1, timeout, key); + updateStore(); + if (!releaser) + return null; + try { + return await proc(); + } finally { + releaser(); + notifyLock(); + updateStore(); + } +} + +// src/LiveSyncCommands.ts +var LiveSyncCommands = class { + get app() { + return this.plugin.app; + } + get settings() { + return this.plugin.settings; + } + get localDatabase() { + return this.plugin.localDatabase; + } + constructor(plugin2) { + this.plugin = plugin2; + } +}; + +// src/CmdPluginAndTheirSettings.ts +var PluginAndTheirSettings = class extends LiveSyncCommands { + constructor() { + super(...arguments); + this.pluginDialog = null; + this.periodicPluginSweepProcessor = new PeriodicProcessor(this.plugin, async () => await this.sweepPlugin(false)); + } + get deviceAndVaultName() { + return this.plugin.deviceAndVaultName; + } + showPluginSyncModal() { + if (this.pluginDialog != null) { + this.pluginDialog.open(); + } else { + this.pluginDialog = new PluginDialogModal(this.app, this.plugin); + this.pluginDialog.open(); + } + } + hidePluginSyncModal() { + if (this.pluginDialog != null) { + this.pluginDialog.close(); + this.pluginDialog = null; + } + } + onload() { + this.plugin.addCommand({ + id: "livesync-plugin-dialog", + name: "Show Plugins and their settings", + callback: () => { + this.showPluginSyncModal(); + } + }); + } + onunload() { + var _a; + this.hidePluginSyncModal(); + (_a = this.periodicPluginSweepProcessor) == null ? void 0 : _a.disable(); + } + parseReplicationResultItem(doc) { + if (isPluginMetadata(doc._id)) { + if (this.settings.notifyPluginOrSettingUpdated) { + this.triggerCheckPluginUpdate(); + return true; + } + } + return false; + } + async beforeReplicate(showMessage) { + if (this.settings.autoSweepPlugins) { + await this.sweepPlugin(showMessage); + } + } + async onResume() { + if (this.plugin.suspended) + return; + if (this.settings.autoSweepPlugins) { + await this.sweepPlugin(false); + } + this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? PERIODIC_PLUGIN_SWEEP * 1e3 : 0); + } + async onInitializeDatabase(showNotice) { + if (this.settings.usePluginSync) { + try { + Logger("Scanning plugins..."); + await this.sweepPlugin(showNotice); + Logger("Scanning plugins done"); + } catch (ex) { + Logger("Scanning plugins failed"); + Logger(ex, LOG_LEVEL.VERBOSE); + } + } + } + async realizeSettingSyncMode() { + var _a; + (_a = this.periodicPluginSweepProcessor) == null ? void 0 : _a.disable(); + if (this.plugin.suspended) + return; + if (this.settings.autoSweepPlugins) { + await this.sweepPlugin(false); + } + this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? PERIODIC_PLUGIN_SWEEP * 1e3 : 0); + } + triggerCheckPluginUpdate() { + (async () => await this.checkPluginUpdate())(); + } + 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 (e2) => await this.localDatabase.getDBEntry(e2.id)))).filter((e2) => e2 !== false).map((e2) => JSON.parse(getDocData(e2.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 checkPluginUpdate() { + var _a, _b; + if (!this.plugin.settings.usePluginSync) + return; + await this.sweepPlugin(false); + const { allPlugins, thisDevicePlugins } = await this.getPluginList(); + const arrPlugins = Object.values(allPlugins); + let updateFound = false; + for (const plugin2 of arrPlugins) { + const ownPlugin = thisDevicePlugins[plugin2.manifest.id]; + if (ownPlugin) { + const remoteVersion = versionNumberString2Number(plugin2.manifest.version); + const ownVersion = versionNumberString2Number(ownPlugin.manifest.version); + if (remoteVersion > ownVersion) { + updateFound = true; + } + if ((plugin2.mtime / 1e3 | 0) > (ownPlugin.mtime / 1e3 | 0) && ((_a = plugin2.dataJson) != null ? _a : "") != ((_b = ownPlugin.dataJson) != null ? _b : "")) { + updateFound = true; + } + } + } + if (updateFound) { + const fragment = createFragment((doc) => { + doc.createEl("a", null, (a2) => { + a2.text = "There're some new plugins or their settings"; + a2.addEventListener("click", () => this.showPluginSyncModal()); + }); + }); + NewNotice(fragment, 1e4); + } else { + Logger("Everything is up to date.", LOG_LEVEL.NOTICE); + } + } + async sweepPlugin(showMessage = false, specificPluginPath = "") { + var _a, _b; + if (!this.settings.usePluginSync) + return; + if (!this.localDatabase.isReady) + return; + const pl = this.app.plugins; + const manifests = Object.values(pl.manifests); + let specificPlugin = ""; + if (specificPluginPath != "") { + specificPlugin = (_b = (_a = manifests.find((e2) => e2.dir.endsWith("/" + specificPluginPath))) == null ? void 0 : _a.id) != null ? _b : ""; + } + 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}-${specificPlugin}`, + endkey: `ps:${this.deviceAndVaultName}-${specificPlugin}\u{10FFFF}`, + include_docs: true + }); + const procs = manifests.map( + async (m) => { + const pluginDataEntryID = `ps:${this.deviceAndVaultName}-${m.id}`; + try { + if (specificPlugin && m.id != specificPlugin) { + return; + } + Logger(`Reading plugin:${m.name}(${m.id})`, LOG_LEVEL.VERBOSE); + const path = (0, import_obsidian.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: pluginDataEntryID, + 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 (isDocContentSame(oldData.data, newData.data) && oldData.deleted == newData.deleted) { + Logger(`Nothing changed:${m.name}`); + return; + } + } + await this.localDatabase.putDBEntry(d); + Logger(`Plugin saved:${m.name}`, logLevel); + }); + } catch (ex) { + Logger(`Plugin save failed:${m.name}`, LOG_LEVEL.NOTICE); + } finally { + oldDocs.rows = oldDocs.rows.filter((e2) => e2.id != pluginDataEntryID); + } + } + ); + await Promise.all(procs); + const delDocs = oldDocs.rows.map((e2) => { + if (e2.doc.type == "newnote" || e2.doc.type == "plain") { + e2.doc.deleted = true; + if (this.settings.deleteMetadataOfDeletedFiles) { + e2.doc._deleted = true; + } + } else { + e2.doc._deleted = true; + } + return e2.doc; + }); + Logger(`Deleting old plugin:(${delDocs.length})`, LOG_LEVEL.VERBOSE); + await db.bulkDocs(delDocs); + Logger(`Scan plugin done.`, logLevel); + }); + } + async applyPluginData(plugin2) { + await runWithLock("plugin-" + plugin2.manifest.id, false, async () => { + const pluginTargetFolderPath = (0, import_obsidian.normalizePath)(plugin2.manifest.dir) + "/"; + const adapter = this.app.vault.adapter; + const stat = this.app.plugins.enabledPlugins.has(plugin2.manifest.id) == true; + if (stat) { + await this.app.plugins.unloadPlugin(plugin2.manifest.id); + Logger(`Unload plugin:${plugin2.manifest.id}`, LOG_LEVEL.NOTICE); + } + if (plugin2.dataJson) + await adapter.write(pluginTargetFolderPath + "data.json", plugin2.dataJson); + Logger("wrote:" + pluginTargetFolderPath + "data.json", LOG_LEVEL.NOTICE); + if (stat) { + await this.app.plugins.loadPlugin(plugin2.manifest.id); + Logger(`Load plugin:${plugin2.manifest.id}`, LOG_LEVEL.NOTICE); + } + }); + } + async applyPlugin(plugin2) { + await runWithLock("plugin-" + plugin2.manifest.id, false, async () => { + const stat = this.app.plugins.enabledPlugins.has(plugin2.manifest.id) == true; + if (stat) { + await this.app.plugins.unloadPlugin(plugin2.manifest.id); + Logger(`Unload plugin:${plugin2.manifest.id}`, LOG_LEVEL.NOTICE); + } + const pluginTargetFolderPath = (0, import_obsidian.normalizePath)(plugin2.manifest.dir) + "/"; + const adapter = this.app.vault.adapter; + if (await adapter.exists(pluginTargetFolderPath) === false) { + await adapter.mkdir(pluginTargetFolderPath); + } + await adapter.write(pluginTargetFolderPath + "main.js", plugin2.mainJs); + await adapter.write(pluginTargetFolderPath + "manifest.json", plugin2.manifestJson); + if (plugin2.styleCss) + await adapter.write(pluginTargetFolderPath + "styles.css", plugin2.styleCss); + if (stat) { + await this.app.plugins.loadPlugin(plugin2.manifest.id); + Logger(`Load plugin:${plugin2.manifest.id}`, LOG_LEVEL.NOTICE); + } + }); + } +}; + +// 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, i) { + const child_ctx = ctx.slice(); + child_ctx[26] = list[i][0]; + child_ctx[27] = list[i][1]; + return child_ctx; +} +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[0] = list[i]; + return child_ctx; +} +function create_else_block(ctx) { + let each_1_anchor; + let each_value = ctx[2]; + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); + } + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(target, anchor); + } + insert(target, each_1_anchor, anchor); + }, + p(ctx2, dirty) { + if (dirty[0] & 204) { + each_value = ctx2[2]; + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].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[0] & 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 t2; + return { + c() { + t2 = text("-"); + }, + m(target, anchor) { + insert(target, t2, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(t2); + } + }; +} +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[0] & 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 t2; + return { + c() { + t2 = text("-"); + }, + m(target, anchor) { + insert(target, t2, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(t2); + } + }; +} +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 t2; + 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, -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, -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"); + t2 = 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, t2); + 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[0] & 4 && t0_value !== (t0_value = ctx2[0].manifest.name + "")) + set_data(t0, t0_value); + if (dirty[0] & 4 && t2_value !== (t2_value = ctx2[0].versionInfo + "")) + set_data(t2, t2_value); + if (dirty[0] & 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[0] & 4 && t8_value !== (t8_value = ctx2[0].mtimeInfo + "")) + set_data(t8, t8_value); + if (dirty[0] & 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[26] + ""; + 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[26]); + } + let each_value_1 = ctx[27]; + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); + } + 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 i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].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 i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].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[0] & 4 && t0_value !== (t0_value = ctx[26] + "")) + set_data(t0, t0_value); + if (dirty[0] & 76) { + each_value_1 = ctx[27]; + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_1(ctx, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block_1(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].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 t2; + 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, -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"); + t2 = 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, t2); + 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[0] & 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: plugin2 } = $$props; + let plugins = []; + let deviceAndPlugins = {}; + let devicePluginList = null; + let ownPlugins = null; + let showOwnPlugins = false; + let targetList = {}; + let addOn; + function saveTargetList() { + window.localStorage.setItem("ols-plugin-targetlist", JSON.stringify(targetList)); + } + function loadTargetList() { + let e2 = window.localStorage.getItem("ols-plugin-targetlist") || "{}"; + try { + $$invalidate(3, targetList = JSON.parse(e2)); + } catch (_) { + } + } + function clearSelection() { + $$invalidate(3, targetList = {}); + } + async function updateList() { + let x = await addOn.getPluginList(); + $$invalidate(18, ownPlugins = x.thisDevicePlugins); + $$invalidate(16, plugins = Object.values(x.allPlugins)); + let targetListItems = Array.from(new Set(plugins.map((e2) => e2.deviceVaultName + "---" + e2.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 plugin2.app.plugins.loadManifests(); + await addOn.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((e2) => e2.manifest.id == id); + if (entry) { + if (opt == "plugin") { + if (entry.versionFlag != "EVEN") + await addOn.applyPlugin(entry); + } else if (opt == "setting") { + if (entry.mtimeFlag != "EVEN") + await addOn.applyPluginData(entry); + } + } + } + } + } + await plugin2.app.plugins.loadManifests(); + await addOn.sweepPlugin(true); + updateList(); + } + async function checkUpdates() { + await addOn.checkPluginUpdate(); + } + async function replicateAndRefresh() { + await plugin2.replicate(true); + updateList(); + } + const click_handler = (deviceName) => toggleAll(deviceName); + const click_handler_1 = (plugin3) => toggleTarget(plugin3.deviceVaultName + "---" + plugin3.manifest.id + "---plugin"); + const click_handler_2 = (plugin3) => toggleTarget(plugin3.deviceVaultName + "---" + plugin3.manifest.id + "---setting"); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin2 = $$props2.plugin); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty[0] & 1) { + $: { + const f3 = plugin2.addOns.filter((e2) => e2 instanceof PluginAndTheirSettings); + if (f3 && f3.length > 0) { + addOn = f3[0]; + } + } + } + if ($$self.$$.dirty[0] & 520195) { + $: { + $$invalidate(17, deviceAndPlugins = {}); + for (const p of plugins) { + if (p.deviceVaultName == plugin2.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 [ + plugin2, + 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(); + init2(this, options, instance, create_fragment, safe_not_equal, { plugin: 0 }, add_css, [-1, -1]); + } +}; +var PluginPane_default = PluginPane; + +// src/dialogs.ts +var PluginDialogModal = class extends import_obsidian.Modal { + constructor(app2, plugin2) { + super(app2); + this.component = null; + this.plugin = plugin2; + } + 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_obsidian.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 }); + const formEl = contentEl.createEl("form"); + new import_obsidian.Setting(formEl).setName(this.key).addText( + (text2) => text2.onChange((value) => { + this.result = value; + }) + ); + new import_obsidian.Setting(formEl).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_obsidian.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/utils.ts +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 tasks = {}; +function scheduleTask(key, timeout, proc) { + cancelTask(key); + tasks[key] = setTimeout(async () => { + delete tasks[key]; + await proc(); + }, timeout); +} +function cancelTask(key) { + if (key in tasks) { + clearTimeout(tasks[key]); + delete tasks[key]; + } +} +function cancelAllTasks() { + for (const v in tasks) { + clearTimeout(tasks[v]); + delete tasks[v]; + } +} +var intervals = {}; +function cancelAllPeriodicTask() { + for (const v in intervals) { + clearInterval(intervals[v]); + delete 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]; +} +function isSensibleMargeApplicable(path) { + if (path.endsWith(".md")) + return true; + return false; +} +function isObjectMargeApplicable(path) { + if (path.endsWith(".canvas")) + return true; + if (path.endsWith(".json")) + return true; + return false; +} +function tryParseJSON(str, fallbackValue) { + try { + return JSON.parse(str); + } catch (ex) { + return fallbackValue; + } +} +var MARK_OPERATOR = ``; +var MARK_DELETED = `${MARK_OPERATOR}__DELETED`; +var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`; +var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`; +function unorderedArrayToObject(obj) { + return obj.map((e2) => ({ [e2.id]: e2 })).reduce((p, c) => ({ ...p, ...c }), {}); +} +function objectToUnorderedArray(obj) { + const entries = Object.entries(obj); + if (entries.some((e2) => { + var _a; + return e2[0] != ((_a = e2[1]) == null ? void 0 : _a.id); + })) + throw new Error("Item looks like not unordered array"); + return entries.map((e2) => e2[1]); +} +function generatePatchUnorderedArray(from, to) { + if (from.every((e2) => typeof e2 == "object" && "id" in e2) && to.every((e2) => typeof e2 == "object" && "id" in e2)) { + const fObj = unorderedArrayToObject(from); + const tObj = unorderedArrayToObject(to); + const diff = generatePatchObj(fObj, tObj); + if (Object.keys(diff).length > 0) { + return { [MARK_ISARRAY]: diff }; + } else { + return {}; + } + } + return { [MARK_SWAPPED]: to }; +} +function generatePatchObj(from, to) { + const entries = Object.entries(from); + const tempMap = new Map(entries); + const ret = {}; + const newEntries = Object.entries(to); + for (const [key, value] of newEntries) { + if (!tempMap.has(key)) { + ret[key] = value; + tempMap.delete(key); + } else { + const v = tempMap.get(key); + if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) { + ret[key] = { [MARK_SWAPPED]: value }; + } else { + if (typeof v == "object" && typeof value == "object" && !Array.isArray(v) && !Array.isArray(value)) { + const wk = generatePatchObj(v, value); + if (Object.keys(wk).length > 0) + ret[key] = wk; + } else if (typeof v == "object" && typeof value == "object" && Array.isArray(v) && Array.isArray(value)) { + const wk = generatePatchUnorderedArray(v, value); + if (Object.keys(wk).length > 0) + ret[key] = wk; + } else if (typeof v != "object" && typeof value != "object") { + if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) { + ret[key] = value; + } + } else { + if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) { + ret[key] = { [MARK_SWAPPED]: value }; + } + } + } + tempMap.delete(key); + } + } + for (const [key] of tempMap) { + ret[key] = MARK_DELETED; + } + return ret; +} +function applyPatch(from, patch) { + const ret = from; + const patches = Object.entries(patch); + for (const [key, value] of patches) { + if (value == MARK_DELETED) { + delete ret[key]; + continue; + } + if (typeof value == "object") { + if (MARK_SWAPPED in value) { + ret[key] = value[MARK_SWAPPED]; + continue; + } + if (MARK_ISARRAY in value) { + if (!(key in ret)) + ret[key] = []; + if (!Array.isArray(ret[key])) { + throw new Error("Patch target type is mismatched (array to something)"); + } + const orgArrayObject = unorderedArrayToObject(ret[key]); + const appliedObject = applyPatch(orgArrayObject, value[MARK_ISARRAY]); + const appliedArray = objectToUnorderedArray(appliedObject); + ret[key] = [...appliedArray]; + } else { + if (!(key in ret)) { + ret[key] = value; + continue; + } + ret[key] = applyPatch(ret[key], value); + } + } else { + ret[key] = value; + } + } + return ret; +} +function mergeObject(objA, objB) { + const newEntries = Object.entries(objB); + const ret = { ...objA }; + if (typeof objA !== typeof objB || Array.isArray(objA) !== Array.isArray(objB)) { + return objB; + } + for (const [key, v] of newEntries) { + if (key in ret) { + const value = ret[key]; + if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) { + ret[key] = v; + } else { + if (typeof v == "object" && typeof value == "object" && !Array.isArray(v) && !Array.isArray(value)) { + ret[key] = mergeObject(v, value); + } else if (typeof v == "object" && typeof value == "object" && Array.isArray(v) && Array.isArray(value)) { + ret[key] = [.../* @__PURE__ */ new Set([...v, ...value])]; + } else { + ret[key] = v; + } + } + } else { + ret[key] = v; + } + } + return Object.entries(ret).sort().reduce((p, [key, value]) => ({ ...p, [key]: value }), {}); +} +function flattenObject(obj, path = []) { + if (typeof obj != "object") + return [[path.join("."), obj]]; + if (Array.isArray(obj)) + return [[path.join("."), JSON.stringify(obj)]]; + const e2 = Object.entries(obj); + const ret = []; + for (const [key, value] of e2) { + const p = flattenObject(value, [...path, key]); + ret.push(...p); + } + return ret; +} +function modifyFile(file, data, options) { + if (typeof data === "string") { + return app.vault.modify(file, data, options); + } else { + return app.vault.modifyBinary(file, data, options); + } +} +function createFile(path, data, options) { + if (typeof data === "string") { + return app.vault.create(path, data, options); + } else { + return app.vault.createBinary(path, data, options); + } +} +function isValidPath(filename) { + if (import_obsidian.Platform.isDesktop) { + if (process.platform == "darwin") + return isValidFilenameInDarwin(filename); + if (process.platform == "linux") + return isValidFilenameInLinux(filename); + return isValidFilenameInWidows(filename); + } + if (import_obsidian.Platform.isAndroidApp) + return isValidFilenameInAndroid(filename); + if (import_obsidian.Platform.isIosApp) + return isValidFilenameInDarwin(filename); + Logger("Could not determine platform for checking filename", LOG_LEVEL.VERBOSE); + return isValidFilenameInWidows(filename); +} +var touchedFiles = []; +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 trimPrefix(target, prefix) { + return target.startsWith(prefix) ? target.substring(prefix.length) : target; +} +function touch(file) { + const f3 = file instanceof import_obsidian.TFile ? file : getAbstractFileByPath(file); + const key = `${f3.path}-${f3.stat.mtime}-${f3.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 = []; +} +function isInternalMetadata(str) { + return str.startsWith(ICHeader); +} +function id2filenameInternalMetadata(str) { + return str.substring(ICHeaderLength); +} +function filename2idInternalMetadata(str) { + return ICHeader + str; +} +function isChunk(str) { + return str.startsWith(CHeader); +} +function isPluginMetadata(str) { + return str.startsWith(PSCHeader); +} +var askYesNo = (app2, message) => { + return new Promise((res2) => { + const popover = new PopoverSelectString(app2, message, null, null, (result) => res2(result)); + popover.open(); + }); +}; +var askSelectString = (app2, message, items) => { + const getItemsFun = () => items; + return new Promise((res2) => { + const popover = new PopoverSelectString(app2, message, "", getItemsFun, (result) => res2(result)); + popover.open(); + }); +}; +var askString = (app2, title, key, placeholder) => { + return new Promise((res2) => { + const dialog = new InputStringDialog(app2, title, key, placeholder, (result) => res2(result)); + dialog.open(); + }); +}; +var PeriodicProcessor = class { + constructor(plugin2, process2) { + this._plugin = plugin2; + this._process = process2; + } + async process() { + try { + await this._process(); + } catch (ex) { + Logger(ex); + } + } + enable(interval) { + this.disable(); + if (interval == 0) + return; + this._timer = window.setInterval(() => this._process().then(() => { + }), interval); + this._plugin.registerInterval(this._timer); + } + disable() { + if (this._timer) + clearInterval(this._timer); + } +}; + +// src/ObsidianLiveSyncSettingTab.ts +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_obsidian.requestUrl)(requestParam); +}; +var ObsidianLiveSyncSettingTab = class extends import_obsidian.PluginSettingTab { + constructor(app2, plugin2) { + super(app2, plugin2); + this.selectedScreen = ""; + this.plugin = plugin2; + } + async testConnection() { + const db = await this.plugin.replicator.connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.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; + let encrypt2 = this.plugin.settings.encrypt; + let passphrase = this.plugin.settings.passphrase; + let useDynamicIterationCount = this.plugin.settings.useDynamicIterationCount; + 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; + }); + this.selectedScreen = screen; + }; + menuTabs.forEach((element2) => { + const e2 = element2.querySelector(".sls-setting-tab"); + if (!e2) + return; + e2.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.17.34"; + const updateInformation = "### 0.17.0\n- 0.17.0 has no surfaced changes but the design of saving chunks has been changed. They have compatibility but changing files after upgrading makes different chunks than before 0.16.x.\n Please rebuild databases once if you have been worried about storage usage.\n\n - Improved:\n - Splitting markdown\n - Saving chunks\n\n - Changed:\n - Chunk ID numbering rules\n\n#### Minors\n- __0.17.1 to 0.17.30 has been moved into `update_old.md`__\n- 0.17.31\n - Fixed:\n - Now `redflag3` can be run surely.\n - Synchronisation can now be aborted.\n - Note: The synchronisation flow has been rewritten drastically. Please do not haste to inform me if you have noticed anything.\n- 0.17.32\n - Fixed:\n - Now periodic internal file scanning works well.\n - The handler of Window-visibility-changed has been fixed.\n - And minor fixes possibly included.\n - Refactored:\n - Unused logic has been removed.\n - Some utility functions have been moved into suitable files.\n - Function names have been renamed.\n- 0.17.33\n - Maintenance update: Refactored; the responsibilities that `LocalDatabase` had were shared. (Hoping) No changes in behaviour.\n- 0.17.34\n - Fixed: The `Fetch` that was broken at 0.17.33 has been fixed.\n - Refactored again: Internal file sync, plug-in sync and Set up URI have been moved into each file.\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_obsidian.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.settings.syncAfterMerge) + return true; + if (this.plugin.replicator.syncStatus == "CONNECTED") + return true; + if (this.plugin.replicator.syncStatus == "PAUSED") + return true; + return false; + }; + let inWizard = false; + const setupWizardEl = containerEl.createDiv(); + setupWizardEl.createEl("h3", { text: "Setup wizard" }); + new import_obsidian.Setting(setupWizardEl).setName("Discard the existing configuration and set up").addButton((text2) => { + text2.setButtonText("Next").onClick(() => { + if (JSON.stringify(this.plugin.settings) != JSON.stringify(DEFAULT_SETTINGS)) { + this.plugin.replicator.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_obsidian.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.settings.syncAfterMerge = false; + this.plugin.replicator.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_obsidian.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((e2) => { + e2.setDisabled(true).setTooltip("Could not change this while any synchronization options are enabled."); + }); + syncWarn.removeClass("sls-hidden"); + } else { + dbSettings.forEach((e2) => { + e2.setDisabled(false).setTooltip(""); + }); + syncWarn.addClass("sls-hidden"); + } + if (this.plugin.settings.liveSync) { + syncNonLive.forEach((e2) => { + e2.setDisabled(true).setTooltip(""); + }); + syncLive.forEach((e2) => { + e2.setDisabled(false).setTooltip(""); + }); + } else if (this.plugin.settings.syncOnFileOpen || this.plugin.settings.syncOnSave || this.plugin.settings.syncOnStart || this.plugin.settings.periodicReplication || this.plugin.settings.syncAfterMerge) { + syncNonLive.forEach((e2) => { + e2.setDisabled(false).setTooltip(""); + }); + syncLive.forEach((e2) => { + e2.setDisabled(true).setTooltip(""); + }); + } else { + syncNonLive.forEach((e2) => { + e2.setDisabled(false).setTooltip(""); + }); + syncLive.forEach((e2) => { + e2.setDisabled(false).setTooltip(""); + }); + } + }; + const dbSettings = []; + dbSettings.push( + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.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(); + }) + ) + ); + const e2e = new import_obsidian.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(encrypt2).onChange(async (value) => { + if (inWizard) { + this.plugin.settings.encrypt = value; + passphraseSetting.setDisabled(!value); + dynamicIteration.setDisabled(!value); + await this.plugin.saveSettings(); + } else { + encrypt2 = value; + passphraseSetting.setDisabled(!value); + dynamicIteration.setDisabled(!value); + await this.plugin.saveSettings(); + markDirtyControl(); + } + }) + ); + const markDirtyControl = () => { + passphraseSetting.controlEl.toggleClass("sls-item-dirty", passphrase != this.plugin.settings.passphrase); + e2e.controlEl.toggleClass("sls-item-dirty", encrypt2 != this.plugin.settings.encrypt); + dynamicIteration.controlEl.toggleClass("sls-item-dirty", useDynamicIterationCount != this.plugin.settings.useDynamicIterationCount); + }; + const passphraseSetting = new import_obsidian.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(passphrase).onChange(async (value) => { + if (inWizard) { + this.plugin.settings.passphrase = value; + await this.plugin.saveSettings(); + } else { + passphrase = value; + await this.plugin.saveSettings(); + markDirtyControl(); + } + }); + text2.inputEl.setAttribute("type", "password"); + }); + passphraseSetting.setDisabled(!encrypt2); + const dynamicIteration = new import_obsidian.Setting(containerRemoteDatabaseEl).setName("Use dynamic iteration count (experimental)").setDesc("Balancing the encryption/decryption load against the length of the passphrase if toggled. (v0.17.5 or higher required)").addToggle((toggle) => { + toggle.setValue(useDynamicIterationCount).onChange(async (value) => { + if (inWizard) { + this.plugin.settings.useDynamicIterationCount = value; + await this.plugin.saveSettings(); + } else { + useDynamicIterationCount = value; + await this.plugin.saveSettings(); + markDirtyControl(); + } + }); + }).setClass("wizardHidden"); + dynamicIteration.setDisabled(!encrypt2); + const checkWorkingPassphrase = async () => { + const settingForCheck = { + ...this.plugin.settings, + encrypt: encrypt2, + passphrase, + useDynamicIterationCount + }; + console.dir(settingForCheck); + const db = await this.plugin.replicator.connectRemoteCouchDBWithSetting(settingForCheck, this.plugin.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 (encrypt2 && passphrase == "") { + Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL.NOTICE); + return; + } + if (encrypt2 && !await testCrypt()) { + Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.NOTICE); + return; + } + if (!await checkWorkingPassphrase() && !sendToServer) { + return; + } + if (!encrypt2) { + passphrase = ""; + } + 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.syncAfterMerge = false; + this.plugin.settings.encrypt = encrypt2; + this.plugin.settings.passphrase = passphrase; + this.plugin.settings.useDynamicIterationCount = useDynamicIterationCount; + await this.plugin.saveSettings(); + markDirtyControl(); + 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_obsidian.Setting(containerRemoteDatabaseEl).setName("Apply").setDesc("Apply encryption settings").setClass("wizardHidden").addButton( + (button) => button.setButtonText("Apply").setWarning().setDisabled(false).onClick(async () => { + await applyEncryption(true); + }) + ).addButton( + (button) => button.setButtonText("Apply w/o rebuilding").setWarning().setDisabled(false).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; + this.plugin.settings.syncAfterMerge = false; + this.plugin.settings.syncInternalFiles = false; + this.plugin.settings.usePluginSync = false; + Logger("Hidden files and plugin synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL.NOTICE); + await this.plugin.saveSettings(); + applyDisplayEnabled(); + await delay(2e3); + if (method == "localOnly") { + await this.plugin.resetLocalDatabase(); + await delay(1e3); + await this.plugin.markRemoteResolved(); + await this.plugin.openDatabase(); + this.plugin.isReady = true; + await this.plugin.replicateAllFromServer(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 delay(1e3); + await this.plugin.initializeDatabase(true); + await this.plugin.markRemoteLocked(); + await this.plugin.tryResetRemoteDatabase(); + await this.plugin.markRemoteLocked(); + await this.plugin.replicateAllToServer(true); + } + }; + new import_obsidian.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).onClick(async () => { + await rebuildDB("remoteOnly"); + }) + ); + new import_obsidian.Setting(containerRemoteDatabaseEl).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").setClass("wizardHidden").addButton( + (button) => button.setButtonText("Rebuild").setWarning().setDisabled(false).onClick(async () => { + await rebuildDB("rebuildBothByThisDevice"); + }) + ); + new import_obsidian.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_obsidian.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 r = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin); + Logger(JSON.stringify(r.json, null, 2)); + const responseConfig = r.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 res2 = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, void 0, key, value); + console.dir(res2); + if (res2.status == 200) { + Logger(`${title} successfully updated`, LOG_LEVEL.NOTICE); + checkResultDiv.removeChild(x); + checkConfig(); + } else { + Logger(`${title} failed`, LOG_LEVEL.NOTICE); + Logger(res2.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((e2) => { + e2[0] = (e2[0] + "").toLowerCase(); + return e2; + }).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_obsidian.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_obsidian.Setting(containerRemoteDatabaseEl).setName("").setClass("wizardOnly").addButton( + (button) => button.setButtonText("Next").setClass("mod-cta").setDisabled(false).onClick(() => { + 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_obsidian.Setting(containerRemoteDatabaseEl).setName("").setClass("wizardOnly").addButton( + (button) => button.setButtonText("Discard exist database and proceed").setDisabled(false).setWarning().onClick(() => { + 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_obsidian.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_obsidian.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).onClick(async () => { + await rebuildDB("localOnly"); + }) + ); + let newDatabaseName = this.plugin.settings.additionalSuffixOfDatabaseName + ""; + new import_obsidian.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_obsidian.Setting(containerLocalDatabaseEl).setName("").setClass("wizardOnly").addButton( + (button) => button.setButtonText("Next").setDisabled(false).onClick(() => { + changeDisplay("40"); + }) + ); + containerLocalDatabaseEl.createEl("h3", { + text: (0, import_obsidian.sanitizeHTMLToDom)(`Experimental`), + cls: "wizardHidden" + }); + new import_obsidian.Setting(containerLocalDatabaseEl).setName("Use new adapter").setDesc("This option is not compatible with a database made by older versions. Changing this configuration will fetch the remote database again.").setClass("wizardHidden").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.useIndexedDBAdapter).onChange(async (value) => { + this.plugin.settings.useIndexedDBAdapter = value; + await this.plugin.saveSettings(); + await rebuildDB("localOnly"); + }) + ); + addScreenElement("10", containerLocalDatabaseEl); + const containerGeneralSettingsEl = containerEl.createDiv(); + containerGeneralSettingsEl.createEl("h3", { text: "General Settings" }); + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.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"); + }); + new import_obsidian.Setting(containerGeneralSettingsEl).setName("Monitor changes to hidden files and plugin").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.watchInternalFileChanges).onChange(async (value) => { + this.plugin.settings.watchInternalFileChanges = value; + await this.plugin.saveSettings(); + }) + ); + 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." }, (e2) => { + e2.addClass("mod-cta"); + e2.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_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.Setting(containerSyncSettingEl).setName("Sync after merging file").setDesc("Sync automatically after merging files").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.syncAfterMerge).onChange(async (value) => { + this.plugin.settings.syncAfterMerge = value; + await this.plugin.saveSettings(); + applyDisplayEnabled(); + }) + ) + ); + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.Setting(containerSyncSettingEl).setName("Disable sensible auto merging on markdown files").setDesc("If this switch is turned on, a merge dialog will be displayed, even if the sensible-merge is possible automatically. (Turn on to previous behavior)").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.disableMarkdownAutoMerge).onChange(async (value) => { + this.plugin.settings.disableMarkdownAutoMerge = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerSyncSettingEl).setName("Write documents after synchronization even if they have conflict").setDesc("Turn on to previous behavior").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.writeDocumentsIfConflicted).onChange(async (value) => { + this.plugin.settings.writeDocumentsIfConflicted = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.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_obsidian.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).onClick(async () => { + const filesAll = await this.plugin.addOnHiddenFileSync.scanInternalFiles(); + const targetFiles = await this.plugin.filterTargetFiles(filesAll); + const now = Date.now(); + const newFiles = targetFiles.map((e2) => ({ ...e2, mtime: now })); + let i = 0; + const maxFiles = newFiles.length; + for (const file of newFiles) { + i++; + Logger(`Touched:${file.path} (${i}/${maxFiles})`, LOG_LEVEL.NOTICE, "touch-files"); + await this.plugin.applyMTimeToFile(file); + } + }) + ); + containerSyncSettingEl.createEl("h3", { + text: (0, import_obsidian.sanitizeHTMLToDom)(`Experimental`) + }); + new import_obsidian.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_obsidian.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_obsidian.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 < 1) { + v = 1; + } + this.plugin.settings.customChunkSize = v; + await this.plugin.saveSettings(); + }); + text2.inputEl.setAttribute("type", "number"); + }); + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.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"); + }); + new import_obsidian.Setting(containerSyncSettingEl).setName("Use timeouts instead of heartbeats").setDesc("If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.").addToggle( + (toggle) => { + toggle.setValue(this.plugin.settings.useTimeouts).onChange(async (value) => { + this.plugin.settings.useTimeouts = value; + await this.plugin.saveSettings(); + }); + return toggle; + } + ); + new import_obsidian.Setting(containerSyncSettingEl).setName("A number of hashes to be cached").setDesc("").addText((text2) => { + text2.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxCount + "").onChange(async (value) => { + let v = Number(value); + if (isNaN(v) || v < 10) { + v = 10; + } + this.plugin.settings.hashCacheMaxCount = v; + await this.plugin.saveSettings(); + }); + text2.inputEl.setAttribute("type", "number"); + }); + new import_obsidian.Setting(containerSyncSettingEl).setName("The total length of hashes to be cached").setDesc("(Mega chars)").addText((text2) => { + text2.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxAmount + "").onChange(async (value) => { + let v = Number(value); + if (isNaN(v) || v < 1) { + v = 1; + } + this.plugin.settings.hashCacheMaxAmount = v; + await this.plugin.saveSettings(); + }); + text2.inputEl.setAttribute("type", "number"); + }); + new import_obsidian.Setting(containerSyncSettingEl).setName("The maximum number of reading chunks online concurrently").setDesc("").addText((text2) => { + text2.setPlaceholder("").setValue(this.plugin.settings.concurrencyOfReadChunksOnline + "").onChange(async (value) => { + let v = Number(value); + if (isNaN(v) || v < 10) { + v = 10; + } + this.plugin.settings.concurrencyOfReadChunksOnline = v; + await this.plugin.saveSettings(); + }); + text2.inputEl.setAttribute("type", "number"); + }); + new import_obsidian.Setting(containerSyncSettingEl).setName("The minimum interval for reading chunks online").setDesc("").addText((text2) => { + text2.setPlaceholder("").setValue(this.plugin.settings.minimumIntervalOfReadChunksOnline + "").onChange(async (value) => { + let v = Number(value); + if (isNaN(v) || v < 10) { + v = 10; + } + this.plugin.settings.minimumIntervalOfReadChunksOnline = v; + await this.plugin.saveSettings(); + }); + text2.inputEl.setAttribute("type", "number"); + }); + addScreenElement("30", containerSyncSettingEl); + const containerMiscellaneousEl = containerEl.createDiv(); + containerMiscellaneousEl.createEl("h3", { text: "Miscellaneous" }); + new import_obsidian.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_obsidian.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; + } + const presetAllDisabled = { + batchSave: false, + liveSync: false, + periodicReplication: false, + syncOnSave: false, + syncOnStart: false, + syncOnFileOpen: false, + syncAfterMerge: false + }; + const presetLiveSync = { + ...presetAllDisabled, + liveSync: true + }; + const presetPeriodic = { + ...presetAllDisabled, + batchSave: true, + periodicReplication: true, + syncOnSave: false, + syncOnStart: true, + syncOnFileOpen: true, + syncAfterMerge: true + }; + if (currentPreset == "LIVESYNC") { + this.plugin.settings = { + ...this.plugin.settings, + ...presetLiveSync + }; + Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL.NOTICE); + } else if (currentPreset == "PERIODIC") { + this.plugin.settings = { + ...this.plugin.settings, + ...presetPeriodic + }; + Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL.NOTICE); + } else { + Logger("All synchronization disabled.", LOG_LEVEL.NOTICE); + this.plugin.settings = { + ...this.plugin.settings, + ...presetAllDisabled + }; + } + this.plugin.saveSettings(); + await this.plugin.realizeSettingSyncMode(); + this.display(); + 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 passphrase_options = { + "": "Default", + LOCALSTORAGE: "Use a custom passphrase", + ASK_AT_LAUNCH: "Ask an passphrase at every launch" + }; + new import_obsidian.Setting(containerMiscellaneousEl).setName("Encrypting sensitive configuration items").addDropdown( + (dropdown) => dropdown.addOptions(passphrase_options).setValue(this.plugin.settings.configPassphraseStore).onChange(async (value) => { + this.plugin.settings.configPassphraseStore = value; + this.plugin.usedPassphrase = ""; + confPassphraseSetting.setDisabled(this.plugin.settings.configPassphraseStore != "LOCALSTORAGE"); + await this.plugin.saveSettings(); + }) + ).setClass("wizardHidden"); + const confPassphrase = localStorage.getItem("ls-setting-passphrase") || ""; + const confPassphraseSetting = new import_obsidian.Setting(containerMiscellaneousEl).setName("Passphrase of sensitive configuration items").setDesc("This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.").addText((text2) => { + text2.setPlaceholder("").setValue(confPassphrase).onChange(async (value) => { + this.plugin.usedPassphrase = ""; + localStorage.setItem("ls-setting-passphrase", value); + await this.plugin.saveSettings(); + markDirtyControl(); + }); + text2.inputEl.setAttribute("type", "password"); + }).setClass("wizardHidden"); + confPassphraseSetting.setDisabled(this.plugin.settings.configPassphraseStore != "LOCALSTORAGE"); + 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_obsidian.Setting(containerHatchEl).setName("Make report to inform the issue").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 r = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin); + Logger(JSON.stringify(r.json, null, 2)); + responseConfig = r.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.encryptedPassphrase = REDACTED; + pluginConfig.encryptedCouchDBConnection = REDACTED; + const msgConfig = `----remote config---- +${(0, import_obsidian.stringifyYaml)(responseConfig)} +---- Plug-in config --- +${(0, import_obsidian.stringifyYaml)(pluginConfig)}`; + console.log(msgConfig); + await navigator.clipboard.writeText(msgConfig); + Logger(`Information has been copied to clipboard`, LOG_LEVEL.NOTICE); + }) + ); + if (this.plugin.replicator.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'" }, (e2) => { + e2.addClass("mod-warning"); + e2.addEventListener("click", async () => { + await this.plugin.markRemoteResolved(); + c.remove(); + }); + }); + c.addClass("op-warn"); + } else { + if (this.plugin.replicator.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" }, (e2) => { + e2.addClass("mod-warning"); + e2.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_obsidian.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 semaphore = Semaphore(10); + const files = this.app.vault.getFiles(); + let i = 0; + const processes = files.map((e2) => (async (file) => { + const releaser = await semaphore.acquire(1, "verifyAndRepair"); + try { + Logger(`UPDATE DATABASE ${file.path}`); + await this.plugin.updateIntoDB(file, false, null, true); + i++; + Logger(`${i}/${files.length} +${file.path}`, LOG_LEVEL.NOTICE, "verify"); + } catch (ex) { + i++; + Logger(`Error while verifyAndRepair`, LOG_LEVEL.NOTICE); + Logger(ex); + } finally { + releaser(); + } + })(e2)); + await Promise.all(processes); + Logger("done", LOG_LEVEL.NOTICE, "verify"); + }) + ); + new import_obsidian.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_obsidian.Setting(containerHatchEl).setName("Write logs into the file").setDesc("Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.writeLogToTheFile).onChange(async (value) => { + this.plugin.settings.writeLogToTheFile = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.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_obsidian.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_obsidian.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_obsidian.Setting(containerPluginSettings).setName("Scan plugins periodically").setDesc("Scan plugins every 1 minute. This configuration will be ignored if monitoring changes of hidden files has been enabled.").addToggle( + (toggle) => toggle.setValue(this.plugin.settings.autoSweepPluginsPeriodic).onChange(async (value) => { + this.plugin.settings.autoSweepPluginsPeriodic = value; + updateDisabledOfDeviceAndVaultName(); + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.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_obsidian.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_obsidian.Setting(containerPluginSettings).setName("Open").setDesc("Open the plugin dialog").addButton((button) => { + button.setButtonText("Open").setDisabled(false).onClick(() => { + this.plugin.addOnPluginAndTheirSettings.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` }, (e2) => { + e2.addEventListener("click", async () => { + await this.plugin.localDatabase.deleteDBEntry(k); + xx.remove(); + }); + }); + ba.addClass("mod-warning"); + xx.createEl("button", { text: `Restore from file` }, (e2) => { + e2.addEventListener("click", async () => { + const f3 = await this.app.vault.getFiles().filter((e3) => path2id(e3.path) == k); + if (f3.length == 0) { + Logger("Not found in vault", LOG_LEVEL.NOTICE); + return; + } + await this.plugin.updateIntoDB(f3[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 = [.../* @__PURE__ */ new Set([...this.plugin.queuedFiles.map((e2) => e2.entry._id)])]; + for (const k of files) { + const xx = cx.createEl("div", { text: `${id2path(k)}` }); + const ba = xx.createEl("button", { text: `Delete this` }, (e2) => { + e2.addEventListener("click", async () => { + await this.plugin.localDatabase.deleteDBEntry(k); + xx.remove(); + }); + }); + ba.addClass("mod-warning"); + xx.createEl("button", { text: `Restore from file` }, (e2) => { + e2.addEventListener("click", async () => { + const f3 = await this.app.vault.getFiles().filter((e3) => path2id(e3.path) == k); + if (f3.length == 0) { + Logger("Not found in vault", LOG_LEVEL.NOTICE); + return; + } + await this.plugin.updateIntoDB(f3[0]); + xx.remove(); + }); + }); + xx.addClass("mod-warning"); + } + } else { + containerCorruptedDataEl.createEl("div", { text: "There is no missing or waiting chunk." }); + } + applyDisplayEnabled(); + addScreenElement("70", containerCorruptedDataEl); + if (this.selectedScreen == "") { + 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"); + } + } + } else { + changeDisplay(this.selectedScreen); + } + } +}; + +// src/DocumentHistoryModal.ts +var import_diff_match_patch2 = __toESM(require_diff_match_patch(), 1); +var DocumentHistoryModal = class extends import_obsidian.Modal { + constructor(app2, plugin2, file) { + super(app2); + this.showDiff = false; + this.revs_info = []; + this.currentText = ""; + this.currentDeleted = false; + this.plugin = plugin2; + this.file = file instanceof import_obsidian.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((e2) => (e2 == null ? void 0 : e2.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 (isErrorOfMissingDoc(ex)) { + 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 index5 = this.revs_info.length - 1 - this.range.value / 1; + const rev2 = this.revs_info[index5]; + const w = await db.getDBEntry(path2id(this.file), { rev: rev2.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
    (${rev2.rev})`; + } else { + this.currentDoc = w; + this.info.innerHTML = `Modified:${new Date(w.mtime).toLocaleString()}`; + let result = ""; + const w1data = w.datatype == "plain" ? getDocData(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" ? getDocData(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" }, (e2) => { + this.range = e2; + e2.addEventListener("change", (e3) => { + this.loadRevs(); + }); + e2.addEventListener("input", (e3) => { + this.loadRevs(); + }); + }); + contentEl.createDiv("", (e2) => { + e2.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" }, (e2) => { + e2.addClass("mod-cta"); + e2.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((f3) => f3.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" }, (e2) => { + e2.addClass("mod-cta"); + e2.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, getDocData(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/StorageEventManager.ts +var StorageEventManager = class { +}; +var StorageEventManagerObsidian = class extends StorageEventManager { + constructor(plugin2) { + super(); + this.queuedFilesStore = getGlobalStore("queuedFiles", { queuedItems: [], fileEventItems: [] }); + this.watchedFileEventQueue = []; + this.plugin = plugin2; + 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); + plugin2.registerEvent(app.vault.on("modify", this.watchVaultChange)); + plugin2.registerEvent(app.vault.on("delete", this.watchVaultDelete)); + plugin2.registerEvent(app.vault.on("rename", this.watchVaultRename)); + plugin2.registerEvent(app.vault.on("create", this.watchVaultCreate)); + plugin2.registerEvent(app.vault.on("raw", this.watchVaultRawEvents)); + } + watchVaultCreate(file, ctx) { + this.appendWatchEvent([{ type: "CREATE", file }], ctx); + } + watchVaultChange(file, ctx) { + this.appendWatchEvent([{ type: "CHANGED", file }], ctx); + } + watchVaultDelete(file, ctx) { + this.appendWatchEvent([{ type: "DELETE", file }], ctx); + } + watchVaultRename(file, oldFile, ctx) { + if (file instanceof import_obsidian.TFile) { + this.appendWatchEvent([ + { type: "CREATE", file }, + { type: "DELETE", file: { path: oldFile, mtime: file.stat.mtime, ctime: file.stat.ctime, size: file.stat.size, deleted: true } } + ], ctx); + } + } + watchVaultRawEvents(path) { + if (!this.plugin.settings.syncInternalFiles) + return; + if (!this.plugin.settings.watchInternalFileChanges) + return; + if (!path.startsWith(app.vault.configDir)) + return; + const ignorePatterns = this.plugin.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((e2) => e2).map((e2) => new RegExp(e2, "i")); + if (ignorePatterns.some((e2) => path.match(e2))) + return; + this.appendWatchEvent( + [{ + type: "INTERNAL", + file: { path, mtime: 0, ctime: 0, size: 0 } + }], + null + ); + } + async appendWatchEvent(params, ctx) { + let forcePerform = false; + for (const param of params) { + if (shouldBeIgnored(param.file.path)) { + continue; + } + const atomicKey = [0, 0, 0, 0, 0, 0].map((e2) => `${Math.floor(Math.random() * 1e5)}`).join("-"); + const type = param.type; + const file = param.file; + const oldPath = param.oldPath; + if (file instanceof import_obsidian.TFolder) + continue; + if (!this.plugin.isTargetFile(file.path)) + continue; + if (this.plugin.settings.suspendFileWatching) + continue; + let cache; + if (file instanceof import_obsidian.TFile && (type == "CREATE" || type == "CHANGED")) { + if (recentlyTouched(file)) { + continue; + } + if (!isPlainText(file.name)) { + cache = await app.vault.readBinary(file); + } else { + cache = await app.vault.cachedRead(file); + if (!cache) + cache = await app.vault.read(file); + } + } + if (type == "DELETE" || type == "RENAME") { + forcePerform = true; + } + if (this.plugin.settings.batchSave) { + let i = this.watchedFileEventQueue.length; + L1: + while (i >= 0) { + i--; + if (i < 0) + break L1; + if (this.watchedFileEventQueue[i].args.file.path != file.path) { + continue L1; + } + if (this.watchedFileEventQueue[i].type != type) + break L1; + this.watchedFileEventQueue.remove(this.watchedFileEventQueue[i]); + this.queuedFilesStore.apply((value) => ({ ...value, fileEventItems: this.watchedFileEventQueue })); + } + } + const fileInfo = file instanceof import_obsidian.TFile ? { + ctime: file.stat.ctime, + mtime: file.stat.mtime, + file, + path: file.path, + size: file.stat.size + } : file; + this.watchedFileEventQueue.push({ + type, + args: { + file: fileInfo, + oldPath, + cache, + ctx + }, + key: atomicKey + }); + } + this.queuedFilesStore.apply((value) => ({ ...value, fileEventItems: this.watchedFileEventQueue })); + this.plugin.procFileEvent(forcePerform); + } + fetchEvent() { + if (this.watchedFileEventQueue.length == 0) + return false; + const item = this.watchedFileEventQueue.shift(); + this.queuedFilesStore.apply((value) => ({ ...value, fileEventItems: this.watchedFileEventQueue })); + return item; + } + cancelRelativeEvent(item) { + this.watchedFileEventQueue = [...this.watchedFileEventQueue].filter((e2) => e2.key != item.key); + this.queuedFilesStore.apply((value) => ({ ...value, fileEventItems: this.watchedFileEventQueue })); + } + getQueueLength() { + return this.watchedFileEventQueue.length; + } +}; + +// 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(t2, e2, n2) { + if (e2.buffer.byteLength < t2.byteLength + n2) { + const i = Math.ceil((t2.byteLength + n2 - e2.buffer.byteLength) / 65536); + e2.grow(i); + } + new Uint8Array(e2.buffer, n2).set(t2); +} +async function xxhash_wasm_default() { + const { instance: { exports: { mem: i, xxh32: o, xxh64: r } } } = await WebAssembly.instantiate(t); + function h2(t2) { + let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0; + return n(t2, i, 0), o(0, t2.byteLength, e2) >>> 0; + } + function c(t2) { + let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o2 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0; + n(t2, i, 8); + const h3 = new DataView(i.buffer); + return h3.setUint32(0, e2, true), h3.setUint32(4, o2, true), r(0, t2.byteLength), h3; + } + return { h32: function(t2) { + let n2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0; + e || (e = new TextEncoder()); + const i2 = e.encode(t2); + return h2(i2, n2).toString(16); + }, h32Raw: h2, h64: function(t2) { + let n2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, i2 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0; + e || (e = new TextEncoder()); + const o2 = e.encode(t2), r2 = c(o2, n2, i2), h3 = r2.getUint32(0, true).toString(16) + r2.getUint32(4, true).toString(16); + return h3; + }, h64Raw: function(t2) { + let e2 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, n2 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0; + return new Uint8Array(c(t2, e2, n2).buffer, 0, 8); + } }; +} + +// src/lib/src/LRUCache.ts +var LRUCache = class { + constructor(maxCache, maxCacheLength) { + this.cache = /* @__PURE__ */ new Map([]); + this.revCache = /* @__PURE__ */ new Map([]); + this.maxCache = 200; + this.maxCachedLength = 5e7; + this.cachedLength = 0; + this.maxCache = maxCache || 200; + this.maxCachedLength = (maxCacheLength || 1) * 1e6; + Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL.VERBOSE); + } + 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); + this.cachedLength += value.length; + if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) { + for (const [key2, value2] of this.cache) { + this.revCache.delete(value2); + this.cache.delete(key2); + this.cachedLength -= value2.length; + if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength) + break; + } + } else { + } + } +}; + +// src/lib/src/LiveSyncDBFunctions.ts +async function putDBEntry(env, note, saveAsBigChunk) { + var _a; + if (!env.isTargetFile(env.id2path(note._id))) { + return false; + } + const savedNotes = []; + let processed = 0; + let made = 0; + let skipped = 0; + const maxChunkSize = MAX_DOC_SIZE_BIN * Math.max(env.settings.customChunkSize, 1); + const pieceSize = maxChunkSize; + let plainSplit = false; + let cacheUsed = 0; + const userPasswordHash = env.h32Raw(new TextEncoder().encode(env.settings.passphrase)); + const minimumChunkSize = env.settings.minimumChunkSize; + if (!saveAsBigChunk && shouldSplitAsPlainText(note._id)) { + plainSplit = true; + } + const newLeafs = []; + const pieces = splitPieces2(note.data, pieceSize, plainSplit, minimumChunkSize, 0); + const currentDocPiece = /* @__PURE__ */ new Map(); + let saved = true; + for (const piece of pieces()) { + processed++; + let leafId = ""; + let hashedPiece = ""; + const cache = env.hashCaches.revGet(piece); + if (cache) { + hashedPiece = ""; + leafId = cache; + skipped++; + cacheUsed++; + currentDocPiece.set(leafId, piece); + } else { + if (env.settings.encrypt) { + hashedPiece = "+" + (env.h32Raw(new TextEncoder().encode(piece)) ^ userPasswordHash ^ piece.length).toString(36); + } else { + hashedPiece = (env.h32Raw(new TextEncoder().encode(piece)) ^ piece.length).toString(36); + } + leafId = "h:" + hashedPiece; + } + if (currentDocPiece.has(leafId)) { + if (currentDocPiece.get(leafId) != piece) { + Logger(`Hash collided! If possible, please report the following string +A:--${currentDocPiece.get(leafId)}-- +B:--${piece}--`, LOG_LEVEL.NOTICE); + Logger(`This document could not be saved:${note._id}`, LOG_LEVEL.NOTICE); + saved = false; + } + } else { + currentDocPiece.set(leafId, piece); + } + savedNotes.push(leafId); + } + const newChunkIds = [...currentDocPiece.keys()]; + do { + const procChunks = newChunkIds.splice(0, 100); + if (procChunks.length > 0) { + const existChunks = await env.localDatabase.allDocs({ keys: [...procChunks], include_docs: true }); + for (const chunk of existChunks.rows) { + if ("error" in chunk && chunk.error == "not_found") { + const data = currentDocPiece.get(chunk.key); + if (typeof data === "undefined") { + Logger("Saving chunk error: Missing data:" + chunk.key); + console.log(data); + saved = false; + continue; + } + const d = { + _id: chunk.key, + data, + type: "leaf" + }; + newLeafs.push(d); + } else if ("error" in chunk) { + Logger("Saving chunk error: " + chunk.error); + saved = false; + } else { + const pieceData = chunk.doc; + if (pieceData.type == "leaf" && pieceData.data == currentDocPiece.get(chunk.key)) { + skipped++; + } else if (pieceData.type == "leaf") { + Logger(`Hash collided on saving! If possible, please report the following string +A:--${currentDocPiece.get(chunk.key)}-- +B:--${pieceData.data}--`, LOG_LEVEL.NOTICE); + Logger(`This document could not be saved:${note._id}`, LOG_LEVEL.NOTICE); + saved = false; + } + } + } + } + } while (newChunkIds.length > 0); + if (newLeafs.length > 0) { + try { + const result = await env.localDatabase.bulkDocs(newLeafs); + for (const item of result) { + if ("ok" in item) { + const id = item.id; + const pieceData = currentDocPiece.get(id); + if (typeof pieceData === "undefined") { + saved = false; + Logger(`Save failed.:id:${item.id} rev:${item.rev}`, LOG_LEVEL.NOTICE); + continue; + } + env.hashCaches.set(id, pieceData); + made++; + } else { + if ((item == null ? void 0 : item.status) == 409) { + skipped++; + } 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} ,chunks: ${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 + }; + return (_a = await runWithLock("file:" + newDoc._id, false, async () => { + try { + const old = await env.localDatabase.get(newDoc._id); + if (!old.type || old.type == "notes" || old.type == "newnote" || old.type == "plain") { + newDoc._rev = old._rev; + } + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + } else { + throw ex; + } + } + const r = await env.localDatabase.put(newDoc, { force: true }); + if (typeof env.corruptedEntries[note._id] != "undefined") { + delete env.corruptedEntries[note._id]; + } + if (r.ok) { + return r; + } else { + return false; + } + })) != null ? _a : false; + } else { + Logger(`note could not saved:${note._id}`); + return false; + } +} +async function getDBEntryMeta(env, path, opt, includeDeleted = false) { + if (!env.isTargetFile(path)) { + return false; + } + const id = env.path2id(path); + try { + let obj = null; + if (opt) { + obj = await env.localDatabase.get(id, opt); + } else { + obj = await env.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 (isErrorOfMissingDoc(ex)) { + return false; + } + throw ex; + } + return false; +} +async function getDBEntryFromMeta(env, obj, opt, dump = false, waitForReady = true, includeDeleted = false) { + const deleted = "deleted" in obj ? obj.deleted : void 0; + 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 env.corruptedEntries[doc._id] != "undefined") { + delete env.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 (env.settings.readChunksOnline) { + const items = await env.collectChunks(obj.children, false, waitForReady); + 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); + env.corruptedEntries[obj._id] = obj; + } + return false; + } + } + } else { + if (opt) { + Logger(`Could not retrieve chunks of ${obj._id}. we have to `, LOG_LEVEL.NOTICE); + } + return false; + } + } else { + try { + if (waitForReady) { + children2 = await Promise.all(obj.children.map((e2) => env.getDBLeaf(e2, waitForReady))); + if (dump) { + Logger(`Chunks:`); + Logger(children2); + } + } else { + const chunkDocs = await env.localDatabase.allDocs({ keys: obj.children, include_docs: true }); + if (chunkDocs.rows.some((e2) => "error" in e2)) { + const missingChunks = chunkDocs.rows.filter((e2) => "error" in e2).map((e2) => e2.id).join(", "); + Logger(`Could not retrieve chunks of ${obj._id}. Chunks are missing:${missingChunks}`, LOG_LEVEL.NOTICE); + return false; + } + if (chunkDocs.rows.some((e2) => e2.doc && e2.doc.type != "leaf")) { + const missingChunks = chunkDocs.rows.filter((e2) => e2.doc && e2.doc.type != "leaf").map((e2) => e2.id).join(", "); + Logger(`Could not retrieve chunks of ${obj._id}. corrupted chunks::${missingChunks}`, LOG_LEVEL.NOTICE); + return false; + } + children2 = chunkDocs.rows.map((e2) => e2.doc.data); + } + } 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); + env.corruptedEntries[obj._id] = obj; + return false; + } + } + const data = children2; + 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 env.corruptedEntries[doc._id] != "undefined") { + delete env.corruptedEntries[doc._id]; + } + return doc; + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + 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); + } + } + return false; +} +async function getDBEntry(env, path, opt, dump = false, waitForReady = true, includeDeleted = false) { + const meta = await getDBEntryMeta(env, path, opt, includeDeleted); + if (meta) { + return await getDBEntryFromMeta(env, meta, opt, dump, waitForReady, includeDeleted); + } else { + return false; + } +} +async function deleteDBEntry(env, path, opt) { + var _a; + if (!env.isTargetFile(path)) { + return false; + } + const id = env.path2id(path); + try { + return (_a = await runWithLock("file:" + id, false, async () => { + let obj = null; + if (opt) { + obj = await env.localDatabase.get(id, opt); + } else { + obj = await env.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 r = await env.localDatabase.put(obj); + Logger(`entry removed:${obj._id}-${r.rev}`); + if (typeof env.corruptedEntries[obj._id] != "undefined") { + delete env.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 (env.settings.deleteMetadataOfDeletedFiles) { + obj._deleted = true; + } + } + const r = await env.localDatabase.put(obj); + Logger(`entry removed:${obj._id}-${r.rev}`); + if (typeof env.corruptedEntries[obj._id] != "undefined") { + delete env.corruptedEntries[obj._id]; + } + return true; + } else { + return false; + } + })) != null ? _a : false; + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + return false; + } + throw ex; + } +} +async function deleteDBEntryPrefix(env, prefixSrc) { + let c = 0; + let readCount = 0; + const delDocs = []; + const prefix = env.path2id(prefixSrc); + do { + const result = await env.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 (env.isTargetFile(env.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 env.localDatabase.get(v); + if (item.type == "newnote" || item.type == "plain") { + item.deleted = true; + if (env.settings.deleteMetadataOfDeletedFiles) { + item._deleted = true; + } + item.mtime = Date.now(); + } else { + item._deleted = true; + } + await env.localDatabase.put(item); + }); + deleteCount++; + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + notfound++; + } else { + throw ex; + } + } + } + Logger(`deleteDBEntryPrefix:deleted ${deleteCount} items, skipped ${notfound}`); + return true; +} +async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange2) { + const defMilestonePoint = { + _id: MILSTONE_DOCID, + type: "milestoneinfo", + created: new Date() / 1, + locked: false, + accepted_nodes: [deviceNodeID], + node_chunk_info: { [deviceNodeID]: currentVersionRange2 } + }; + const remoteMilestone = { ...defMilestonePoint, ...await resolveWithIgnoreKnownError(db.get(MILSTONE_DOCID), defMilestonePoint) }; + remoteMilestone.node_chunk_info = { ...defMilestonePoint.node_chunk_info, ...remoteMilestone.node_chunk_info }; + const writeMilestone = remoteMilestone.node_chunk_info[deviceNodeID].min != currentVersionRange2.min || remoteMilestone.node_chunk_info[deviceNodeID].max != currentVersionRange2.max || typeof remoteMilestone._rev == "undefined"; + if (writeMilestone) { + remoteMilestone.node_chunk_info[deviceNodeID].min = currentVersionRange2.min; + remoteMilestone.node_chunk_info[deviceNodeID].max = currentVersionRange2.max; + await db.put(remoteMilestone); + } + let globalMin = currentVersionRange2.min; + let globalMax = currentVersionRange2.max; + for (const nodeId of remoteMilestone.accepted_nodes) { + if (nodeId == deviceNodeID) + 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; + } + } + if (globalMax < globalMin) { + if (!setting.ignoreVersionCheck) { + return "INCOMPATIBLE"; + } + } + if (remoteMilestone.locked) { + if (remoteMilestone.accepted_nodes.indexOf(deviceNodeID) == -1) { + return "NODE_LOCKED"; + } + return "LOCKED"; + } + return "OK"; +} + +// src/lib/src/LiveSyncLocalDB.ts +var LiveSyncLocalDB = class { + constructor(dbname, env) { + this.isReady = false; + this.hashCaches = new LRUCache(10, 10); + this.corruptedEntries = {}; + this.changeHandler = null; + this.leafArrivedCallbacks = {}; + this.docSeq = ""; + this.chunkVersion = -1; + this.maxChunkVersion = -1; + this.minChunkVersion = -1; + this.needScanning = false; + this.collectThrottleTimeout = null; + this.collectThrottleQueuedIds = []; + this.chunkCollectedCallbacks = {}; + this.auth = { + username: "", + password: "" + }; + this.dbname = dbname; + this.env = env; + this.refreshSettings(); + } + onunload() { + var _a, _b; + this.env.beforeOnUnload(this); + this.leafArrivedCallbacks; + (_a = this.changeHandler) == null ? void 0 : _a.cancel(); + (_b = this.changeHandler) == null ? void 0 : _b.removeAllListeners(); + this.localDatabase.removeAllListeners(); + } + refreshSettings() { + const settings = this.env.getSettings(); + this.settings = settings; + this.hashCaches = new LRUCache(settings.hashCacheMaxCount, settings.hashCacheMaxAmount); + } + id2path(filename) { + return this.env.id2path(filename); + } + path2id(filename) { + return this.env.path2id(filename); + } + async close() { + var _a, _b; + Logger("Database closed (by close)"); + this.isReady = false; + (_a = this.changeHandler) == null ? void 0 : _a.cancel(); + (_b = this.changeHandler) == null ? void 0 : _b.removeAllListeners(); + if (this.localDatabase != null) { + await this.localDatabase.close(); + } + this.env.onClose(this); + } + async initializeDatabase() { + var _a, _b; + await this.prepareHashFunctions(); + if (this.localDatabase != null) + await this.localDatabase.close(); + (_a = this.changeHandler) == null ? void 0 : _a.cancel(); + (_b = this.changeHandler) == null ? void 0 : _b.removeAllListeners(); + this.localDatabase = null; + this.localDatabase = this.env.createPouchDBInstance(this.dbname + "-livesync-v2", { + auto_compaction: false, + revs_limit: 100, + deterministic_revs: true + }); + await this.env.onInitializeDatabase(this); + Logger("Opening Database..."); + Logger("Database info", LOG_LEVEL.VERBOSE); + Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE); + this.localDatabase.on("close", () => { + var _a2; + Logger("Database closed."); + this.isReady = false; + this.localDatabase.removeAllListeners(); + (_a2 = this.env.getReplicator()) == null ? void 0 : _a2.closeReplication(); + }); + const changes3 = this.localDatabase.changes({ + since: "now", + live: true, + filter: (doc) => doc.type == "leaf" + }).on("change", (e2) => { + if (e2.deleted) + return; + this.leafArrived(e2.id); + this.docSeq = `${e2.seq}`; + }); + this.changeHandler = changes3; + this.isReady = true; + Logger("Database is now ready."); + return true; + } + 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((res2, 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); + res2(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 (isErrorOfMissingDoc(ex)) { + 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) { + return getDBEntryMeta(this, path, opt, includeDeleted); + } + async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) { + return getDBEntry(this, path, opt, dump, waitForReady, includeDeleted); + } + async deleteDBEntry(path, opt) { + return deleteDBEntry(this, path, opt); + } + async deleteDBEntryPrefix(prefixSrc) { + return deleteDBEntryPrefix(this, prefixSrc); + } + async putDBEntry(note, saveAsBigChunk) { + return putDBEntry(this, note, saveAsBigChunk); + } + async resetDatabase() { + var _a, _b; + (_a = this.changeHandler) == null ? void 0 : _a.cancel(); + (_b = this.changeHandler) == null ? void 0 : _b.removeAllListeners(); + this.env.getReplicator().closeReplication(); + await this.env.onResetDatabase(this); + Logger("Database closed for reset Database."); + this.isReady = false; + await this.localDatabase.destroy(); + this.localDatabase = null; + await this.initializeDatabase(); + Logger("Local Database Reset", LOG_LEVEL.NOTICE); + } + 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((e2) => "error" in e2)) { + 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(filenameSrc) { + const file = filenameSrc.startsWith("i:") ? filenameSrc.substring(2) : filenameSrc; + if (file.startsWith("ps:")) + return true; + if (file.includes(":")) + return false; + 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].ok) { + 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, waitForReady) { + const promises = ids.map((id) => new Promise((res3, rej) => { + if (typeof this.chunkCollectedCallbacks[id] == "undefined") { + this.chunkCollectedCallbacks[id] = { ok: [], failed: () => { + delete this.chunkCollectedCallbacks[id]; + rej(new Error("Failed to collect one of chunks")); + } }; + } + this.chunkCollectedCallbacks[id].ok.push((chunk) => { + res3(chunk); + }); + })); + this.collectThrottleQueuedIds = [.../* @__PURE__ */ new Set([...this.collectThrottleQueuedIds, ...ids])]; + this.execCollect(); + const res2 = await Promise.all(promises); + return res2; + } + execCollect() { + runWithLock("execCollect", true, async () => { + do { + const minimumInterval = this.settings.minimumIntervalOfReadChunksOnline; + const start = Date.now(); + const requesting = this.collectThrottleQueuedIds.splice(0, this.settings.concurrencyOfReadChunksOnline); + if (requesting.length == 0) + return; + try { + const chunks = await this.CollectChunksInternal(requesting, false); + if (chunks) { + this.collectThrottleQueuedIds = this.collectThrottleQueuedIds.filter((e2) => !chunks.some((f3) => f3._id == e2)); + for (const chunk of chunks) { + this.chunkCollected(chunk); + } + } else { + Logger(`Could not retrieve chunks`, LOG_LEVEL.NOTICE); + for (const id of requesting) { + if (id in this.chunkCollectedCallbacks) { + this.chunkCollectedCallbacks[id].failed(); + } + } + } + } catch (ex) { + Logger(`Exception raised while retrieving chunks`, LOG_LEVEL.NOTICE); + Logger(ex, LOG_LEVEL.VERBOSE); + for (const id of requesting) { + if (id in this.chunkCollectedCallbacks) { + this.chunkCollectedCallbacks[id].failed(); + } + } + } + const passed = Date.now() - start; + const intervalLeft = minimumInterval - passed; + if (this.collectThrottleQueuedIds.length == 0) + return; + await delay(intervalLeft < 0 ? 0 : intervalLeft); + } while (this.collectThrottleQueuedIds.length > 0); + }).then(() => { + }); + } + async CollectChunksInternal(ids, showResult = false) { + const localChunks = await this.localDatabase.allDocs({ keys: ids, include_docs: true }); + const missingChunks = localChunks.rows.filter((e2) => "error" in e2).map((e2) => e2.key); + if (missingChunks.length == 0) { + return localChunks.rows.map((e2) => e2.doc); + } + const remoteDocs = await this.env.getReplicator().fetchRemoteChunks(missingChunks, showResult); + if (remoteDocs == false) { + return false; + } + const max2 = remoteDocs.length; + remoteDocs.forEach((e2) => this.hashCaches.set(e2._id, e2.data)); + await this.localDatabase.bulkDocs(remoteDocs, { new_edits: false }); + let last = 0; + function findChunk(key) { + if (!remoteDocs) + throw Error("Chunk collecting error"); + const offset = last; + for (let i = 0; i < max2; i++) { + const idx = (offset + i) % max2; + last = i; + if (remoteDocs[idx]._id == key) + return remoteDocs[idx]; + } + throw Error("Chunk collecting error"); + } + return localChunks.rows.map((e2) => "error" in e2 ? findChunk(e2.key) : e2.doc); + } + async *findEntries(startKey, endKey, opt) { + const pageLimit = 100; + let nextKey = startKey; + do { + const docs = await this.localDatabase.allDocs({ limit: pageLimit, startkey: nextKey, endkey: endKey, include_docs: true, ...opt }); + 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") { + yield doc; + } + } + } while (nextKey != ""); + } + async *findAllDocs(opt) { + const f1 = this.findEntries("", "h:", opt != null ? opt : {}); + const f22 = this.findEntries(`h:\u{10FFFF}`, "", opt != null ? opt : {}); + for await (const f3 of f1) { + yield f3; + } + for await (const f3 of f22) { + yield f3; + } + } + async *findEntryNames(startKey, endKey, opt) { + const pageLimit = 100; + let nextKey = startKey; + do { + const docs = await this.localDatabase.allDocs({ limit: pageLimit, startkey: nextKey, endkey: endKey, ...opt }); + nextKey = ""; + for (const row of docs.rows) { + nextKey = `${row.id}\u{10FFFF}`; + yield row.id; + } + } while (nextKey != ""); + } + async *findAllDocNames(opt) { + const targets = [ + this.findEntryNames("", "h:", opt != null ? opt : {}), + this.findEntryNames(`h:\u{10FFFF}`, "i:", opt != null ? opt : {}), + this.findEntryNames(`i:\u{10FFFF}`, "ps:", opt != null ? opt : {}), + this.findEntryNames(`ps:\u{10FFFF}`, "", opt != null ? opt : {}) + ]; + for (const target of targets) { + for await (const f3 of target) { + if (f3.startsWith("_")) + continue; + if (f3 == VERSIONINFO_DOCID) + continue; + yield f3; + } + } + } +}; + +// src/lib/src/LiveSyncReplicator.ts +var currentVersionRange = { + min: 0, + max: 2, + current: 2 +}; +async function* genReplication(s, signal) { + const p = []; + let locker = () => Promise.resolve(); + let unlock = () => { + locker = () => new Promise((res2) => unlock = res2); + }; + unlock(); + const push = function(e2) { + p.push(e2); + unlock(); + }; + s.on("complete", (result) => push(["complete", result])); + s.on("change", (result) => push(["change", result])); + s.on("active", () => push(["active"])); + s.on("denied", (err) => push(["denied", err])); + s.on("error", (err) => push(["error", err])); + s.on("paused", (err) => push(["paused", err])); + s.then(() => push(["finally"])).catch(() => push(["finally"])); + try { + L1: + do { + const r = p.shift(); + if (r) { + yield r; + if (r[0] == "finally") + break; + continue; + } else { + const dx = async () => { + await locker(); + return true; + }; + do { + const timeout = async () => { + await delay(100); + return false; + }; + const raced = await Promise.race([dx(), timeout()]); + if (raced) + continue L1; + if (signal.aborted) + break L1; + } while (true); + } + } while (true); + } finally { + s.cancel(); + } +} +var LiveSyncDBReplicator = class { + constructor(env) { + this.syncStatus = "NOT_CONNECTED"; + this.docArrived = 0; + this.docSent = 0; + this.lastSyncPullSeq = 0; + this.maxPullSeq = 0; + this.lastSyncPushSeq = 0; + this.maxPushSeq = 0; + this.originalSetting = null; + this.nodeid = ""; + this.remoteLocked = false; + this.remoteLockedAndDeviceNotAccepted = false; + this.updateInfo = () => { + this.env.replicationStat.set({ + sent: this.docSent, + arrived: this.docArrived, + maxPullSeq: this.maxPullSeq, + maxPushSeq: this.maxPushSeq, + lastSyncPullSeq: this.lastSyncPullSeq, + lastSyncPushSeq: this.lastSyncPushSeq, + syncStatus: this.syncStatus + }); + }; + this.env = env; + this.initializeDatabaseForReplication(); + this.env.getDatabase().on("close", () => { + this.closeReplication(); + }); + } + async initializeDatabaseForReplication() { + const db = this.env.getDatabase(); + try { + const nodeinfo = await resolveWithIgnoreKnownError(db.get(NODEINFO_DOCID), { + _id: NODEINFO_DOCID, + type: "nodeinfo", + nodeid: "", + v20220607: true + }); + if (nodeinfo.nodeid == "") { + nodeinfo.nodeid = Math.random().toString(36).slice(-10); + await db.put(nodeinfo); + } + this.nodeid = nodeinfo.nodeid; + await putDesignDocuments(db); + } catch (ex) { + Logger(ex); + return false; + } + } + async migrate(from, to) { + Logger(`Database updated from ${from} to ${to}`, LOG_LEVEL.NOTICE); + return true; + } + terminateSync() { + if (!this.controller) { + return; + } + this.controller.abort(); + this.controller = null; + } + async openReplication(setting, keepAlive, showResult) { + await this.initializeDatabaseForReplication(); + if (keepAlive) { + this.openContinuousReplication(setting, showResult, false); + } else { + return this.openOneShotReplication(setting, showResult, false, "sync"); + } + } + replicationActivated(showResult) { + this.syncStatus = "CONNECTED"; + this.updateInfo(); + Logger("Replication activated", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); + } + async replicationChangeDetected(e2, showResult, docSentOnStart, docArrivedOnStart) { + try { + if (e2.direction == "pull") { + await this.env.processReplication(e2.change.docs); + this.docArrived += e2.change.docs.length; + } else { + this.docSent += e2.change.docs.length; + } + if (showResult) { + const maxPullSeq = this.maxPullSeq; + const maxPushSeq = this.maxPushSeq; + const lastSyncPullSeq = this.lastSyncPullSeq; + const lastSyncPushSeq = this.lastSyncPushSeq; + const pushLast = lastSyncPushSeq == 0 ? "" : lastSyncPushSeq >= maxPushSeq ? " (LIVE)" : ` (${maxPushSeq - lastSyncPushSeq})`; + const pullLast = lastSyncPullSeq == 0 ? "" : lastSyncPullSeq >= maxPullSeq ? " (LIVE)" : ` (${maxPullSeq - lastSyncPullSeq})`; + Logger(`\u2191${this.docSent - docSentOnStart}${pushLast} \u2193${this.docArrived - docArrivedOnStart}${pullLast}`, 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.terminateSync(); + } + replicationDenied(e2) { + this.syncStatus = "ERRORED"; + this.updateInfo(); + this.terminateSync(); + Logger("Replication denied", LOG_LEVEL.NOTICE, "sync"); + Logger(e2); + } + replicationErrored(e2) { + this.syncStatus = "ERRORED"; + this.terminateSync(); + this.updateInfo(); + Logger("Replication error", LOG_LEVEL.NOTICE, "sync"); + Logger(e2); + } + replicationPaused() { + this.syncStatus = "PAUSED"; + this.updateInfo(); + Logger("replication paused", LOG_LEVEL.VERBOSE, "sync"); + } + async processSync(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying) { + const controller = new AbortController(); + if (this.controller) { + this.controller.abort(); + } + this.controller = controller; + const gen = genReplication(syncHandler, controller.signal); + try { + for await (const [type, e2] of gen) { + switch (type) { + case "change": + if ("direction" in e2) { + if (e2.direction == "pull") { + this.lastSyncPullSeq = Number(`${e2.change.last_seq}`.split("-")[0]); + } else { + this.lastSyncPushSeq = Number(`${e2.change.last_seq}`.split("-")[0]); + } + await this.replicationChangeDetected(e2, showResult, docSentOnStart, docArrivedOnStart); + } else { + if (syncMode == "pullOnly") { + this.lastSyncPullSeq = Number(`${e2.last_seq}`.split("-")[0]); + await this.replicationChangeDetected({ direction: "pull", change: e2 }, showResult, docSentOnStart, docArrivedOnStart); + } else if (syncMode == "pushOnly") { + this.lastSyncPushSeq = Number(`${e2.last_seq}`.split("-")[0]); + this.updateInfo(); + await this.replicationChangeDetected({ direction: "push", change: e2 }, showResult, docSentOnStart, docArrivedOnStart); + } + } + if (retrying) { + if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) { + return "NEED_RESURRECT"; + } + } + break; + case "complete": + this.replicationCompleted(showResult); + return "DONE"; + case "active": + this.replicationActivated(showResult); + break; + case "denied": + this.replicationDenied(e2); + return "FAILED"; + case "error": + this.replicationErrored(e2); + Logger("Replication stopped.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); + if (this.env.getLastPostFailedBySize()) { + if (e2 && (e2 == null ? void 0 : e2.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; + } + return "NEED_RETRY"; + } else { + Logger("Replication error", LOG_LEVEL.NOTICE, "sync"); + Logger(e2); + } + return "FAILED"; + case "paused": + this.replicationPaused(); + break; + case "finally": + break; + default: + Logger(`Unexpected synchronization status:${JSON.stringify(e2)}`); + } + } + return "DONE"; + } catch (ex) { + Logger(`Unexpected synchronization exception`); + Logger(ex, LOG_LEVEL.VERBOSE); + } finally { + this.terminateSync(); + this.controller = null; + } + } + async openOneShotReplication(setting, showResult, retrying, syncMode) { + if (this.controller != null) { + Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "sync"); + return; + } + const localDB = this.env.getDatabase(); + Logger(`OneShot Sync begin... (${syncMode})`); + 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; + } + this.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]); + this.maxPushSeq = Number(`${(await localDB.info()).update_seq}`.split("-")[0]); + 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.terminateSync(); + let syncHandler; + if (syncMode == "sync") { + syncHandler = localDB.sync(db, { checkpoint: "target", ...syncOptionBase }); + } else if (syncMode == "pullOnly") { + syncHandler = localDB.replicate.from(db, { checkpoint: "target", ...syncOptionBase, ...setting.readChunksOnline ? { filter: "replicate/pull" } : {} }); + } else if (syncMode == "pushOnly") { + syncHandler = localDB.replicate.to(db, { checkpoint: "target", ...syncOptionBase, ...setting.readChunksOnline ? { filter: "replicate/push" } : {} }); + } + const syncResult = await this.processSync(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying); + if (syncResult == "DONE") { + return true; + } + if (syncResult == "FAILED") { + return false; + } + if (syncResult == "NEED_RESURRECT") { + this.terminateSync(); + return await this.openOneShotReplication(this.originalSetting, showResult, false, syncMode); + } + if (syncResult == "NEED_RETRY") { + 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); + return false; + } else { + Logger(`Retry with lower batch size:${tempSetting.batch_size}/${tempSetting.batches_limit}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); + return await this.openOneShotReplication(tempSetting, showResult, true, syncMode); + } + } + return false; + } + replicateAllToServer(setting, showingNotice) { + return this.openOneShotReplication( + setting, + showingNotice != null ? showingNotice : false, + false, + "pushOnly" + ); + } + replicateAllFromServer(setting, showingNotice) { + return this.openOneShotReplication(setting, showingNotice, false, "pullOnly"); + } + async checkReplicationConnectivity(setting, keepAlive, skipCheck, showResult) { + 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.controller != null) { + Logger("Another replication running."); + return false; + } + const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.env.getIsMobile()); + 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 ensure = await ensureDatabaseIsCompatible(dbRet.db, setting, this.nodeid, currentVersionRange); + if (ensure == "INCOMPATIBLE") { + Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", LOG_LEVEL.NOTICE); + return false; + } else if (ensure == "NODE_LOCKED") { + 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); + this.remoteLockedAndDeviceNotAccepted = true; + this.remoteLocked = true; + return false; + } else if (ensure == "LOCKED") { + this.remoteLocked = true; + } + } + 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: setting.useTimeouts ? false : 3e4, ...syncOptionBase } : { ...syncOptionBase }; + return { db: dbRet.db, info: dbRet.info, syncOptionBase, syncOption }; + } + async openContinuousReplication(setting, showResult, retrying) { + if (this.controller != null) { + Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); + return; + } + const localDB = this.env.getDatabase(); + Logger("Before LiveSync, start OneShot once..."); + if (await this.openOneShotReplication( + setting, + showResult, + false, + "pullOnly" + )) { + 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.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]); + this.maxPushSeq = Number(`${(await localDB.info()).update_seq}`.split("-")[0]); + this.updateInfo(); + const docArrivedOnStart = this.docArrived; + const docSentOnStart = this.docSent; + if (!retrying) { + this.originalSetting = setting; + } + this.terminateSync(); + const syncHandler = localDB.sync(db, { + ...syncOption, + pull: { + checkpoint: "target" + }, + push: { + checkpoint: "source" + } + }); + const syncMode = "sync"; + const syncResult = await this.processSync(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying); + if (syncResult == "DONE") { + return true; + } + if (syncResult == "FAILED") { + return false; + } + if (syncResult == "NEED_RESURRECT") { + this.terminateSync(); + return await this.openContinuousReplication(this.originalSetting, showResult, false); + } + if (syncResult == "NEED_RETRY") { + 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); + return false; + } else { + Logger(`Retry with lower batch size:${tempSetting.batch_size}/${tempSetting.batches_limit}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); + return await this.openContinuousReplication(tempSetting, showResult, true); + } + } + } + } + closeReplication() { + if (!this.controller) { + return; + } + this.controller.abort(); + this.controller = null; + this.syncStatus = "CLOSED"; + Logger("Replication closed"); + this.updateInfo(); + } + async tryResetRemoteDatabase(setting) { + this.closeReplication(); + const con = await this.connectRemoteCouchDBWithSetting(setting, this.env.getIsMobile()); + 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.env.getIsMobile()); + 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.env.getIsMobile()); + 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.env.getIsMobile()); + 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(/* @__PURE__ */ new Set([...remoteMilestone.accepted_nodes, this.nodeid])); + Logger("Mark this device as 'resolved'.", LOG_LEVEL.NOTICE); + await dbRet.db.put(remoteMilestone); + } + connectRemoteCouchDBWithSetting(settings, isMobile) { + if (settings.encrypt && settings.passphrase == "" && !settings.permitEmptyPassphrase) { + return "Empty passphrases cannot be used without explicit permission"; + } + return this.env.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, + settings.useDynamicIterationCount + ); + } + async fetchRemoteChunks(missingChunks, showResult) { + const ret = await this.connectRemoteCouchDBWithSetting(this.env.getSettings(), this.env.getIsMobile()); + 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((e2) => "error" in e2)) { + Logger(`Some chunks are not exists both on remote and local database.`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO, "fetch"); + return false; + } + const remoteChunkItems = remoteChunks.rows.map((e2) => e2.doc); + return remoteChunkItems; + } +}; + +// 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 = /* @__PURE__ */ new WeakMap(); +var transactionDoneMap = /* @__PURE__ */ new WeakMap(); +var transactionStoreNamesMap = /* @__PURE__ */ new WeakMap(); +var transformCache = /* @__PURE__ */ new WeakMap(); +var reverseTransformCache = /* @__PURE__ */ 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, version2, { blocked, upgrade, blocking, terminated } = {}) { + const request = indexedDB.open(name, version2); + const openPromise = wrap(request); + if (upgrade) { + request.addEventListener("upgradeneeded", (event) => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); + }); + } + if (blocked) { + request.addEventListener("blocked", (event) => blocked( + event.oldVersion, + event.newVersion, + event + )); + } + openPromise.then((db) => { + if (terminated) + db.addEventListener("close", () => terminated()); + if (blocking) { + db.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event)); + } + }).catch(() => { + }); + return openPromise; +} +function deleteDB(name, { blocked } = {}) { + const request = indexedDB.deleteDatabase(name); + if (blocked) { + request.addEventListener("blocked", (event) => blocked( + event.oldVersion, + event + )); + } + return wrap(request).then(() => void 0); +} +var readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; +var writeMethods = ["put", "add", "delete", "clear"]; +var cachedMethods = /* @__PURE__ */ 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(query3, count) { + return db.getAllKeys(storeKey, query3, count); + }, + close() { + delete databaseCache[dbKey]; + return db.close(); + }, + async destroy() { + delete databaseCache[dbKey]; + db.close(); + await deleteDB(dbKey); + } + }; +}; + +// src/JsonResolvePane.svelte +var import_diff_match_patch3 = __toESM(require_diff_match_patch(), 1); +function add_css2(target) { + append_styles(target, "svelte-guf68w", ".deleted.svelte-guf68w{text-decoration:line-through}.svelte-guf68w{box-sizing:border-box}.scroller.svelte-guf68w{display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text}.json-source.svelte-guf68w{white-space:pre;height:auto;overflow:auto;min-height:var(--font-ui-medium);flex-grow:1}"); +} +function get_each_context2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[23] = list[i]; + return child_ctx; +} +function get_each_context_12(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[26] = list[i]; + return child_ctx; +} +function create_else_block2(ctx) { + let div0; + let t0; + let t1; + let div1; + let t2; + let t3_value = revStringToRevNumber(ctx[0]._rev) + ""; + let t3; + let t4; + let t5_value = new Date(ctx[0].mtime).toLocaleString() + ""; + let t5; + let t6; + let t7_value = ctx[2].length + ""; + let t7; + let t8; + let t9; + let div2; + let t10; + let t11_value = revStringToRevNumber(ctx[1]._rev) + ""; + let t11; + let t12; + let t13_value = new Date(ctx[1].mtime).toLocaleString() + ""; + let t13; + let t14; + let t15_value = ctx[3].length + ""; + let t15; + let t16; + let t17; + let div3; + let button; + let mounted; + let dispose; + let each_value_1 = ctx[9]; + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_12(get_each_context_12(ctx, each_value_1, i)); + } + function select_block_type_1(ctx2, dirty) { + if (ctx2[5] != false) + return create_if_block_12; + return create_else_block_12; + } + let current_block_type = select_block_type_1(ctx, -1); + let if_block = current_block_type(ctx); + return { + c() { + div0 = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + t0 = space(); + if_block.c(); + t1 = space(); + div1 = element("div"); + t2 = text("A Rev:"); + t3 = text(t3_value); + t4 = text(" ,"); + t5 = text(t5_value); + t6 = space(); + t7 = text(t7_value); + t8 = text(" letters"); + t9 = space(); + div2 = element("div"); + t10 = text("B Rev:"); + t11 = text(t11_value); + t12 = text(" ,"); + t13 = text(t13_value); + t14 = space(); + t15 = text(t15_value); + t16 = text(" letters"); + t17 = space(); + div3 = element("div"); + button = element("button"); + button.textContent = "Apply"; + attr(div0, "class", "options svelte-guf68w"); + attr(div1, "class", "svelte-guf68w"); + attr(div2, "class", "svelte-guf68w"); + attr(button, "class", "svelte-guf68w"); + attr(div3, "class", "buttons svelte-guf68w"); + }, + m(target, anchor) { + insert(target, div0, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div0, null); + } + insert(target, t0, anchor); + if_block.m(target, anchor); + insert(target, t1, anchor); + insert(target, div1, anchor); + append(div1, t2); + append(div1, t3); + append(div1, t4); + append(div1, t5); + append(div1, t6); + append(div1, t7); + append(div1, t8); + insert(target, t9, anchor); + insert(target, div2, anchor); + append(div2, t10); + append(div2, t11); + append(div2, t12); + append(div2, t13); + append(div2, t14); + append(div2, t15); + append(div2, t16); + insert(target, t17, anchor); + insert(target, div3, anchor); + append(div3, button); + if (!mounted) { + dispose = listen(button, "click", ctx[10]); + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 592) { + each_value_1 = ctx2[9]; + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_12(ctx2, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block_12(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(div0, null); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].d(1); + } + each_blocks.length = each_value_1.length; + } + if (current_block_type === (current_block_type = select_block_type_1(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(t1.parentNode, t1); + } + } + if (dirty & 1 && t3_value !== (t3_value = revStringToRevNumber(ctx2[0]._rev) + "")) + set_data(t3, t3_value); + if (dirty & 1 && t5_value !== (t5_value = new Date(ctx2[0].mtime).toLocaleString() + "")) + set_data(t5, t5_value); + if (dirty & 4 && t7_value !== (t7_value = ctx2[2].length + "")) + set_data(t7, t7_value); + if (dirty & 2 && t11_value !== (t11_value = revStringToRevNumber(ctx2[1]._rev) + "")) + set_data(t11, t11_value); + if (dirty & 2 && t13_value !== (t13_value = new Date(ctx2[1].mtime).toLocaleString() + "")) + set_data(t13, t13_value); + if (dirty & 8 && t15_value !== (t15_value = ctx2[3].length + "")) + set_data(t15, t15_value); + }, + d(detaching) { + if (detaching) + detach(div0); + destroy_each(each_blocks, detaching); + if (detaching) + detach(t0); + if_block.d(detaching); + if (detaching) + detach(t1); + if (detaching) + detach(div1); + if (detaching) + detach(t9); + if (detaching) + detach(div2); + if (detaching) + detach(t17); + if (detaching) + detach(div3); + mounted = false; + dispose(); + } + }; +} +function create_if_block2(ctx) { + let div0; + let t1; + let div1; + let button; + let mounted; + let dispose; + return { + c() { + div0 = element("div"); + div0.textContent = "Just for a minute, please!"; + t1 = space(); + div1 = element("div"); + button = element("button"); + button.textContent = "Dismiss"; + attr(div0, "class", "message svelte-guf68w"); + attr(button, "class", "svelte-guf68w"); + attr(div1, "class", "buttons svelte-guf68w"); + }, + m(target, anchor) { + insert(target, div0, anchor); + insert(target, t1, anchor); + insert(target, div1, anchor); + append(div1, button); + if (!mounted) { + dispose = listen(button, "click", ctx[10]); + mounted = true; + } + }, + p: noop, + d(detaching) { + if (detaching) + detach(div0); + if (detaching) + detach(t1); + if (detaching) + detach(div1); + mounted = false; + dispose(); + } + }; +} +function create_if_block_22(ctx) { + let label; + let input; + let input_value_value; + let t0; + let div; + let t1_value = ctx[26][1] + ""; + let t1; + let label_class_value; + let mounted; + let dispose; + return { + c() { + label = element("label"); + input = element("input"); + t0 = space(); + div = element("div"); + t1 = text(t1_value); + attr(input, "type", "radio"); + attr(input, "name", "disp"); + input.__value = input_value_value = ctx[26][0]; + input.value = input.__value; + attr(input, "class", "sls-setting-tab svelte-guf68w"); + ctx[19][0].push(input); + attr(div, "class", "sls-setting-menu-btn svelte-guf68w"); + attr(label, "class", label_class_value = null_to_empty(`sls-setting-label ${ctx[26][0] == ctx[4] ? "selected" : ""}`) + " svelte-guf68w"); + }, + m(target, anchor) { + insert(target, label, anchor); + append(label, input); + input.checked = input.__value === ctx[4]; + append(label, t0); + append(label, div); + append(div, t1); + if (!mounted) { + dispose = listen(input, "change", ctx[18]); + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 16) { + input.checked = input.__value === ctx2[4]; + } + if (dirty & 16 && label_class_value !== (label_class_value = null_to_empty(`sls-setting-label ${ctx2[26][0] == ctx2[4] ? "selected" : ""}`) + " svelte-guf68w")) { + attr(label, "class", label_class_value); + } + }, + d(detaching) { + if (detaching) + detach(label); + ctx[19][0].splice(ctx[19][0].indexOf(input), 1); + mounted = false; + dispose(); + } + }; +} +function create_each_block_12(ctx) { + let if_block_anchor; + let if_block = (ctx[26][0] == "" || ctx[6][ctx[26][0]] != false) && create_if_block_22(ctx); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx2, dirty) { + if (ctx2[26][0] == "" || ctx2[6][ctx2[26][0]] != false) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block_22(ctx2); + if_block.c(); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + }, + d(detaching) { + if (if_block) + if_block.d(detaching); + if (detaching) + detach(if_block_anchor); + } + }; +} +function create_else_block_12(ctx) { + let t2; + return { + c() { + t2 = text("NO PREVIEW"); + }, + m(target, anchor) { + insert(target, t2, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(t2); + } + }; +} +function create_if_block_12(ctx) { + let div; + let each_value = ctx[7]; + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i)); + } + return { + c() { + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div, "class", "op-scrollable json-source svelte-guf68w"); + }, + m(target, anchor) { + insert(target, div, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div, null); + } + }, + p(ctx2, dirty) { + if (dirty & 128) { + each_value = ctx2[7]; + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context2(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block2(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(div, null); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].d(1); + } + each_blocks.length = each_value.length; + } + }, + d(detaching) { + if (detaching) + detach(div); + destroy_each(each_blocks, detaching); + } + }; +} +function create_each_block2(ctx) { + let span; + let t_value = ctx[23][1] + ""; + let t2; + let span_class_value; + return { + c() { + span = element("span"); + t2 = text(t_value); + attr(span, "class", span_class_value = null_to_empty(ctx[23][0] == import_diff_match_patch3.DIFF_DELETE ? "deleted" : ctx[23][0] == import_diff_match_patch3.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w"); + }, + m(target, anchor) { + insert(target, span, anchor); + append(span, t2); + }, + p(ctx2, dirty) { + if (dirty & 128 && t_value !== (t_value = ctx2[23][1] + "")) + set_data(t2, t_value); + if (dirty & 128 && span_class_value !== (span_class_value = null_to_empty(ctx2[23][0] == import_diff_match_patch3.DIFF_DELETE ? "deleted" : ctx2[23][0] == import_diff_match_patch3.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w")) { + attr(span, "class", span_class_value); + } + }, + d(detaching) { + if (detaching) + detach(span); + } + }; +} +function create_fragment2(ctx) { + let h1; + let t1; + let div; + let span; + let t2; + let t3; + let if_block_anchor; + function select_block_type(ctx2, dirty) { + if (!ctx2[0] || !ctx2[1]) + return create_if_block2; + return create_else_block2; + } + let current_block_type = select_block_type(ctx, -1); + let if_block = current_block_type(ctx); + return { + c() { + h1 = element("h1"); + h1.textContent = "Conflicted settings"; + t1 = space(); + div = element("div"); + span = element("span"); + t2 = text(ctx[8]); + t3 = space(); + if_block.c(); + if_block_anchor = empty(); + attr(h1, "class", "svelte-guf68w"); + attr(span, "class", "svelte-guf68w"); + attr(div, "class", "svelte-guf68w"); + }, + m(target, anchor) { + insert(target, h1, anchor); + insert(target, t1, anchor); + insert(target, div, anchor); + append(div, span); + append(span, t2); + insert(target, t3, anchor); + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx2, [dirty]) { + if (dirty & 256) + set_data(t2, ctx2[8]); + 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(if_block_anchor.parentNode, if_block_anchor); + } + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) + detach(h1); + if (detaching) + detach(t1); + if (detaching) + detach(div); + if (detaching) + detach(t3); + if_block.d(detaching); + if (detaching) + detach(if_block_anchor); + } + }; +} +function revStringToRevNumber(rev2) { + return rev2.split("-")[0]; +} +function instance2($$self, $$props, $$invalidate) { + let mergedObjs; + let selectedObj; + let filename; + var _a; + let { docs = [] } = $$props; + let { callback = async (_, __) => { + Promise.resolve(); + } } = $$props; + let docA = void 0; + let docB = void 0; + let docAContent = ""; + let docBContent = ""; + let objA = {}; + let objB = {}; + let objAB = {}; + let objBA = {}; + let diffs; + const modes = [["", "Not now"], ["A", "A"], ["B", "B"], ["AB", "A + B"], ["BA", "B + A"]]; + let mode = ""; + function docToString(doc) { + return doc.datatype == "plain" ? getDocData(doc.data) : base64ToString(doc.data); + } + function getDiff(left, right) { + const dmp = new import_diff_match_patch3.diff_match_patch(); + const mapLeft = dmp.diff_linesToChars_(left, right); + const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false); + dmp.diff_charsToLines_(diffLeftSrc, mapLeft.lineArray); + return diffLeftSrc; + } + function getJsonDiff(a2, b) { + return getDiff(JSON.stringify(a2, null, 2), JSON.stringify(b, null, 2)); + } + function apply() { + if (mode == "A") + return callback(docA._rev, null); + if (mode == "B") + return callback(docB._rev, null); + if (mode == "BA") + return callback(null, JSON.stringify(objBA, null, 2)); + if (mode == "AB") + return callback(null, JSON.stringify(objAB, null, 2)); + callback(null, null); + } + const $$binding_groups = [[]]; + function input_change_handler() { + mode = this.__value; + $$invalidate(4, mode); + } + $$self.$$set = ($$props2) => { + if ("docs" in $$props2) + $$invalidate(11, docs = $$props2.docs); + if ("callback" in $$props2) + $$invalidate(12, callback = $$props2.callback); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & 247823) { + $: { + if (docs && docs.length >= 1) { + if (docs[0].mtime < docs[1].mtime) { + $$invalidate(0, docA = docs[0]); + $$invalidate(1, docB = docs[1]); + } else { + $$invalidate(0, docA = docs[1]); + $$invalidate(1, docB = docs[0]); + } + $$invalidate(2, docAContent = docToString(docA)); + $$invalidate(3, docBContent = docToString(docB)); + try { + $$invalidate(14, objA = false); + $$invalidate(15, objB = false); + $$invalidate(14, objA = JSON.parse(docAContent)); + $$invalidate(15, objB = JSON.parse(docBContent)); + $$invalidate(16, objAB = mergeObject(objA, objB)); + $$invalidate(17, objBA = mergeObject(objB, objA)); + if (JSON.stringify(objAB) == JSON.stringify(objBA)) { + $$invalidate(17, objBA = false); + } + } catch (ex) { + $$invalidate(17, objBA = false); + $$invalidate(16, objAB = false); + } + } + } + } + if ($$self.$$.dirty & 245760) { + $: + $$invalidate(6, mergedObjs = { + "": false, + A: objA, + B: objB, + AB: objAB, + BA: objBA + }); + } + if ($$self.$$.dirty & 80) { + $: + $$invalidate(5, selectedObj = mode in mergedObjs ? mergedObjs[mode] : {}); + } + if ($$self.$$.dirty & 16416) { + $: { + $$invalidate(7, diffs = getJsonDiff(objA, selectedObj)); + console.dir(selectedObj); + } + } + if ($$self.$$.dirty & 8193) { + $: + $$invalidate(8, filename = id2path($$invalidate(13, _a = docA === null || docA === void 0 ? void 0 : docA._id) !== null && _a !== void 0 ? _a : "")); + } + }; + return [ + docA, + docB, + docAContent, + docBContent, + mode, + selectedObj, + mergedObjs, + diffs, + filename, + modes, + apply, + docs, + callback, + _a, + objA, + objB, + objAB, + objBA, + input_change_handler, + $$binding_groups + ]; +} +var JsonResolvePane = class extends SvelteComponent { + constructor(options) { + super(); + init2(this, options, instance2, create_fragment2, safe_not_equal, { docs: 11, callback: 12 }, add_css2); + } +}; +var JsonResolvePane_default = JsonResolvePane; + +// src/JsonResolveModal.ts +var JsonResolveModal = class extends import_obsidian.Modal { + constructor(app2, filename, docs, callback) { + super(app2); + this.callback = callback; + this.filename = filename; + this.docs = docs; + } + async UICallback(keepRev, mergedStr) { + this.close(); + await this.callback(keepRev, mergedStr); + this.callback = null; + } + onOpen() { + const { contentEl } = this; + contentEl.empty(); + if (this.component == null) { + this.component = new JsonResolvePane_default({ + target: contentEl, + props: { + docs: this.docs, + callback: (keepRev, mergedStr) => this.UICallback(keepRev, mergedStr) + } + }); + } + return; + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + if (this.callback != null) { + this.callback(null); + } + if (this.component != null) { + this.component.$destroy(); + this.component = null; + } + } +}; + +// src/CmdHiddenFileSync.ts +var HiddenFileSync = class extends LiveSyncCommands { + constructor() { + super(...arguments); + this.periodicInternalFileScanProcessor = new PeriodicProcessor(this.plugin, async () => await this.syncInternalFilesAndDatabase("push", false)); + this.confirmPopup = null; + this.procInternalFiles = []; + this.recentProcessedInternalFiles = []; + } + get kvDB() { + return this.plugin.kvDB; + } + ensureDirectoryEx(fullPath) { + return this.plugin.ensureDirectoryEx(fullPath); + } + getConflictedDoc(path, rev2) { + return this.plugin.getConflictedDoc(path, rev2); + } + onunload() { + var _a; + (_a = this.periodicInternalFileScanProcessor) == null ? void 0 : _a.disable(); + } + onload() { + this.plugin.addCommand({ + id: "livesync-scaninternal", + name: "Sync hidden files", + callback: () => { + this.syncInternalFilesAndDatabase("safe", true); + } + }); + } + async onInitializeDatabase(showNotice) { + if (this.settings.syncInternalFiles) { + try { + Logger("Synchronizing hidden files..."); + await this.syncInternalFilesAndDatabase("push", showNotice); + Logger("Synchronizing hidden files done"); + } catch (ex) { + Logger("Synchronizing hidden files failed"); + Logger(ex, LOG_LEVEL.VERBOSE); + } + } + } + async beforeReplicate(showNotice) { + if (this.settings.syncInternalFiles && this.settings.syncInternalFilesBeforeReplication && !this.settings.watchInternalFileChanges) { + await this.syncInternalFilesAndDatabase("push", showNotice); + } + } + async onResume() { + if (this.plugin.suspended) + return; + if (this.settings.syncInternalFiles) { + await this.syncInternalFilesAndDatabase("safe", false); + } + this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? this.settings.syncInternalFilesInterval * 1e3 : 0); + } + parseReplicationResultItem(docs) { + return false; + } + realizeSettingSyncMode() { + var _a; + (_a = this.periodicInternalFileScanProcessor) == null ? void 0 : _a.disable(); + this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? this.settings.syncInternalFilesInterval * 1e3 : 0); + return; + } + 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`); + }); + } + procInternalFile(filename) { + this.procInternalFiles.push(filename); + scheduleTask("procInternal", 500, async () => { + await this.execInternalFile(); + }); + } + 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 = filename2idInternalMetadata(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 }); + const pluginDir = this.app.vault.configDir + "/plugins/"; + const pluginFiles = ["manifest.json", "data.json", "style.css", "main.js"]; + if (path.startsWith(pluginDir) && pluginFiles.some((e2) => path.endsWith(e2)) && this.settings.usePluginSync) { + const pluginName = trimPrefix(path, pluginDir).split("/")[0]; + await this.plugin.addOnPluginAndTheirSettings.sweepPlugin(false, pluginName); + } + } + } + async resolveConflictOnInternalFiles() { + const conflicted = this.localDatabase.findEntries(ICHeader, ICHeaderEnd, { conflicts: true }); + for await (const doc of conflicted) { + if (!("_conflicts" in doc)) + continue; + if (isInternalMetadata(doc._id)) { + await this.resolveConflictOnInternalFile(doc._id); + } + } + } + async resolveConflictOnInternalFile(id) { + var _a, _b; + try { + 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:${id2filenameInternalMetadata(id)}`); + const conflicts = doc._conflicts.sort((a2, b) => Number(a2.split("-")[0]) - Number(b.split("-")[0])); + const revA = doc._rev; + const revB = conflicts[0]; + if (doc._id.endsWith(".json")) { + const conflictedRev = conflicts[0]; + const conflictedRevNo = Number(conflictedRev.split("-")[0]); + const revFrom = await this.localDatabase.localDatabase.get(id, { revs_info: true }); + const commonBase = (_b = (_a = revFrom._revs_info.filter((e2) => e2.status == "available" && Number(e2.rev.split("-")[0]) < conflictedRevNo).first()) == null ? void 0 : _a.rev) != null ? _b : ""; + const result = await this.plugin.mergeObject(id, commonBase, doc._rev, conflictedRev); + if (result) { + Logger(`Object merge:${id}`, LOG_LEVEL.INFO); + const filename = id2filenameInternalMetadata(id); + const isExists = await this.app.vault.adapter.exists(filename); + if (!isExists) { + await this.ensureDirectoryEx(filename); + } + await this.app.vault.adapter.write(filename, result); + const stat = await this.app.vault.adapter.stat(filename); + await this.storeInternalFileToDatabase({ path: filename, ...stat }); + await this.extractInternalFileFromDatabase(filename); + await this.localDatabase.localDatabase.remove(id, revB); + return this.resolveConflictOnInternalFile(id); + } else { + Logger(`Object merge is not applicable.`, LOG_LEVEL.VERBOSE); + } + const docAMerge = await this.localDatabase.getDBEntry(id, { rev: revA }); + const docBMerge = await this.localDatabase.getDBEntry(id, { rev: revB }); + if (docAMerge != false && docBMerge != false) { + if (await this.showJSONMergeDialogAndMerge(docAMerge, docBMerge)) { + await delay(200); + return this.resolveConflictOnInternalFile(id); + } + return false; + } + } + 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:${id2filenameInternalMetadata(id)}`); + return this.resolveConflictOnInternalFile(id); + } catch (ex) { + Logger("Failed to resolve conflict (Hidden)"); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + } + 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.replace(/\n| /g, "").split(",").filter((e2) => e2).map((e2) => new RegExp(e2, "i")); + if (!files) + files = await this.scanInternalFiles(); + const filesOnDB = (await this.localDatabase.localDatabase.allDocs({ startkey: ICHeader, endkey: ICHeaderEnd, include_docs: true })).rows.map((e2) => e2.doc).filter((e2) => !e2.deleted); + const allFileNamesSrc = [.../* @__PURE__ */ new Set([...files.map((e2) => (0, import_obsidian.normalizePath)(e2.path)), ...filesOnDB.map((e2) => (0, import_obsidian.normalizePath)(id2path(id2filenameInternalMetadata(e2._id))))])]; + const allFileNames = allFileNamesSrc.filter((filename) => !targetFiles || targetFiles && targetFiles.indexOf(filename) !== -1); + function compareMTime(a2, b) { + const wa = ~~(a2 / 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_obsidian.normalizePath)(pathPieces); + if (!(pathPieces in updatedFolders)) { + updatedFolders[pathPieces] = 0; + } + updatedFolders[pathPieces]++; + c = pieces.shift(); + } + }; + const p = []; + const semaphore = Semaphore(10); + let caches = {}; + caches = await this.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((e2) => filename.match(e2))) + continue; + const fileOnStorage = files.find((e2) => e2.path == filename); + const fileOnDatabase = filesOnDB.find((e2) => e2._id == filename2idInternalMetadata(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, false); + } 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.kvDB.set("diff-caches-internal", caches); + if (direction == "pull" && filesChanged != 0) { + const configDir = (0, import_obsidian.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((e2) => enabledPlugins.has(e2.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, (a2) => { + a2.appendText(`Files in ${updatePluginName} has been updated, Press `); + a2.appendChild(a2.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); + }); + })); + a2.appendText(` to reload ${updatePluginName}, or press elsewhere to dismiss this message.`); + }); + }); + const updatedPluginKey = "popupUpdated-" + updatePluginId; + scheduleTask(updatedPluginKey, 1e3, async () => { + var _a; + const popup = await memoIfNotExist(updatedPluginKey, () => new import_obsidian.Notice(fragment, 0)); + const isShown = (_a = popup == null ? void 0 : popup.noticeEl) == null ? void 0 : _a.isShown(); + if (!isShown) { + memoObject(updatedPluginKey, new import_obsidian.Notice(fragment, 0)); + } + scheduleTask(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, (a2) => { + a2.appendText(`Hidden files have been synchronized, Press `); + a2.appendChild(a2.createEl("a", null, (anchor) => { + anchor.text = "HERE"; + anchor.addEventListener("click", () => { + this.app.commands.executeCommandById("app:reload"); + }); + })); + a2.appendText(` to reload obsidian, or press elsewhere to dismiss this message.`); + }); + }); + scheduleTask("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_obsidian.Notice(fragment, 0); + } + scheduleTask("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"); + } + async storeInternalFileToDatabase(file, forceWrite = false) { + const id = filename2idInternalMetadata(path2id(file.path)); + const contentBin = await this.app.vault.adapter.readBinary(file.path); + let content; + try { + content = await arrayBufferToBase64(contentBin); + } catch (ex) { + Logger(`The file ${file.path} could not be encoded`); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + const mtime = file.mtime; + return await runWithLock("file-" + id, false, async () => { + try { + 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 (isDocContentSame(old.data, content) && !forceWrite) { + return; + } + saveData = { + ...old, + data: content, + mtime, + size: file.size, + datatype: "newnote", + children: [], + deleted: false, + type: "newnote" + }; + } + const ret = await this.localDatabase.putDBEntry(saveData, true); + Logger(`STORAGE --> DB:${file.path}: (hidden) Done`); + return ret; + } catch (ex) { + Logger(`STORAGE --> DB:${file.path}: (hidden) Failed`); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + }); + } + async deleteInternalFileOnDatabase(filename, forceWrite = false) { + const id = filename2idInternalMetadata(path2id(filename)); + const mtime = new Date().getTime(); + await runWithLock("file-" + id, false, async () => { + try { + 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`); + } catch (ex) { + Logger(`STORAGE -x> DB:${filename}: (hidden) Failed`); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + }); + } + async extractInternalFileFromDatabase(filename, force = false) { + const isExists = await this.app.vault.adapter.exists(filename); + const id = filename2idInternalMetadata(path2id(filename)); + return await runWithLock("file-" + id, false, async () => { + var _a; + try { + const fileOnDB = await this.localDatabase.getDBEntry(id, { conflicts: true }, false, false); + if (fileOnDB === false) + throw new Error(`File not found on database.:${id}`); + if ((_a = fileOnDB == null ? void 0 : fileOnDB._conflicts) == null ? void 0 : _a.length) { + Logger(`Hidden file ${id} has conflicted revisions, to keep in safe, writing to storage has been prevented`, LOG_LEVEL.INFO); + return; + } + const deleted = "deleted" in fileOnDB ? fileOnDB.deleted : false; + if (deleted) { + if (!isExists) { + Logger(`STORAGE { + Logger("Opening data-merging dialog", LOG_LEVEL.VERBOSE); + const docs = [docA, docB]; + const modal = new JsonResolveModal(this.app, id2path(docA._id), [docA, docB], async (keep, result) => { + try { + const filename = id2filenameInternalMetadata(docA._id); + let needFlush = false; + if (!result && !keep) { + Logger(`Skipped merging: ${filename}`); + } + if (result || keep) { + for (const doc of docs) { + if (doc._rev != keep) { + if (await this.localDatabase.deleteDBEntry(doc._id, { rev: doc._rev })) { + Logger(`Conflicted revision has been deleted: ${filename}`); + needFlush = true; + } + } + } + } + if (!keep && result) { + const isExists = await this.app.vault.adapter.exists(filename); + if (!isExists) { + await this.ensureDirectoryEx(filename); + } + await this.app.vault.adapter.write(filename, result); + const stat = await this.app.vault.adapter.stat(filename); + await this.storeInternalFileToDatabase({ path: filename, ...stat }, true); + try { + await app.vault.adapter.reconcileInternalFile(filename); + } catch (ex) { + Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL.VERBOSE); + Logger(ex, LOG_LEVEL.VERBOSE); + } + Logger(`STORAGE <-- DB:${filename}: written (hidden,merged)`); + } + if (needFlush) { + await this.extractInternalFileFromDatabase(filename, false); + Logger(`STORAGE --> DB:${filename}: extracted (hidden,merged)`); + } + res2(true); + } catch (ex) { + Logger("Could not merge conflicted json"); + Logger(ex, LOG_LEVEL.VERBOSE); + res2(false); + } + }); + modal.open(); + }); + } + async scanInternalFiles() { + const ignoreFilter = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((e2) => e2).map((e2) => new RegExp(e2, "i")); + const root = this.app.vault.getRoot(); + const findRoot = root.path; + const filenames = (await this.getFiles(findRoot, [], null, ignoreFilter)).filter((e2) => e2.startsWith(".")).filter((e2) => !e2.startsWith(".trash")); + const files = filenames.map(async (e2) => { + return { + path: e2, + stat: await this.app.vault.adapter.stat(e2) + }; + }); + const result = []; + for (const f3 of files) { + const w = await f3; + result.push({ + ...w, + ...w.stat + }); + } + return result; + } + async getFiles(path, ignoreList, filter2, ignoreFilter) { + const w = await this.app.vault.adapter.list(path); + let files = [ + ...w.files.filter((e2) => !ignoreList.some((ee) => e2.endsWith(ee))).filter((e2) => !filter2 || filter2.some((ee) => e2.match(ee))).filter((e2) => !ignoreFilter || ignoreFilter.every((ee) => !e2.match(ee))) + ]; + L1: + for (const v of w.folders) { + for (const ignore of ignoreList) { + if (v.endsWith(ignore)) { + continue L1; + } + } + if (ignoreFilter && ignoreFilter.some((e2) => v.match(e2))) { + continue L1; + } + files = files.concat(await this.getFiles(v, ignoreList, filter2, ignoreFilter)); + } + return files; + } +}; + +// src/CmdSetupLiveSync.ts +var SetupLiveSync = class extends LiveSyncCommands { + onunload() { + } + onload() { + this.plugin.registerObsidianProtocolHandler("setuplivesync", async (conf) => await this.setupWizard(conf.settings)); + this.plugin.addCommand({ + id: "livesync-copysetupuri", + name: "Copy the setup URI", + callback: this.command_copySetupURI.bind(this) + }); + this.plugin.addCommand({ + id: "livesync-copysetupurifull", + name: "Copy the setup URI (Full)", + callback: this.command_copySetupURIFull.bind(this) + }); + this.plugin.addCommand({ + id: "livesync-opensetupuri", + name: "Open the setup URI", + callback: this.command_openSetupURI.bind(this) + }); + } + onInitializeDatabase(showNotice) { + } + beforeReplicate(showNotice) { + } + onResume() { + } + parseReplicationResultItem(docs) { + return false; + } + async realizeSettingSyncMode() { + } + async command_copySetupURI() { + const encryptingPassphrase = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", ""); + if (encryptingPassphrase === false) + return; + const setting = { ...this.settings, configPassphraseStore: "", encryptedCouchDBConnection: "", encryptedPassphrase: "" }; + const keys2 = Object.keys(setting); + for (const k of keys2) { + 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, false)); + const uri = `${configURIBase}${encryptedSetting}`; + await navigator.clipboard.writeText(uri); + Logger("Setup URI copied to clipboard", LOG_LEVEL.NOTICE); + } + async command_copySetupURIFull() { + const encryptingPassphrase = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", ""); + if (encryptingPassphrase === false) + return; + const setting = { ...this.settings, configPassphraseStore: "", encryptedCouchDBConnection: "", encryptedPassphrase: "" }; + const encryptedSetting = encodeURIComponent(await encrypt(JSON.stringify(setting), encryptingPassphrase, false)); + const uri = `${configURIBase}${encryptedSetting}`; + await navigator.clipboard.writeText(uri); + Logger("Setup URI copied to clipboard", LOG_LEVEL.NOTICE); + } + async command_openSetupURI() { + 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 this.setupWizard(config); + } + async setupWizard(confString) { + try { + const oldConf = JSON.parse(JSON.stringify(this.settings)); + const encryptingPassphrase = await askString(this.app, "Passphrase", "The passphrase to decrypt your setup URI", ""); + if (encryptingPassphrase === false) + return; + const newConf = await JSON.parse(await decrypt(confString, encryptingPassphrase, false)); + if (newConf) { + const result = await askYesNo(this.app, "Importing LiveSync's conf, OK?"); + if (result == "yes") { + const newSettingW = Object.assign({}, DEFAULT_SETTINGS, newConf); + this.plugin.replicator.closeReplication(); + this.settings.suspendFileWatching = true; + console.dir(newSettingW); + newSettingW.configPassphraseStore = ""; + newSettingW.encryptedPassphrase = ""; + newSettingW.encryptedCouchDBConnection = ""; + 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.plugin.settings = newSettingW; + this.plugin.usedPassphrase = ""; + await this.plugin.saveSettings(); + } else if (setupType == setupAsNew) { + this.plugin.settings = newSettingW; + this.plugin.usedPassphrase = ""; + await this.plugin.saveSettings(); + await this.plugin.resetLocalDatabase(); + await this.plugin.localDatabase.initializeDatabase(); + await this.plugin.markRemoteResolved(); + await this.plugin.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; + } + this.plugin.settings = newSettingW; + this.plugin.usedPassphrase = ""; + await this.plugin.saveSettings(); + await this.plugin.resetLocalDatabase(); + await this.plugin.localDatabase.initializeDatabase(); + await this.plugin.initializeDatabase(true); + await this.plugin.tryResetRemoteDatabase(); + await this.plugin.markRemoteLocked(); + await this.plugin.markRemoteResolved(); + await this.plugin.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.plugin.settings = newSettingW; + this.plugin.usedPassphrase = ""; + await this.plugin.saveSettings(); + const replicate2 = await askYesNo(this.app, "Unlock and replicate?"); + if (replicate2 == "yes") { + await this.plugin.replicate(true); + await this.plugin.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.plugin.settings = oldConf; + return; + } + } + let initDB; + this.plugin.settings = newSettingW; + this.plugin.usedPassphrase = ""; + await this.plugin.saveSettings(); + if (keepLocalDB == "no") { + await this.plugin.resetLocalDatabase(); + await this.plugin.localDatabase.initializeDatabase(); + const rebuild = await askYesNo(this.app, "Rebuild the database?"); + if (rebuild == "yes") { + initDB = this.plugin.initializeDatabase(true); + } else { + await this.plugin.markRemoteResolved(); + } + } + if (keepRemoteDB == "no") { + await this.plugin.tryResetRemoteDatabase(); + await this.plugin.markRemoteLocked(); + } + if (keepLocalDB == "no" || keepRemoteDB == "no") { + const replicate2 = await askYesNo(this.app, "Replicate once?"); + if (replicate2 == "yes") { + if (initDB != null) { + await initDB; + } + await this.plugin.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); + } + } +}; + +// src/main.ts +var isDebug = false; +setNoticeClass(import_obsidian.Notice); +var ObsidianLiveSyncPlugin = class extends import_obsidian.Plugin { + constructor() { + super(...arguments); + this.isMobile = false; + this.isReady = false; + this.packageVersion = ""; + this.manifestVersion = ""; + this.addOnPluginAndTheirSettings = new PluginAndTheirSettings(this); + this.addOnHiddenFileSync = new HiddenFileSync(this); + this.addOnSetup = new SetupLiveSync(this); + this.addOns = [this.addOnPluginAndTheirSettings, this.addOnHiddenFileSync, this.addOnSetup]; + this.periodicSyncProcessor = new PeriodicProcessor(this, async () => await this.replicate()); + this.last_successful_post = false; + this.processReplication = (e2) => this.parseReplicationResult(e2); + this.replicationStat = new ObservableStore({ + sent: 0, + arrived: 0, + maxPullSeq: 0, + maxPushSeq: 0, + lastSyncPullSeq: 0, + lastSyncPushSeq: 0, + syncStatus: "CLOSED" + }); + this.usedPassphrase = ""; + this.notifies = {}; + this.lastLog = ""; + this.queuedEntries = []; + this.dbChangeProcRunning = false; + this.queuedFiles = []; + this.queuedFilesStore = getGlobalStore("queuedFiles", { queuedItems: [], fileEventItems: [] }); + this.chunkWaitTimeout = 6e4; + this.lastMessage = ""; + this.logHideTimer = null; + this.conflictedCheckFiles = []; + } + getLastPostFailedBySize() { + return !this.last_successful_post; + } + async fetchByAPI(request) { + var _a, _b; + const ret = await (0, import_obsidian.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; + } + getDatabase() { + return this.localDatabase.localDatabase; + } + getSettings() { + return this.settings; + } + getIsMobile() { + return this.isMobile; + } + async connectRemoteCouchDB(uri, auth, disableRequestURI, passphrase, useDynamicIterationCount) { + 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 r = await this.fetchByAPI(requestParam); + if (method == "POST" || method == "PUT") { + this.last_successful_post = r.status - r.status % 100 == 200; + } else { + this.last_successful_post = true; + } + Logger(`HTTP:${method}${size} to:${localURL} -> ${r.status}`, LOG_LEVEL.DEBUG); + return new Response(r.arrayBuffer, { + headers: r.headers, + status: r.status, + statusText: `${r.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 index_es_default(uri, conf); + if (passphrase !== "false" && typeof passphrase === "string") { + enableEncryption(db, passphrase, useDynamicIterationCount); + } + try { + const info2 = await db.info(); + return { db, info: info2 }; + } 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; + } + } + id2path(filename) { + return id2path(filename); + } + path2id(filename) { + return path2id(filename); + } + createPouchDBInstance(name, options) { + if (this.settings.useIndexedDBAdapter) { + options.adapter = "indexeddb"; + return new index_es_default(name + "-indexeddb", options); + } + return new index_es_default(name, options); + } + beforeOnUnload(db) { + this.kvDB.close(); + } + onClose(db) { + this.kvDB.close(); + } + async onInitializeDatabase(db) { + this.kvDB = await OpenKeyValueDatabase(db.dbname + "-livesync-kv"); + this.replicator = new LiveSyncDBReplicator(this); + } + async onResetDatabase(db) { + await this.kvDB.destroy(); + this.kvDB = await OpenKeyValueDatabase(db.dbname + "-livesync-kv"); + this.replicator = new LiveSyncDBReplicator(this); + } + getReplicator() { + return this.replicator; + } + 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_obsidian.normalizePath)(FLAGMD_REDFLAG)); + if (redflag != null) { + return true; + } + return false; + } + isRedFlag2Raised() { + const redflag = getAbstractFileByPath((0, import_obsidian.normalizePath)(FLAGMD_REDFLAG2)); + if (redflag != null) { + return true; + } + return false; + } + async deleteRedFlag2() { + const redflag = getAbstractFileByPath((0, import_obsidian.normalizePath)(FLAGMD_REDFLAG2)); + if (redflag != null) { + await app.vault.delete(redflag, true); + } + } + isRedFlag3Raised() { + const redflag = getAbstractFileByPath((0, import_obsidian.normalizePath)(FLAGMD_REDFLAG3)); + if (redflag != null) { + return true; + } + return false; + } + async deleteRedFlag3() { + const redflag = getAbstractFileByPath((0, import_obsidian.normalizePath)(FLAGMD_REDFLAG3)); + if (redflag != null) { + await app.vault.delete(redflag, true); + } + } + showHistory(file) { + new DocumentHistoryModal(this.app, this, file).open(); + } + async fileHistory() { + const notes = []; + for await (const doc of this.localDatabase.findAllDocs()) { + notes.push({ path: id2path(doc._id), mtime: doc.mtime }); + } + notes.sort((a2, b) => b.mtime - a2.mtime); + const notesList = notes.map((e2) => e2.path); + const target = await askSelectString(this.app, "File to view History", notesList); + if (target) { + this.showHistory(target); + } + } + async pickFileForResolve() { + const notes = []; + for await (const doc of this.localDatabase.findAllDocs({ conflicts: true })) { + if (!("_conflicts" in doc)) + continue; + notes.push({ path: id2path(doc._id), mtime: doc.mtime }); + } + notes.sort((a2, b) => b.mtime - a2.mtime); + const notesList = notes.map((e2) => e2.path); + if (notesList.length == 0) { + Logger("There are no conflicted documents", LOG_LEVEL.NOTICE); + return false; + } + const target = await askSelectString(this.app, "File to view History", notesList); + if (target) { + await this.resolveConflicted(target); + return true; + } + return false; + } + async resolveConflicted(target) { + if (isInternalMetadata(target)) { + await this.addOnHiddenFileSync.resolveConflictOnInternalFile(target); + } else if (isPluginMetadata(target)) { + await this.resolveConflictByNewerEntry(target); + } else { + await this.showIfConflicted(target); + } + } + async collectDeletedFiles() { + const limitDays = this.settings.automaticallyDeleteMetadataOfDeletedFiles; + if (limitDays <= 0) + return; + Logger(`Checking expired file history`); + const limit = Date.now() - 86400 * 1e3 * limitDays; + const notes = []; + for await (const doc of this.localDatabase.findAllDocs({ conflicts: true })) { + 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 (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 onLayoutReady() { + this.registerFileWatchEvents(); + if (!this.localDatabase.isReady) { + Logger(`Something went wrong! The local database is not ready`, LOG_LEVEL.NOTICE); + return; + } + try { + if (this.isRedFlagRaised() || this.isRedFlag2Raised() || this.isRedFlag3Raised()) { + 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.syncAfterMerge = false; + this.settings.autoSweepPlugins = false; + this.settings.usePluginSync = false; + this.settings.suspendFileWatching = true; + this.settings.syncInternalFiles = false; + await this.saveSettings(); + if (this.isRedFlag2Raised()) { + Logger(`${FLAGMD_REDFLAG2} has been detected! Self-hosted LiveSync suspends all sync and rebuild everything.`, LOG_LEVEL.NOTICE); + await this.resetLocalDatabase(); + await this.initializeDatabase(true); + await this.markRemoteLocked(); + await this.tryResetRemoteDatabase(); + await this.markRemoteLocked(); + await this.replicateAllToServer(true); + await this.deleteRedFlag2(); + if (await askYesNo(this.app, "Do you want to disable Suspend file watching and restart obsidian now?") == "yes") { + this.settings.suspendFileWatching = false; + await this.saveSettings(); + this.app.commands.executeCommandById("app:reload"); + } + } else if (this.isRedFlag3Raised()) { + Logger(`${FLAGMD_REDFLAG3} has been detected! Self-hosted LiveSync will discard the local database and fetch everything from the remote once again.`, LOG_LEVEL.NOTICE); + await this.resetLocalDatabase(); + await delay(1e3); + await this.markRemoteResolved(); + await this.openDatabase(); + this.isReady = true; + await this.replicateAllFromServer(true); + await this.deleteRedFlag3(); + if (await askYesNo(this.app, "Do you want to disable Suspend file watching and restart obsidian now?") == "yes") { + this.settings.suspendFileWatching = false; + await this.saveSettings(); + this.app.commands.executeCommandById("app:reload"); + } + } else { + this.settings.writeLogToTheFile = true; + 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(false, false); + if (!isInitialized) { + return false; + } + } + await this.realizeSettingSyncMode(); + this.registerWatchEvents(); + if (this.settings.syncOnStart) { + this.replicator.openReplication(this.settings, false, false); + } + this.scanStat(); + } catch (ex) { + Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL.NOTICE); + Logger(ex, LOG_LEVEL.VERBOSE); + } + } + async scanStat() { + const notes = []; + Logger(`Additional safety scan..`, LOG_LEVEL.VERBOSE); + for await (const doc of this.localDatabase.findAllDocs({ conflicts: true })) { + if (!("_conflicts" in doc)) + continue; + notes.push({ path: id2path(doc._id), mtime: doc.mtime }); + } + if (notes.length > 0) { + Logger(`Some files have been left conflicted! Please resolve them by "Pick a file to resolve conflict". The list is written in the log.`, LOG_LEVEL.NOTICE); + for (const note of notes) { + Logger(`Conflicted: ${note.path}`); + } + } else { + Logger(`There are no conflicted files`, LOG_LEVEL.VERBOSE); + } + Logger(`Additional safety scan done`, LOG_LEVEL.VERBOSE); + } + async onload() { + logStore.subscribe((e2) => this.addLog(e2.message, e2.level, e2.key)); + Logger("loading plugin"); + const manifestVersion = "0.17.34"; + const packageVersion = "0.17.34"; + this.manifestVersion = manifestVersion; + this.packageVersion = packageVersion; + 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.syncAfterMerge = 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(); + this.watchWorkspaceOpen = (0, import_obsidian.debounce)(this.watchWorkspaceOpen.bind(this), 1e3, false); + this.watchWindowVisibility = (0, import_obsidian.debounce)(this.watchWindowVisibility.bind(this), 1e3, false); + this.watchOnline = (0, import_obsidian.debounce)(this.watchOnline.bind(this), 500, false); + this.parseReplicationResult = this.parseReplicationResult.bind(this); + this.loadQueuedFiles = this.loadQueuedFiles.bind(this); + this.triggerRealizeSettingSyncMode = (0, import_obsidian.debounce)(this.triggerRealizeSettingSyncMode.bind(this), 1e3); + this.statusBar = this.addStatusBarItem(); + this.statusBar.addClass("syncstatusbar"); + (0, import_obsidian.addIcon)( + "replicate", + ` + + + + + ` + ); + (0, import_obsidian.addIcon)( + "view-log", + ` + + + ` + ); + await Promise.all(this.addOns.map((e2) => e2.onload())); + this.addRibbonIcon("replicate", "Replicate", async () => { + await this.replicate(true); + }); + this.addRibbonIcon("view-log", "Show log", () => { + new LogDisplayModal(this.app, this).open(); + }); + this.addSettingTab(new ObsidianLiveSyncSettingTab(this.app, this)); + this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this)); + 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_obsidian.debounce)(this.triggerRealizeSettingSyncMode.bind(this), 1e3); + this.addCommand({ + id: "livesync-filehistory", + name: "Pick a file to show history", + callback: () => { + this.fileHistory(); + } + }); + this.addCommand({ + id: "livesync-conflictcheck", + name: "Pick a file to resolve conflict", + callback: () => { + this.pickFileForResolve(); + } + }); + this.addCommand({ + id: "livesync-all-conflictcheck", + name: "Resolve all conflicted files", + callback: async () => { + while (await this.pickFileForResolve()) + ; + } + }); + this.addCommand({ + id: "livesync-runbatch", + name: "Run pended batch processes", + callback: async () => { + await this.applyBatchChange(); + } + }); + this.addCommand({ + id: "livesync-abortsync", + name: "Abort synchronization immediately", + callback: () => { + this.replicator.terminateSync(); + } + }); + } + onunload() { + var _a; + for (const addOn of this.addOns) { + addOn.onunload(); + } + if (this.localDatabase != null) { + this.localDatabase.onunload(); + } + (_a = this.periodicSyncProcessor) == null ? void 0 : _a.disable(); + if (this.localDatabase != null) { + this.replicator.closeReplication(); + this.localDatabase.close(); + } + cancelAllPeriodicTask(); + cancelAllTasks(); + Logger("unloading plugin"); + } + async openDatabase() { + if (this.localDatabase != null) { + await this.localDatabase.close(); + } + const vaultName = this.getVaultName(); + Logger("Waiting for ready..."); + this.isMobile = this.app.isMobile; + this.localDatabase = new LiveSyncLocalDB(vaultName, this); + this.observeForLogs(); + return await this.localDatabase.initializeDatabase(); + } + getPassphrase(settings) { + const methods = { + "": () => Promise.resolve("*"), + "LOCALSTORAGE": () => { + var _a; + return Promise.resolve((_a = localStorage.getItem("ls-setting-passphrase")) != null ? _a : false); + }, + "ASK_AT_LAUNCH": () => askString(this.app, "Passphrase", "passphrase", "") + }; + const method = settings.configPassphraseStore; + const methodFunc = method in methods ? methods[method] : methods[""]; + return methodFunc(); + } + async decryptConfigurationItem(encrypted, passphrase) { + const dec = await tryDecrypt(encrypted, passphrase + SALT_OF_PASSPHRASE, false); + if (dec) { + this.usedPassphrase = passphrase; + return dec; + } + return false; + } + tryDecodeJson(encoded) { + try { + if (!encoded) + return false; + return JSON.parse(encoded); + } catch (ex) { + return false; + } + } + async encryptConfigurationItem(src, settings) { + if (this.usedPassphrase != "") { + return await encrypt(src, this.usedPassphrase + SALT_OF_PASSPHRASE, false); + } + const passphrase = await this.getPassphrase(settings); + if (passphrase === false) { + Logger("Could not determine passphrase to save data.json! You probably make the configuration sure again!", LOG_LEVEL.URGENT); + return ""; + } + const dec = await encrypt(src, passphrase + SALT_OF_PASSPHRASE, false); + if (dec) { + this.usedPassphrase = passphrase; + return dec; + } + return ""; + } + async loadSettings() { + const settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + const passphrase = await this.getPassphrase(settings); + if (passphrase === false) { + Logger("Could not determine passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL.URGENT); + } else { + if (settings.encryptedCouchDBConnection) { + const keys2 = ["couchDB_URI", "couchDB_USER", "couchDB_PASSWORD", "couchDB_DBNAME"]; + const decrypted = this.tryDecodeJson(await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, passphrase)); + if (decrypted) { + for (const key of keys2) { + if (key in decrypted) { + settings[key] = decrypted[key]; + } + } + } else { + Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL.URGENT); + for (const key of keys2) { + settings[key] = ""; + } + } + } + if (settings.encrypt && settings.encryptedPassphrase) { + const encrypted = settings.encryptedPassphrase; + const decrypted = await this.decryptConfigurationItem(encrypted, passphrase); + if (decrypted) { + settings.passphrase = decrypted; + } else { + Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL.URGENT); + settings.passphrase = ""; + } + } + } + this.settings = settings; + if ("workingEncrypt" in this.settings) + delete this.settings.workingEncrypt; + if ("workingPassphrase" in this.settings) + delete this.settings.workingPassphrase; + this.settings.disableRequestURI = true; + this.settings.gcDelay = 0; + this.settings.useHistory = true; + const 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 || ""); + const settings = { ...this.settings }; + if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) { + Logger("Could not determine passphrase for saving data.json! Our data.json have insecure items!", LOG_LEVEL.NOTICE); + } else { + if (settings.couchDB_PASSWORD != "" || settings.couchDB_URI != "" || settings.couchDB_USER != "" || settings.couchDB_DBNAME) { + const connectionSetting = { + couchDB_DBNAME: settings.couchDB_DBNAME, + couchDB_PASSWORD: settings.couchDB_PASSWORD, + couchDB_URI: settings.couchDB_URI, + couchDB_USER: settings.couchDB_USER + }; + settings.encryptedCouchDBConnection = await this.encryptConfigurationItem(JSON.stringify(connectionSetting), settings); + settings.couchDB_PASSWORD = ""; + settings.couchDB_DBNAME = ""; + settings.couchDB_URI = ""; + settings.couchDB_USER = ""; + } + if (settings.encrypt && settings.passphrase != "") { + settings.encryptedPassphrase = await this.encryptConfigurationItem(settings.passphrase, settings); + settings.passphrase = ""; + } + } + await this.saveData(settings); + this.localDatabase.settings = this.settings; + this.triggerRealizeSettingSyncMode(); + } + registerFileWatchEvents() { + this.vaultManager = new StorageEventManagerObsidian(this); + } + registerWatchEvents() { + this.registerEvent(this.app.workspace.on("file-open", this.watchWorkspaceOpen)); + this.registerDomEvent(document, "visibilitychange", this.watchWindowVisibility); + this.registerDomEvent(window, "online", this.watchOnline); + this.registerDomEvent(window, "offline", 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() { + var _a; + if (this.settings.suspendFileWatching) + return; + if (!this.isReady) + return; + const isHidden = document.hidden; + await this.applyBatchChange(); + if (isHidden) { + this.replicator.closeReplication(); + (_a = this.periodicSyncProcessor) == null ? void 0 : _a.disable(); + } else { + if (this.suspended) + return; + await Promise.all(this.addOns.map((e2) => e2.onResume())); + if (this.settings.liveSync) { + this.replicator.openReplication(this.settings, true, false); + } + if (this.settings.syncOnStart) { + this.replicator.openReplication(this.settings, false, false); + } + this.periodicSyncProcessor.enable(this.settings.periodicReplication ? this.settings.periodicReplicationInterval * 1e3 : 0); + } + } + async procFileEvent(applyBatch) { + if (!this.isReady) + return; + if (this.settings.batchSave) { + if (!applyBatch && this.vaultManager.getQueueLength() < FileWatchEventQueueMax) { + scheduleTask("applyBatchAuto", 3e4, () => { + this.procFileEvent(true); + }); + return; + } + } + cancelTask("applyBatchAuto"); + const ret = await runWithLock("procFiles", true, async () => { + do { + const queue2 = this.vaultManager.fetchEvent(); + if (queue2 === false) + break; + if (queue2 === void 0) + break; + const file = queue2.args.file; + const key = `file-last-proc-${queue2.type}-${file.path}`; + const last = Number(await this.kvDB.get(key) || 0); + if (queue2.type == "DELETE") { + await this.deleteFromDBbyPath(file.path); + } else if (queue2.type == "INTERNAL") { + await this.addOnHiddenFileSync.watchVaultRawEventsAsync(file.path); + } else { + const targetFile = this.app.vault.getAbstractFileByPath(file.path); + if (!(targetFile instanceof import_obsidian.TFile)) { + Logger(`Target file was not found: ${file.path}`, LOG_LEVEL.INFO); + continue; + } + if (file.mtime == last) { + Logger(`File has been already scanned on ${queue2.type}, skip: ${file.path}`, LOG_LEVEL.VERBOSE); + continue; + } + const cache = queue2.args.cache; + if (queue2.type == "CREATE" || queue2.type == "CHANGED") { + if (!await this.updateIntoDB(targetFile, false, cache)) { + Logger(`DB -> STORAGE: failed, cancel the relative operations: ${targetFile.path}`, LOG_LEVEL.INFO); + this.vaultManager.cancelRelativeEvent(queue2); + continue; + } + } + if (queue2.type == "RENAME") { + await this.watchVaultRenameAsync(targetFile, queue2.args.oldPath); + } + } + await this.kvDB.set(key, file.mtime); + } while (this.vaultManager.getQueueLength() > 0); + return true; + }); + return ret; + } + 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); + } + } + getFilePath(file) { + if (file instanceof import_obsidian.TFolder) { + if (file.isRoot()) + return ""; + return this.getFilePath(file.parent) + "/" + file.name; + } + if (file instanceof import_obsidian.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_obsidian.TFile) { + try { + if (await this.updateIntoDB(file, false, cache)) { + await this.deleteFromDBbyPath(oldFile); + } else { + Logger(`Could not save new file: ${file.path} `, LOG_LEVEL.NOTICE); + } + } catch (ex) { + Logger(ex); + } + } + } + async addLog(message, level = LOG_LEVEL.INFO, key = "") { + var _a, _b; + 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 now = new Date(); + const timestamp = now.toLocaleString(); + const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2); + if (message instanceof Error) { + } + const newMessage = timestamp + "->" + messageContent; + console.log(vaultName + ":" + newMessage); + if ((_a = this.settings) == null ? void 0 : _a.writeLogToTheFile) { + const time = now.toISOString().split("T")[0]; + const logDate = `${PREFIXMD_LOGFILE}${time}.md`; + const file = this.app.vault.getAbstractFileByPath((0, import_obsidian.normalizePath)(logDate)); + if (!file) { + this.app.vault.adapter.append((0, import_obsidian.normalizePath)(logDate), "```\n"); + } + this.app.vault.adapter.append((0, import_obsidian.normalizePath)(logDate), vaultName + ":" + newMessage + "\n"); + } + logMessageStore.apply((e2) => [...e2, newMessage].slice(-100)); + this.setStatusBarText(null, messageContent); + if (level >= LOG_LEVEL.NOTICE) { + if (!key) + key = messageContent; + if (key in this.notifies) { + const isShown = (_b = this.notifies[key].notice.noticeEl) == null ? void 0 : _b.isShown(); + if (!isShown) { + this.notifies[key].notice = new import_obsidian.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_obsidian.Notice(messageContent, 0); + this.notifies[key] = { + count: 0, + notice: notify, + timer: setTimeout(() => { + delete this.notifies[key]; + notify.hide(); + }, 5e3) + }; + } + } + } + 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(docEntry, file, force) { + var _a; + const mode = file == void 0 ? "create" : "modify"; + 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 = ~~((((_a = file == null ? void 0 : file.stat) == null ? void 0 : _a.mtime) || 0) / 1e3); + const docMtime = ~~(docEntry.mtime / 1e3); + const doc = await this.localDatabase.getDBEntry(pathSrc, { rev: docEntry._rev }); + if (doc === false) + return; + const path = id2path(doc._id); + const msg = `DB -> STORAGE (${mode}${force ? ",force" : ""},${doc.datatype}) `; + if (doc.datatype != "newnote" && doc.datatype != "plain") { + Logger(msg + "ERROR, Invalid datatype: " + path + "(" + doc.datatype + ")", LOG_LEVEL.NOTICE); + return; + } + if (!force && localMtime >= docMtime) + return; + if (!isValidPath(path)) { + Logger(msg + "ERROR, invalid path: " + path, LOG_LEVEL.NOTICE); + return; + } + const writeData = doc.datatype == "newnote" ? base64ToArrayBuffer(doc.data) : getDocData(doc.data); + await this.ensureDirectoryEx(path); + try { + let outFile; + if (mode == "create") { + outFile = await createFile((0, import_obsidian.normalizePath)(path), writeData, { ctime: doc.ctime, mtime: doc.mtime }); + } else { + await modifyFile(file, writeData, { ctime: doc.ctime, mtime: doc.mtime }); + outFile = getAbstractFileByPath(file.path); + } + Logger(msg + path); + touch(outFile); + this.app.vault.trigger(mode, outFile); + } catch (ex) { + Logger(msg + "ERROR, Could not write: " + path, LOG_LEVEL.NOTICE); + Logger(ex, LOG_LEVEL.VERBOSE); + } + } + async deleteVaultItem(file) { + if (file instanceof import_obsidian.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(`xxx <- STORAGE (deleted) ${file.path}`); + Logger(`files: ${dir.children.length}`); + if (dir.children.length == 0) { + if (!this.settings.doNotDeleteFolder) { + Logger(`All files under the parent directory (${dir}) have been deleted, so delete this one.`); + await this.deleteVaultItem(dir); + } + } + } + handleDBChanged(change) { + const af = app.workspace.getActiveFile(); + if (af && af.path == id2path(change._id)) { + this.queuedEntries = this.queuedEntries.filter((e2) => e2._id != change._id); + return this.handleDBChangedAsync(change); + } + this.queuedEntries.push(change); + this.execDBchanged(); + } + async execDBchanged() { + if (this.dbChangeProcRunning) + return false; + this.dbChangeProcRunning = true; + const semaphore = Semaphore(4); + try { + do { + const entry = this.queuedEntries.shift(); + if (this.queuedEntries.some((e2) => e2._id == entry._id)) + continue; + try { + const releaser = await semaphore.acquire(1); + runWithLock(`dbchanged-${entry._id}`, false, async () => { + Logger(`Applying ${entry._id} (${entry._rev}) change...`, LOG_LEVEL.VERBOSE); + await this.handleDBChangedAsync(entry); + Logger(`Applied ${entry._id} (${entry._rev}) change...`); + }).finally(() => { + releaser(); + }); + } catch (ex) { + Logger(`Failed to apply the change of ${entry._id} (${entry._rev})`); + } + } while (this.queuedEntries.length > 0); + } finally { + this.dbChangeProcRunning = false; + } + } + async handleDBChangedAsync(change) { + const targetFile = getAbstractFileByPath(id2path(change._id)); + if (targetFile == null) { + if (change._deleted || change.deleted) { + return; + } + const doc = change; + await this.doc2storage(doc); + } else if (targetFile instanceof import_obsidian.TFile) { + const doc = change; + const file = targetFile; + const queueConflictCheck = () => { + if (!this.settings.checkConflictOnlyOnOpen) { + this.queueConflictedCheck(file); + return true; + } else { + const af = app.workspace.getActiveFile(); + if (af && af.path == file.path) { + this.queueConflictedCheck(file); + return true; + } + } + return false; + }; + if (this.settings.writeDocumentsIfConflicted) { + await this.doc2storage(doc, file); + queueConflictCheck(); + } else { + const d = await this.localDatabase.getDBEntryMeta(id2path(change._id), { conflicts: true }, true); + if (d && !d._conflicts) { + await this.doc2storage(doc, file); + } else { + if (!queueConflictCheck()) { + Logger(`${id2path(change._id)} is conflicted, write to the storage has been pended.`, LOG_LEVEL.NOTICE); + } + } + } + } else { + Logger(`${id2path(change._id)} is already exist as the folder`); + } + } + saveQueuedFiles() { + const saveData = JSON.stringify(this.queuedFiles.filter((e2) => !e2.done).map((e2) => e2.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((e2) => e2.entry._id == doc.doc._id)) { + await this.parseIncomingDoc(doc.doc); + } + } + } + procQueuedFiles() { + this.saveQueuedFiles(); + for (const queue2 of this.queuedFiles) { + if (queue2.done) + continue; + const now = new Date().getTime(); + if (queue2.missingChildren.length == 0) { + queue2.done = true; + if (isInternalMetadata(queue2.entry._id)) { + const filename = id2path(id2filenameInternalMetadata(queue2.entry._id)); + this.addOnHiddenFileSync.procInternalFile(filename); + } else if (isValidPath(id2path(queue2.entry._id))) { + this.handleDBChanged(queue2.entry); + } else { + Logger(`Skipped: ${queue2.entry._id}`, LOG_LEVEL.VERBOSE); + } + } else if (now > queue2.timeout) { + if (!queue2.warned) + Logger(`Timed out: ${queue2.entry._id} could not collect ${queue2.missingChildren.length} chunks. plugin keeps watching, but you have to check the file after the replication.`, LOG_LEVEL.NOTICE); + queue2.warned = true; + continue; + } + } + this.queuedFiles = this.queuedFiles.filter((e2) => !e2.done); + this.queuedFilesStore.apply((value) => ({ ...value, queuedItems: this.queuedFiles })); + this.saveQueuedFiles(); + } + parseIncomingChunk(chunk) { + const now = new Date().getTime(); + let isNewFileCompleted = false; + for (const queue2 of this.queuedFiles) { + if (queue2.done) + continue; + if (queue2.missingChildren.indexOf(chunk._id) !== -1) { + queue2.missingChildren = queue2.missingChildren.filter((e2) => e2 != chunk._id); + queue2.timeout = now + this.chunkWaitTimeout; + } + if (queue2.missingChildren.length == 0) { + for (const e2 of this.queuedFiles) { + if (e2.entry._id == queue2.entry._id && e2.entry.mtime < queue2.entry.mtime) { + e2.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 (isInternalMetadata(doc._id) && !this.settings.syncInternalFiles) + return; + const ignoreFiles = [ + "_design/replicate", + FLAGMD_REDFLAG, + FLAGMD_REDFLAG2, + FLAGMD_REDFLAG3 + ]; + if (!isInternalMetadata(doc._id) && ignoreFiles.contains(id2path(doc._id))) { + return; + } + if (!isInternalMetadata(doc._id) && skipOldFile) { + const info2 = getAbstractFileByPath(id2path(doc._id)); + if (info2 && info2 instanceof import_obsidian.TFile) { + const localMtime = ~~(info2.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((e2) => "error" in e2).map((e2) => e2.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) { + L1: + for (const change of docs) { + for (const proc of this.addOns) { + if (await proc.parseReplicationResultItem(change)) { + continue L1; + } + } + 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.replicator.closeReplication(); + Logger(`Remote database updated to incompatible version. update your self-hosted-livesync plugin.`, LOG_LEVEL.NOTICE); + } + } + } + } + async realizeSettingSyncMode() { + var _a; + this.replicator.closeReplication(); + (_a = this.periodicSyncProcessor) == null ? void 0 : _a.disable(); + this.localDatabase.refreshSettings(); + await this.applyBatchChange(); + await Promise.all(this.addOns.map((e2) => e2.realizeSettingSyncMode())); + if (this.suspended) + return; + await Promise.all(this.addOns.map((e2) => e2.onResume())); + if (this.settings.liveSync) { + this.replicator.openReplication(this.settings, true, false); + } + this.periodicSyncProcessor.enable(this.settings.periodicReplication ? this.settings.periodicReplicationInterval * 1e3 : 0); + } + observeForLogs() { + const observer__ = observeStores(this.queuedFilesStore, lockStore); + const observer = observeStores(observer__, this.replicationStat); + observer.observe((e2) => { + const sent = e2.sent; + const arrived = e2.arrived; + const maxPullSeq = e2.maxPullSeq; + const maxPushSeq = e2.maxPushSeq; + const lastSyncPullSeq = e2.lastSyncPullSeq; + const lastSyncPushSeq = e2.lastSyncPushSeq; + let pushLast = ""; + let pullLast = ""; + let w = ""; + switch (e2.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"; + pushLast = lastSyncPushSeq == 0 ? "" : lastSyncPushSeq >= maxPushSeq ? " (LIVE)" : ` (${maxPushSeq - lastSyncPushSeq})`; + pullLast = lastSyncPullSeq == 0 ? "" : lastSyncPullSeq >= maxPullSeq ? " (LIVE)" : ` (${maxPullSeq - lastSyncPullSeq})`; + break; + case "ERRORED": + w = "\u26A0"; + break; + default: + w = "?"; + } + this.statusBar.title = e2.syncStatus; + let waiting = ""; + if (this.settings.batchSave) { + waiting = " " + "\u{1F6EB}".repeat(this.vaultManager.getQueueLength()); + waiting = waiting.replace(/(🛫){10}/g, "\u{1F680}"); + } + let queued = ""; + const queue2 = Object.entries(e2.queuedItems).filter((e3) => !e3[1].warned); + const queuedCount = queue2.length; + if (queuedCount) { + const pieces = queue2.map((e3) => e3[1].missingChildren).reduce((prev, cur) => prev + cur.length, 0); + queued = ` \u{1F9E9} ${queuedCount} (${pieces})`; + } + const processes = e2.count; + const processesDisp = processes == 0 ? "" : ` \u23F3${processes}`; + const message = `Sync: ${w} \u2191${sent}${pushLast} \u2193${arrived}${pullLast}${waiting}${processesDisp}${queued}`; + function getProcKind(proc) { + const p = proc.indexOf("-"); + if (p == -1) { + return proc; + } + return proc.substring(0, p); + } + const pendingTask = e2.pending.length ? "\nPending: " + Object.entries(e2.pending.reduce((p, c) => { + var _a; + return { ...p, [getProcKind(c)]: ((_a = p[getProcKind(c)]) != null ? _a : 0) + 1 }; + }, {})).map((e3) => `${e3[0]}${e3[1] == 1 ? "" : `(${e3[1]})`}`).join(", ") : ""; + const runningTask = e2.running.length ? "\nRunning: " + Object.entries(e2.running.reduce((p, c) => { + var _a; + return { ...p, [getProcKind(c)]: ((_a = p[getProcKind(c)]) != null ? _a : 0) + 1 }; + }, {})).map((e3) => `${e3[0]}${e3[1] == 1 ? "" : `(${e3[1]})`}`).join(", ") : ""; + this.setStatusBarText(message + pendingTask + runningTask); + }); + } + refreshStatusText() { + return; + } + setStatusBarText(message = null, log2 = null) { + if (!this.statusBar) + return; + const newMsg = typeof message == "string" ? message : this.lastMessage; + const newLog = typeof log2 == "string" ? log2 : this.lastLog; + if (`${this.lastMessage}-${this.lastLog}` != `${newMsg}-${newLog}`) { + this.statusBar.setText(newMsg.split("\n")[0]); + if (this.settings.showStatusOnEditor) { + const root = activeDocument.documentElement; + const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`); + q.forEach((e2) => e2.setAttr("data-log", newMsg + "\n" + newLog)); + } else { + const root = activeDocument.documentElement; + const q = root.querySelectorAll(`.CodeMirror-wrap,.cm-s-obsidian>.cm-editor,.canvas-wrapper`); + q.forEach((e2) => e2.setAttr("data-log", "")); + } + 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(); + await Promise.all(this.addOns.map((e2) => e2.beforeReplicate(showMessage))); + await this.loadQueuedFiles(); + return await this.replicator.openReplication(this.settings, false, showMessage); + } + async initializeDatabase(showingNotice, reopenDatabase = true) { + this.isReady = false; + if (!reopenDatabase || await this.openDatabase()) { + if (this.localDatabase.isReady) { + await this.syncAllFiles(showingNotice); + } + await Promise.all(this.addOns.map((e2) => e2.onInitializeDatabase(showingNotice))); + this.isReady = true; + await this.procFileEvent(true); + return true; + } else { + this.isReady = false; + return false; + } + } + async replicateAllToServer(showingNotice) { + if (!this.isReady) + return false; + await Promise.all(this.addOns.map((e2) => e2.beforeReplicate(showingNotice))); + return await this.replicator.replicateAllToServer(this.settings, showingNotice); + } + async replicateAllFromServer(showingNotice) { + if (!this.isReady) + return false; + return await this.replicator.replicateAllFromServer(this.settings, showingNotice); + } + async markRemoteLocked() { + return await this.replicator.markRemoteLocked(this.settings, true); + } + async markRemoteUnlocked() { + return await this.replicator.markRemoteLocked(this.settings, false); + } + async markRemoteResolved() { + return await this.replicator.markRemoteResolved(this.settings); + } + async syncAllFiles(showingNotice) { + let initialScan = false; + if (showingNotice) { + Logger("Initializing", LOG_LEVEL.NOTICE, "syncAll"); + } + Logger("Initialize and checking database files"); + Logger("Checking deleted files"); + await this.collectDeletedFiles(); + Logger("Collecting local files on the storage", LOG_LEVEL.VERBOSE); + const filesStorage = this.app.vault.getFiles().filter((e2) => this.isTargetFile(e2)); + const filesStorageName = filesStorage.map((e2) => e2.path); + Logger("Collecting local files on the DB", LOG_LEVEL.VERBOSE); + const filesDatabase = []; + for await (const docId of this.localDatabase.findAllDocNames()) { + const path = id2path(docId); + if (isValidPath(docId) && this.isTargetFile(path)) { + filesDatabase.push(path); + } + } + Logger("Opening the key-value database", LOG_LEVEL.VERBOSE); + const isInitialized = await this.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((e2) => filesDatabase.indexOf(e2.path) == -1); + const onlyInDatabase = filesDatabase.filter((e2) => filesStorageName.indexOf(e2) == -1); + const onlyInStorageNames = onlyInStorage.map((e2) => e2.path); + const syncFiles = filesStorage.filter((e2) => onlyInStorageNames.indexOf(e2.path) == -1); + Logger("Updating database by new files"); + this.setStatusBarText(`UPDATE DATABASE`); + const runAll = async (procedureName, objects, callback) => { + Logger(procedureName); + const semaphore = Semaphore(25); + if (!this.localDatabase.isReady) + throw Error("Database is not ready!"); + const processes = objects.map((e2) => (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(); + } + })(e2)); + await Promise.all(processes); + Logger(`${procedureName} done.`); + }; + await runAll("UPDATE DATABASE", onlyInStorage, async (e2) => { + Logger(`UPDATE DATABASE ${e2.path}`); + await this.updateIntoDB(e2, initialScan); + }); + if (!initialScan) { + await runAll("UPDATE STORAGE", onlyInDatabase, async (e2) => { + const w = await this.localDatabase.getDBEntryMeta(e2, {}, true); + if (w && !(w.deleted || w._deleted)) { + Logger(`Check or pull from db:${e2}`); + await this.pullFile(e2, filesStorage, false, null, false); + Logger(`Check or pull from db:${e2} OK`); + } else if (w) { + Logger(`Deletion history skipped: ${e2}`, LOG_LEVEL.VERBOSE); + } else { + Logger(`entry not found: ${e2}`); + } + }); + } + if (!initialScan) { + let caches = {}; + caches = await this.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((e2) => path2id(e2.path)), include_docs: true }); + const syncFilesToSync = syncFilesX.map((e2) => ({ file: e2, doc: docs.rows.find((ee) => ee.id == path2id(e2.path)).doc })); + await runAll(`CHECK FILE STATUS:${syncFiles.length}/${docsCount}`, syncFilesToSync, async (e2) => { + caches = await this.syncFileBetweenDBandStorage(e2.file, e2.doc, initialScan, caches); + }); + } while (syncFiles.length > 0); + await this.kvDB.set("diff-caches", caches); + } + this.setStatusBarText(`NOW TRACKING!`); + Logger("Initialized, NOW TRACKING!"); + if (!isInitialized) { + await this.kvDB.set("initialized", true); + } + if (showingNotice) { + Logger("Initialize done!", LOG_LEVEL.NOTICE, "syncAll"); + } + } + async getConflictedDoc(path, rev2) { + try { + const doc = await this.localDatabase.getDBEntry(path, { rev: rev2 }, false, false, true); + if (doc === false) + return false; + let data = getDocData(doc.data); + if (doc.datatype == "newnote") { + data = base64ToString(data); + } else if (doc.datatype == "plain") { + } + return { + deleted: doc.deleted || doc._deleted, + ctime: doc.ctime, + mtime: doc.mtime, + rev: rev2, + data + }; + } catch (ex) { + if (isErrorOfMissingDoc(ex)) { + return false; + } + } + return false; + } + async mergeSensibly(path, baseRev, currentRev, conflictedRev) { + var _a, _b, _c, _d; + const baseLeaf = await this.getConflictedDoc(path, baseRev); + const leftLeaf = await this.getConflictedDoc(path, currentRev); + const rightLeaf = await this.getConflictedDoc(path, conflictedRev); + let autoMerge = false; + if (baseLeaf == false || leftLeaf == false || rightLeaf == false) { + return false; + } + const dmp = new import_diff_match_patch4.diff_match_patch(); + const mapLeft = dmp.diff_linesToChars_(baseLeaf.data, leftLeaf.data); + const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false); + dmp.diff_charsToLines_(diffLeftSrc, mapLeft.lineArray); + const mapRight = dmp.diff_linesToChars_(baseLeaf.data, rightLeaf.data); + const diffRightSrc = dmp.diff_main(mapRight.chars1, mapRight.chars2, false); + dmp.diff_charsToLines_(diffRightSrc, mapRight.lineArray); + function splitDiffPiece(src) { + const ret = []; + do { + const d = src.shift(); + const pieces = d[1].split(/([^\n]*\n)/).filter((f3) => f3 != ""); + if (typeof d == "undefined") { + break; + } + if (d[0] != import_diff_match_patch4.DIFF_DELETE) { + ret.push(...pieces.map((e2) => [d[0], e2])); + } + if (d[0] == import_diff_match_patch4.DIFF_DELETE) { + const nd = src.shift(); + if (typeof nd != "undefined") { + const piecesPair = nd[1].split(/([^\n]*\n)/).filter((f3) => f3 != ""); + if (nd[0] == import_diff_match_patch4.DIFF_INSERT) { + for (const pt of pieces) { + ret.push([d[0], pt]); + const pairP = piecesPair.shift(); + if (typeof pairP != "undefined") + ret.push([import_diff_match_patch4.DIFF_INSERT, pairP]); + } + ret.push(...piecesPair.map((e2) => [nd[0], e2])); + } else { + ret.push(...pieces.map((e2) => [d[0], e2])); + ret.push(...piecesPair.map((e2) => [nd[0], e2])); + } + } else { + ret.push(...pieces.map((e2) => [0, e2])); + } + } + } while (src.length > 0); + return ret; + } + const diffLeft = splitDiffPiece(diffLeftSrc); + const diffRight = splitDiffPiece(diffRightSrc); + let rightIdx = 0; + let leftIdx = 0; + const merged = []; + autoMerge = true; + LOOP_MERGE: + do { + if (leftIdx >= diffLeft.length && rightIdx >= diffRight.length) { + break LOOP_MERGE; + } + const leftItem = (_a = diffLeft[leftIdx]) != null ? _a : [0, ""]; + const rightItem = (_b = diffRight[rightIdx]) != null ? _b : [0, ""]; + leftIdx++; + rightIdx++; + if (leftItem[0] == import_diff_match_patch4.DIFF_EQUAL && rightItem[0] == import_diff_match_patch4.DIFF_EQUAL && leftItem[1] == rightItem[1]) { + merged.push(leftItem); + continue; + } + if (leftItem[0] == import_diff_match_patch4.DIFF_DELETE && rightItem[0] == import_diff_match_patch4.DIFF_DELETE && leftItem[1] == rightItem[1]) { + const nextLeftIdx = leftIdx; + const nextRightIdx = rightIdx; + const [nextLeftItem, nextRightItem] = [(_c = diffLeft[nextLeftIdx]) != null ? _c : [0, ""], (_d = diffRight[nextRightIdx]) != null ? _d : [0, ""]]; + if (nextLeftItem[0] == import_diff_match_patch4.DIFF_INSERT && nextRightItem[0] == import_diff_match_patch4.DIFF_INSERT && nextLeftItem[1] != nextRightItem[1]) { + autoMerge = false; + break; + } else { + merged.push(leftItem); + continue; + } + } + if (leftItem[0] == import_diff_match_patch4.DIFF_INSERT && rightItem[0] == import_diff_match_patch4.DIFF_INSERT) { + if (leftItem[1] == rightItem[1]) { + merged.push(leftItem); + continue; + } else { + if (leftLeaf.mtime <= rightLeaf.mtime) { + merged.push(leftItem); + merged.push(rightItem); + continue; + } else { + merged.push(rightItem); + merged.push(leftItem); + continue; + } + } + } + if (leftItem[0] == import_diff_match_patch4.DIFF_INSERT) { + rightIdx--; + merged.push(leftItem); + continue; + } + if (rightItem[0] == import_diff_match_patch4.DIFF_INSERT) { + leftIdx--; + merged.push(rightItem); + continue; + } + if (rightItem[1] != leftItem[1]) { + Logger(`MERGING PANIC:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`, LOG_LEVEL.VERBOSE); + autoMerge = false; + break LOOP_MERGE; + } + if (leftItem[0] == import_diff_match_patch4.DIFF_DELETE) { + if (rightItem[0] == import_diff_match_patch4.DIFF_EQUAL) { + merged.push(leftItem); + continue; + } else { + autoMerge = false; + break LOOP_MERGE; + } + } + if (rightItem[0] == import_diff_match_patch4.DIFF_DELETE) { + if (leftItem[0] == import_diff_match_patch4.DIFF_EQUAL) { + merged.push(rightItem); + continue; + } else { + autoMerge = false; + break LOOP_MERGE; + } + } + Logger(`Weird condition:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`, LOG_LEVEL.VERBOSE); + break LOOP_MERGE; + } while (leftIdx < diffLeft.length || rightIdx < diffRight.length); + if (autoMerge) { + Logger(`Sensibly merge available`, LOG_LEVEL.VERBOSE); + return merged; + } else { + return false; + } + } + async mergeObject(path, baseRev, currentRev, conflictedRev) { + try { + const baseLeaf = await this.getConflictedDoc(path, baseRev); + const leftLeaf = await this.getConflictedDoc(path, currentRev); + const rightLeaf = await this.getConflictedDoc(path, conflictedRev); + if (baseLeaf == false || leftLeaf == false || rightLeaf == false) { + return false; + } + const baseObj = { data: tryParseJSON(baseLeaf.data, {}) }; + const leftObj = { data: tryParseJSON(leftLeaf.data, {}) }; + const rightObj = { data: tryParseJSON(rightLeaf.data, {}) }; + const diffLeft = generatePatchObj(baseObj, leftObj); + const diffRight = generatePatchObj(baseObj, rightObj); + const diffSetLeft = new Map(flattenObject(diffLeft)); + const diffSetRight = new Map(flattenObject(diffRight)); + for (const [key, value] of diffSetLeft) { + if (diffSetRight.has(key)) { + if (diffSetRight.get(key) == value) { + diffSetRight.delete(key); + } + } + } + for (const [key, value] of diffSetRight) { + if (diffSetLeft.has(key) && diffSetLeft.get(key) != value) { + return false; + } + } + const patches = [ + { mtime: leftLeaf.mtime, patch: diffLeft }, + { mtime: rightLeaf.mtime, patch: diffRight } + ].sort((a2, b) => a2.mtime - b.mtime); + let newObj = { ...baseObj }; + for (const patch of patches) { + newObj = applyPatch(newObj, patch.patch); + } + return JSON.stringify(newObj.data); + } catch (ex) { + Logger("Could not merge object"); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + } + async getConflictedStatus(path) { + var _a, _b; + const test = await this.localDatabase.getDBEntry(path, { conflicts: true, revs_info: 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 conflicts = test._conflicts.sort((a2, b) => Number(a2.split("-")[0]) - Number(b.split("-")[0])); + if ((isSensibleMargeApplicable(path) || isObjectMargeApplicable(path)) && !this.settings.disableMarkdownAutoMerge) { + const conflictedRev = conflicts[0]; + const conflictedRevNo = Number(conflictedRev.split("-")[0]); + const revFrom = await this.localDatabase.localDatabase.get(path2id(path), { revs_info: true }); + const commonBase = (_b = (_a = revFrom._revs_info.filter((e2) => e2.status == "available" && Number(e2.rev.split("-")[0]) < conflictedRevNo).first()) == null ? void 0 : _a.rev) != null ? _b : ""; + let p = void 0; + if (commonBase) { + if (isSensibleMargeApplicable(path)) { + const result = await this.mergeSensibly(path, commonBase, test._rev, conflictedRev); + if (result) { + p = result.filter((e2) => e2[0] != import_diff_match_patch4.DIFF_DELETE).map((e2) => e2[1]).join(""); + Logger(`Sensible merge:${path}`, LOG_LEVEL.INFO); + } else { + Logger(`Sensible merge is not applicable.`, LOG_LEVEL.VERBOSE); + } + } else if (isObjectMargeApplicable(path)) { + const result = await this.mergeObject(path, commonBase, test._rev, conflictedRev); + if (result) { + Logger(`Object merge:${path}`, LOG_LEVEL.INFO); + p = result; + } else { + Logger(`Object merge is not applicable.`, LOG_LEVEL.VERBOSE); + } + } + if (p != void 0) { + await this.localDatabase.deleteDBEntry(path, { rev: conflictedRev }); + const file = getAbstractFileByPath(path); + if (file) { + await this.app.vault.modify(file, p); + await this.updateIntoDB(file); + } else { + const newFile = await this.app.vault.create(path, p); + await this.updateIntoDB(newFile); + } + await this.pullFile(path); + Logger(`Automatically merged (sensible) :${path}`, LOG_LEVEL.INFO); + return true; + } + } + } + const leftLeaf = await this.getConflictedDoc(path, test._rev); + const rightLeaf = await this.getConflictedDoc(path, 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: 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_patch4.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((res2, rej) => { + Logger("open conflict dialog", LOG_LEVEL.VERBOSE); + new ConflictResolveModal(this.app, filename, 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 res2(true); + } + if (!testDoc._conflicts) { + Logger("Nothing have to do with this conflict", LOG_LEVEL.VERBOSE); + return res2(true); + } + const toDelete = selected; + const toKeep = conflictCheckResult.left.rev != toDelete ? conflictCheckResult.left.rev : conflictCheckResult.right.rev; + if (toDelete == "") { + const p = conflictCheckResult.diff.map((e2) => e2[1]).join(""); + await this.localDatabase.deleteDBEntry(filename, { rev: testDoc._conflicts[0] }); + 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"); + if (this.settings.syncAfterMerge && !this.suspended) { + await this.replicate(); + } + setTimeout(() => { + this.showIfConflicted(filename); + }, 500); + } else if (toDelete == null) { + Logger("Leave it still conflicted"); + } else { + await this.localDatabase.deleteDBEntry(filename, { rev: toDelete }); + await this.pullFile(filename, null, true, toKeep); + Logger(`Conflict resolved:${filename}`); + if (this.settings.syncAfterMerge && !this.suspended) { + await this.replicate(); + } + setTimeout(() => { + this.showIfConflicted(filename); + }, 500); + } + return res2(true); + }).open(); + }); + } + queueConflictedCheck(file) { + this.conflictedCheckFiles = this.conflictedCheckFiles.filter((e2) => e2 != 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_obsidian.TFile) { + await this.showIfConflicted(file2.path); + } + } catch (ex) { + Logger(ex); + } + } + }, 100); + } + async showIfConflicted(filename) { + await runWithLock("conflicted", false, async () => { + const conflictCheckResult = await this.getConflictedStatus(filename); + if (conflictCheckResult === false) { + return; + } + if (conflictCheckResult === true) { + if (this.settings.syncAfterMerge && !this.suspended) { + await this.replicate(); + } + 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, rev2, waitForReady = true) { + const targetFile = getAbstractFileByPath(id2path(filename)); + if (!this.isTargetFile(id2path(filename))) + return; + if (targetFile == null) { + const doc = await this.localDatabase.getDBEntry(filename, rev2 ? { rev: rev2 } : null, false, waitForReady); + if (doc === false) { + Logger(`${filename} Skipped`); + return; + } + await this.doc2storage(doc, void 0, force); + } else if (targetFile instanceof import_obsidian.TFile) { + const file = targetFile; + const doc = await this.localDatabase.getDBEntry(filename, rev2 ? { rev: rev2 } : null, false, waitForReady); + if (doc === false) { + Logger(`${filename} Skipped`); + return; + } + await this.doc2storage(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_obsidian.TFile) && "path" in file) { + const w = getAbstractFileByPath(file.path); + if (w instanceof import_obsidian.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) { + Logger("STORAGE .. DB :" + file.path, LOG_LEVEL.VERBOSE); + 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(docx, file); + } else { + Logger("STORAGE <- DB :" + file.path + " Skipped"); + } + caches[dK] = { storageMtime, docMtime }; + return caches; + } + Logger("STORAGE == DB :" + file.path, LOG_LEVEL.VERBOSE); + caches[dK] = { storageMtime, docMtime }; + return caches; + } + async updateIntoDB(file, initialScan, cache, force) { + if (!this.isTargetFile(file)) + return true; + if (shouldBeIgnored(file.path)) { + return true; + } + let content; + let datatype = "newnote"; + if (!cache) { + if (!isPlainText(file.name)) { + Logger(`Reading : ${file.path}`, LOG_LEVEL.VERBOSE); + const contentBin = await this.app.vault.readBinary(file); + Logger(`Processing: ${file.path}`, LOG_LEVEL.VERBOSE); + try { + content = await arrayBufferToBase64(contentBin); + } catch (ex) { + Logger(`The file ${file.path} could not be encoded`); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + datatype = "newnote"; + } else { + content = await this.app.vault.read(file); + datatype = "plain"; + } + } else { + if (cache instanceof ArrayBuffer) { + Logger(`Processing: ${file.path}`, LOG_LEVEL.VERBOSE); + try { + content = await arrayBufferToBase64(cache); + } catch (ex) { + Logger(`The file ${file.path} could not be encoded`); + Logger(ex, LOG_LEVEL.VERBOSE); + return false; + } + 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; + } + try { + 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 (oldData.deleted != newData.deleted) + return false; + if (!isDocContentSame(old.data, newData.data)) + return false; + Logger(msg + "Skipped (not changed) " + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""), LOG_LEVEL.VERBOSE); + return true; + } + } catch (ex) { + if (force) { + Logger(msg + "Error, Could not check the diff for the old one." + (force ? "force writing." : "") + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""), LOG_LEVEL.VERBOSE); + } else { + Logger(msg + "Error, Could not check the diff for the old one." + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""), LOG_LEVEL.VERBOSE); + } + return !force; + } + return false; + }); + if (isNotChanged) + return true; + const ret = await this.localDatabase.putDBEntry(d, initialScan); + this.queuedFiles = this.queuedFiles.map((e2) => ({ ...e2, ...e2.entry._id == d._id ? { done: true } : {} })); + Logger(msg + fullPath); + if (this.settings.syncOnSave && !this.suspended) { + await this.replicate(); + } + return ret != false; + } + 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(); + } + async tryResetRemoteDatabase() { + await this.replicator.tryResetRemoteDatabase(this.settings); + } + async tryCreateRemoteDatabase() { + await this.replicator.tryCreateRemoteDatabase(this.settings); + } + 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 += "/"; + } + } + filterTargetFiles(files, targetFiles = false) { + const ignorePatterns = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((e2) => e2).map((e2) => new RegExp(e2, "i")); + return files.filter((file) => !ignorePatterns.some((e2) => file.path.match(e2))).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 resolveConflictByNewerEntry(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:${id2filenameInternalMetadata(id)}`); + const conflicts = doc._conflicts.sort((a2, b) => Number(a2.split("-")[0]) - Number(b.split("-")[0])); + const revA = doc._rev; + const revB = 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:${id2filenameInternalMetadata(id)}`); + return true; + } + isTargetFile(file) { + if (file instanceof import_obsidian.TFile) { + return this.localDatabase.isTargetFile(file.path); + } else if (typeof file == "string") { + return this.localDatabase.isTargetFile(file); + } + } +}; diff --git a/src/content/blog/.obsidian/plugins/obsidian-livesync/manifest.json b/src/content/blog/.obsidian/plugins/obsidian-livesync/manifest.json new file mode 100644 index 0000000..97d439e --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-livesync/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-livesync", + "name": "Self-hosted LiveSync", + "version": "0.17.34", + "minAppVersion": "0.9.12", + "description": "Community implementation of self-hosted livesync. Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.", + "author": "vorotamoroz", + "authorUrl": "https://github.com/vrtmrz", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/obsidian-livesync/styles.css b/src/content/blog/.obsidian/plugins/obsidian-livesync/styles.css new file mode 100644 index 0000000..befde2b --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-livesync/styles.css @@ -0,0 +1,254 @@ +.added { + color: var(--text-on-accent); + background-color: var(--text-accent); +} + +.normal { + color: var(--text-normal); +} + +.deleted { + color: var(--text-on-accent); + background-color: var(--text-muted); +} + +.op-scrollable { + overflow-y: scroll; + /* min-height: 280px; */ + max-height: 280px; + user-select: text; +} + +.op-pre { + white-space: pre-wrap; +} + +.op-warn { + border: 1px solid salmon; + padding: 2px; + border-radius: 4px; +} + +.op-warn::before { + content: "Warning"; + font-weight: bold; + color: salmon; + position: relative; + display: block; +} + +.op-warn-info { + border: 1px solid rgb(255, 209, 81); + padding: 2px; + border-radius: 4px; +} + +.op-warn-info::before { + content: "Notice"; + font-weight: bold; + color: rgb(255, 209, 81); + position: relative; + display: block; +} + +.syncstatusbar { + -webkit-filter: grayscale(100%); + filter: grayscale(100%); +} + +.tcenter { + text-align: center; +} + +.sls-plugins-wrap { + display: flex; + flex-grow: 1; + max-height: 50vh; + overflow-y: scroll; +} + +.sls-plugins-tbl { + border: 1px solid var(--background-modifier-border); + width: 100%; + max-height: 80%; +} + +.divider th { + border-top: 1px solid var(--background-modifier-border); +} + +/* .sls-table-head{ + width:50%; +} +.sls-table-tail{ + width:50%; + +} */ + + +.sls-header-button { + margin-left: 2em; +} + +.sls-hidden { + display: none; +} + +:root { + --slsmessage: ""; +} + +.CodeMirror-wrap::before, +.cm-s-obsidian>.cm-editor::before, +.canvas-wrapper::before { + content: attr(data-log); + text-align: right; + white-space: pre-wrap; + position: absolute; + border-radius: 4px; + /* border:1px solid --background-modifier-border; */ + display: inline-block; + top: 8px; + color: --text-normal; + opacity: 0.5; + font-size: 80%; + -webkit-filter: grayscale(100%); + filter: grayscale(100%); +} + +.canvas-wrapper::before { + right: 48px; +} + +.CodeMirror-wrap::before { + right: 0px; +} + +.cm-s-obsidian>.cm-editor::before { + right: 16px; +} + +.sls-setting-tab { + display: none; +} + +div.sls-setting-menu-btn { + color: var(--text-normal); + background-color: var(--background-secondary-alt); + border-radius: 4px 4px 0 0; + padding: 6px 10px; + cursor: pointer; + margin-right: 12px; + font-family: "Inter", sans-serif; + outline: none; + user-select: none; + flex-grow: 1; + text-align: center; + flex-shrink: 1; +} + +.sls-setting-label.selected { + /* order: 1; */ + flex-grow: 1; + /* width: 100%; */ +} + +.sls-setting-tab:hover~div.sls-setting-menu-btn, +.sls-setting-label.selected .sls-setting-tab:checked~div.sls-setting-menu-btn { + background-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +.sls-setting-menu { + display: flex; + flex-direction: row; + /* flex-wrap: wrap; */ + overflow-x: auto; +} + +.sls-setting-label { + flex-grow: 1; + display: inline-flex; + justify-content: center; +} + +.setting-collapsed { + display: none; +} + +.sls-plugins-tbl-buttons { + text-align: right; +} + +.sls-plugins-tbl-buttons button { + flex-grow: 0; + padding: 6px 10px; +} + +.sls-plugins-tbl-device-head { + background-color: var(--background-secondary-alt); + color: var(--text-accent); +} + +.op-flex { + display: flex; +} + +.op-flex input { + display: inline-flex; + flex-grow: 1; + margin-bottom: 8px; +} + +.op-info { + display: inline-flex; + flex-grow: 1; + border-bottom: 1px solid var(--background-modifier-border); + width: 100%; + margin-bottom: 4px; + padding-bottom: 4px; +} + +.history-added { + color: var(--text-on-accent); + background-color: var(--text-accent); +} + +.history-normal { + color: var(--text-normal); +} + +.history-deleted { + color: var(--text-on-accent); + background-color: var(--text-muted); + text-decoration: line-through; +} + +.ob-btn-config-fix label { + margin-right: 40px; +} + +.ob-btn-config-info { + border: 1px solid salmon; + padding: 2px; + margin: 1px; + border-radius: 4px; +} + +.ob-btn-config-head { + padding: 2px; + margin: 1px; + border-radius: 4px; +} + +.isWizard .wizardHidden { + display: none; +} + +.sls-setting:not(.isWizard) .wizardOnly { + display: none; +} + +.sls-item-dirty::before { + content: "✏"; +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/main.js b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/main.js new file mode 100644 index 0000000..a0d3ede --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/main.js @@ -0,0 +1,61 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __reflectGet = Reflect.get; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// main.ts +var main_exports = {}; +__export(main_exports, { + default: () => MarkdownSuffixPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian = require("obsidian"); +var MarkdownSuffixPlugin = class extends import_obsidian.Plugin { + onload() { + return __async(this, null, function* () { + __superGet(MarkdownSuffixPlugin.prototype, this, "onload").call(this); + this.registerExtensions(["mdx", "svx"], "markdown"); + }); + } +}; diff --git a/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/manifest.json b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/manifest.json new file mode 100644 index 0000000..c1ca759 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-markdown-file-suffix", + "name": "Addional Markdown suffix (.mdx/.svx).", + "version": "1.0.0", + "minAppVersion": "0.10.12", + "description": "Use additional files like .mdx / .svx as if they were markdown.", + "author": "swissmation", + "authorUrl": "https://github.com/swissmation", + "isDesktopOnly": false +} diff --git a/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/styles.css b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/styles.css new file mode 100644 index 0000000..71cc60f --- /dev/null +++ b/src/content/blog/.obsidian/plugins/obsidian-markdown-file-suffix/styles.css @@ -0,0 +1,8 @@ +/* + +This CSS file will be included with your plugin, and +available in the app when your plugin is enabled. + +If your plugin does not need CSS, delete this file. + +*/ diff --git a/src/content/blog/.obsidian/plugins/templater-obsidian/data.json b/src/content/blog/.obsidian/plugins/templater-obsidian/data.json new file mode 100644 index 0000000..c128b05 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/templater-obsidian/data.json @@ -0,0 +1,30 @@ +{ + "command_timeout": 5, + "templates_folder": "_templates", + "templates_pairs": [ + [ + "", + "" + ] + ], + "trigger_on_file_creation": true, + "auto_jump_to_cursor": false, + "enable_system_commands": false, + "shell_path": "", + "user_scripts_folder": "", + "enable_folder_templates": true, + "folder_templates": [ + { + "folder": "", + "template": "" + } + ], + "syntax_highlighting": true, + "syntax_highlighting_mobile": true, + "enabled_templates_hotkeys": [ + "" + ], + "startup_templates": [ + "" + ] +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/plugins/templater-obsidian/main.js b/src/content/blog/.obsidian/plugins/templater-obsidian/main.js new file mode 100644 index 0000000..2309914 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/templater-obsidian/main.js @@ -0,0 +1,5624 @@ +/* +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 __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); +}; +var __toBinary = /* @__PURE__ */ (() => { + var table = new Uint8Array(128); + for (var i = 0; i < 64; i++) + table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i; + return (base64) => { + var n = base64.length, bytes = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0); + for (var i2 = 0, j = 0; i2 < n; ) { + var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)]; + var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)]; + bytes[j++] = c0 << 2 | c1 >> 4; + bytes[j++] = c1 << 4 | c2 >> 2; + bytes[j++] = c2 << 6 | c3; + } + return bytes; + }; +})(); + +// src/main.ts +__export(exports, { + default: () => TemplaterPlugin +}); +var import_obsidian17 = __toModule(require("obsidian")); + +// src/settings/Settings.ts +var import_obsidian6 = __toModule(require("obsidian")); + +// src/utils/Log.ts +var import_obsidian = __toModule(require("obsidian")); +function log_error(e) { + const notice = new import_obsidian.Notice("", 8e3); + if (e instanceof TemplaterError && e.console_msg) { + notice.noticeEl.innerHTML = `Templater Error:
    ${e.message}
    Check console for more information`; + console.error(`Templater Error:`, e.message, "\n", e.console_msg); + } else { + notice.noticeEl.innerHTML = `Templater Error:
    ${e.message}`; + } +} + +// src/utils/Error.ts +var TemplaterError = class extends Error { + constructor(msg, console_msg) { + super(msg); + this.console_msg = console_msg; + this.name = this.constructor.name; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +}; +async function errorWrapper(fn2, msg) { + try { + return await fn2(); + } catch (e) { + if (!(e instanceof TemplaterError)) { + log_error(new TemplaterError(msg, e.message)); + } else { + log_error(e); + } + return null; + } +} +function errorWrapperSync(fn2, msg) { + try { + return fn2(); + } catch (e) { + log_error(new TemplaterError(msg, e.message)); + return null; + } +} + +// src/settings/suggesters/FolderSuggester.ts +var import_obsidian3 = __toModule(require("obsidian")); + +// src/settings/suggesters/suggest.ts +var import_obsidian2 = __toModule(require("obsidian")); + +// node_modules/@popperjs/core/lib/enums.js +var top = "top"; +var bottom = "bottom"; +var right = "right"; +var left = "left"; +var auto = "auto"; +var basePlacements = [top, bottom, right, left]; +var start = "start"; +var end = "end"; +var clippingParents = "clippingParents"; +var viewport = "viewport"; +var popper = "popper"; +var reference = "reference"; +var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); +}, []); +var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); +}, []); +var beforeRead = "beforeRead"; +var read = "read"; +var afterRead = "afterRead"; +var beforeMain = "beforeMain"; +var main = "main"; +var afterMain = "afterMain"; +var beforeWrite = "beforeWrite"; +var write = "write"; +var afterWrite = "afterWrite"; +var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; + +// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js +function getNodeName(element) { + return element ? (element.nodeName || "").toLowerCase() : null; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindow.js +function getWindow(node) { + if (node == null) { + return window; + } + if (node.toString() !== "[object Window]") { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } + return node; +} + +// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js +function isElement(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; +} +function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; +} +function isShadowRoot(node) { + if (typeof ShadowRoot === "undefined") { + return false; + } + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; +} + +// node_modules/@popperjs/core/lib/modifiers/applyStyles.js +function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function(name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element = state.elements[name]; + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(name2) { + var value = attributes[name2]; + if (value === false) { + element.removeAttribute(name2); + } else { + element.setAttribute(name2, value === true ? "" : value); + } + }); + }); +} +function effect(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: "0", + top: "0", + margin: "0" + }, + arrow: { + position: "absolute" + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + return function() { + Object.keys(state.elements).forEach(function(name) { + var element = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); + var style = styleProperties.reduce(function(style2, property) { + style2[property] = ""; + return style2; + }, {}); + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(attribute) { + element.removeAttribute(attribute); + }); + }); + }; +} +var applyStyles_default = { + name: "applyStyles", + enabled: true, + phase: "write", + fn: applyStyles, + effect, + requires: ["computeStyles"] +}; + +// node_modules/@popperjs/core/lib/utils/getBasePlacement.js +function getBasePlacement(placement) { + return placement.split("-")[0]; +} + +// node_modules/@popperjs/core/lib/utils/math.js +var max = Math.max; +var min = Math.min; +var round = Math.round; + +// node_modules/@popperjs/core/lib/utils/userAgent.js +function getUAString() { + var uaData = navigator.userAgentData; + if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { + return uaData.brands.map(function(item) { + return item.brand + "/" + item.version; + }).join(" "); + } + return navigator.userAgent; +} + +// node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js +function isLayoutViewport() { + return !/^((?!chrome|android).)*safari/i.test(getUAString()); +} + +// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js +function getBoundingClientRect(element, includeScale, isFixedStrategy) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + var clientRect = element.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; + if (includeScale && isHTMLElement(element)) { + scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; + scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; + } + var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport; + var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; + var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; + var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; + var width = clientRect.width / scaleX; + var height = clientRect.height / scaleY; + return { + width, + height, + top: y, + right: x + width, + bottom: y + height, + left: x, + x, + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js +function getLayoutRect(element) { + var clientRect = getBoundingClientRect(element); + var width = element.offsetWidth; + var height = element.offsetHeight; + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + return { + x: element.offsetLeft, + y: element.offsetTop, + width, + height + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/contains.js +function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); + if (parent.contains(child)) { + return true; + } else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + do { + if (next && parent.isSameNode(next)) { + return true; + } + next = next.parentNode || next.host; + } while (next); + } + return false; +} + +// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js +function getComputedStyle(element) { + return getWindow(element).getComputedStyle(element); +} + +// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js +function isTableElement(element) { + return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js +function getDocumentElement(element) { + return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement; +} + +// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js +function getParentNode(element) { + if (getNodeName(element) === "html") { + return element; + } + return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element); +} + +// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js +function getTrueOffsetParent(element) { + if (!isHTMLElement(element) || getComputedStyle(element).position === "fixed") { + return null; + } + return element.offsetParent; +} +function getContainingBlock(element) { + var isFirefox = /firefox/i.test(getUAString()); + var isIE = /Trident/i.test(getUAString()); + if (isIE && isHTMLElement(element)) { + var elementCss = getComputedStyle(element); + if (elementCss.position === "fixed") { + return null; + } + } + var currentNode = getParentNode(element); + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle(currentNode); + if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { + return currentNode; + } else { + currentNode = currentNode.parentNode; + } + } + return null; +} +function getOffsetParent(element) { + var window2 = getWindow(element); + var offsetParent = getTrueOffsetParent(element); + while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") { + offsetParent = getTrueOffsetParent(offsetParent); + } + if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) { + return window2; + } + return offsetParent || getContainingBlock(element) || window2; +} + +// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js +function getMainAxisFromPlacement(placement) { + return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; +} + +// node_modules/@popperjs/core/lib/utils/within.js +function within(min2, value, max2) { + return max(min2, min(value, max2)); +} +function withinMaxClamp(min2, value, max2) { + var v = within(min2, value, max2); + return v > max2 ? max2 : v; +} + +// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js +function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 + }; +} + +// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js +function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); +} + +// node_modules/@popperjs/core/lib/utils/expandToHashMap.js +function expandToHashMap(value, keys) { + return keys.reduce(function(hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); +} + +// node_modules/@popperjs/core/lib/modifiers/arrow.js +var toPaddingObject = function toPaddingObject2(padding, state) { + padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); +}; +function arrow(_ref) { + var _state$modifiersData$; + var state = _ref.state, name = _ref.name, options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets2 = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? "height" : "width"; + if (!arrowElement || !popperOffsets2) { + return; + } + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === "y" ? top : left; + var maxProp = axis === "y" ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; + var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; + var min2 = paddingObject[minProp]; + var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset2 = within(min2, center, max2); + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$); +} +function effect2(_ref2) { + var state = _ref2.state, options = _ref2.options; + var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; + if (arrowElement == null) { + return; + } + if (typeof arrowElement === "string") { + arrowElement = state.elements.popper.querySelector(arrowElement); + if (!arrowElement) { + return; + } + } + if (!contains(state.elements.popper, arrowElement)) { + return; + } + state.elements.arrow = arrowElement; +} +var arrow_default = { + name: "arrow", + enabled: true, + phase: "main", + fn: arrow, + effect: effect2, + requires: ["popperOffsets"], + requiresIfExists: ["preventOverflow"] +}; + +// node_modules/@popperjs/core/lib/utils/getVariation.js +function getVariation(placement) { + return placement.split("-")[1]; +} + +// node_modules/@popperjs/core/lib/modifiers/computeStyles.js +var unsetSides = { + top: "auto", + right: "auto", + bottom: "auto", + left: "auto" +}; +function roundOffsetsByDPR(_ref, win) { + var x = _ref.x, y = _ref.y; + var dpr = win.devicePixelRatio || 1; + return { + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 + }; +} +function mapToStyles(_ref2) { + var _Object$assign2; + var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y; + var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ + x, + y + }) : { + x, + y + }; + x = _ref3.x; + y = _ref3.y; + var hasX = offsets.hasOwnProperty("x"); + var hasY = offsets.hasOwnProperty("y"); + var sideX = left; + var sideY = top; + var win = window; + if (adaptive) { + var offsetParent = getOffsetParent(popper2); + var heightProp = "clientHeight"; + var widthProp = "clientWidth"; + if (offsetParent === getWindow(popper2)) { + offsetParent = getDocumentElement(popper2); + if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") { + heightProp = "scrollHeight"; + widthProp = "scrollWidth"; + } + } + offsetParent = offsetParent; + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp]; + y -= offsetY - popperRect.height; + y *= gpuAcceleration ? 1 : -1; + } + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp]; + x -= offsetX - popperRect.width; + x *= gpuAcceleration ? 1 : -1; + } + } + var commonStyles = Object.assign({ + position + }, adaptive && unsetSides); + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x, + y + }, getWindow(popper2)) : { + x, + y + }; + x = _ref4.x; + y = _ref4.y; + if (gpuAcceleration) { + var _Object$assign; + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2)); +} +function computeStyles(_ref5) { + var state = _ref5.state, options = _ref5.options; + var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + var commonStyles = { + placement: getBasePlacement(state.placement), + variation: getVariation(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration, + isFixed: state.options.strategy === "fixed" + }; + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive, + roundOffsets + }))); + } + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: "absolute", + adaptive: false, + roundOffsets + }))); + } + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-placement": state.placement + }); +} +var computeStyles_default = { + name: "computeStyles", + enabled: true, + phase: "beforeWrite", + fn: computeStyles, + data: {} +}; + +// node_modules/@popperjs/core/lib/modifiers/eventListeners.js +var passive = { + passive: true +}; +function effect3(_ref) { + var state = _ref.state, instance = _ref.instance, options = _ref.options; + var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; + var window2 = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.addEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.addEventListener("resize", instance.update, passive); + } + return function() { + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.removeEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.removeEventListener("resize", instance.update, passive); + } + }; +} +var eventListeners_default = { + name: "eventListeners", + enabled: true, + phase: "write", + fn: function fn() { + }, + effect: effect3, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js +var hash = { + left: "right", + right: "left", + bottom: "top", + top: "bottom" +}; +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function(matched) { + return hash[matched]; + }); +} + +// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js +var hash2 = { + start: "end", + end: "start" +}; +function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function(matched) { + return hash2[matched]; + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js +function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft, + scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js +function getWindowScrollBarX(element) { + return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; +} + +// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js +function getViewportRect(element, strategy) { + var win = getWindow(element); + var html = getDocumentElement(element); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + var layoutViewport = isLayoutViewport(); + if (layoutViewport || !layoutViewport && strategy === "fixed") { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x: x + getWindowScrollBarX(element), + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js +function getDocumentRect(element) { + var _element$ownerDocumen; + var html = getDocumentElement(element); + var winScroll = getWindowScroll(element); + var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element); + var y = -winScroll.scrollTop; + if (getComputedStyle(body || html).direction === "rtl") { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; + } + return { + width, + height, + x, + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js +function isScrollParent(element) { + var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); +} + +// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js +function getScrollParent(node) { + if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { + return node.ownerDocument.body; + } + if (isHTMLElement(node) && isScrollParent(node)) { + return node; + } + return getScrollParent(getParentNode(node)); +} + +// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js +function listScrollParents(element, list) { + var _element$ownerDocumen; + if (list === void 0) { + list = []; + } + var scrollParent = getScrollParent(element); + var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target))); +} + +// node_modules/@popperjs/core/lib/utils/rectToClientRect.js +function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js +function getInnerBoundingClientRect(element, strategy) { + var rect = getBoundingClientRect(element, false, strategy === "fixed"); + rect.top = rect.top + element.clientTop; + rect.left = rect.left + element.clientLeft; + rect.bottom = rect.top + element.clientHeight; + rect.right = rect.left + element.clientWidth; + rect.width = element.clientWidth; + rect.height = element.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; +} +function getClientRectFromMixedType(element, clippingParent, strategy) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); +} +function getClippingParents(element) { + var clippingParents2 = listScrollParents(getParentNode(element)); + var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; + if (!isElement(clipperElement)) { + return []; + } + return clippingParents2.filter(function(clippingParent) { + return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; + }); +} +function getClippingRect(element, boundary, rootBoundary, strategy) { + var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary); + var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents2[0]; + var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { + var rect = getClientRectFromMixedType(element, clippingParent, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element, firstClippingParent, strategy)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; +} + +// node_modules/@popperjs/core/lib/utils/computeOffsets.js +function computeOffsets(_ref) { + var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement; + var basePlacement = placement ? getBasePlacement(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference2.x + reference2.width / 2 - element.width / 2; + var commonY = reference2.y + reference2.height / 2 - element.height / 2; + var offsets; + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference2.y - element.height + }; + break; + case bottom: + offsets = { + x: commonX, + y: reference2.y + reference2.height + }; + break; + case right: + offsets = { + x: reference2.x + reference2.width, + y: commonY + }; + break; + case left: + offsets = { + x: reference2.x - element.width, + y: commonY + }; + break; + default: + offsets = { + x: reference2.x, + y: reference2.y + }; + } + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; + if (mainAxis != null) { + var len = mainAxis === "y" ? "height" : "width"; + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2); + break; + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2); + break; + default: + } + } + return offsets; +} + +// node_modules/@popperjs/core/lib/utils/detectOverflow.js +function detectOverflow(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var popperRect = state.rects.popper; + var element = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); + var referenceClientRect = getBoundingClientRect(state.elements.reference); + var popperOffsets2 = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + strategy: "absolute", + placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right + }; + var offsetData = state.modifiersData.offset; + if (elementContext === popper && offsetData) { + var offset2 = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function(key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; + overflowOffsets[key] += offset2[axis] * multiply; + }); + } + return overflowOffsets; +} + +// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js +function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { + return getVariation(placement2) === variation; + }) : basePlacements; + var allowedPlacements = placements2.filter(function(placement2) { + return allowedAutoPlacements.indexOf(placement2) >= 0; + }); + if (allowedPlacements.length === 0) { + allowedPlacements = placements2; + } + var overflows = allowedPlacements.reduce(function(acc, placement2) { + acc[placement2] = detectOverflow(state, { + placement: placement2, + boundary, + rootBoundary, + padding + })[getBasePlacement(placement2)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function(a, b) { + return overflows[a] - overflows[b]; + }); +} + +// node_modules/@popperjs/core/lib/modifiers/flip.js +function getExpandedFallbackPlacements(placement) { + if (getBasePlacement(placement) === auto) { + return []; + } + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; +} +function flip(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + if (state.modifiersData[name]._skip) { + return; + } + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { + return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, { + placement: placement2, + boundary, + rootBoundary, + padding, + flipVariations, + allowedAutoPlacements + }) : placement2); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements2[0]; + for (var i = 0; i < placements2.length; i++) { + var placement = placements2[i]; + var _basePlacement = getBasePlacement(placement); + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? "width" : "height"; + var overflow = detectOverflow(state, { + placement, + boundary, + rootBoundary, + altBoundary, + padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); + } + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } + if (checks.every(function(check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } + checksMap.set(placement, checks); + } + if (makeFallbackChecks) { + var numberOfChecks = flipVariations ? 3 : 1; + var _loop = function _loop2(_i2) { + var fittingPlacement = placements2.find(function(placement2) { + var checks2 = checksMap.get(placement2); + if (checks2) { + return checks2.slice(0, _i2).every(function(check) { + return check; + }); + } + }); + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); + if (_ret === "break") + break; + } + } + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } +} +var flip_default = { + name: "flip", + enabled: true, + phase: "main", + fn: flip, + requiresIfExists: ["offset"], + data: { + _skip: false + } +}; + +// node_modules/@popperjs/core/lib/modifiers/hide.js +function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x + }; +} +function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function(side) { + return overflow[side] >= 0; + }); +} +function hide(_ref) { + var state = _ref.state, name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: "reference" + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets, + popperEscapeOffsets, + isReferenceHidden, + hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-reference-hidden": isReferenceHidden, + "data-popper-escaped": hasPopperEscaped + }); +} +var hide_default = { + name: "hide", + enabled: true, + phase: "main", + requiresIfExists: ["preventOverflow"], + fn: hide +}; + +// node_modules/@popperjs/core/lib/modifiers/offset.js +function distanceAndSkiddingToXY(placement, rects, offset2) { + var basePlacement = getBasePlacement(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, { + placement + })) : offset2, skidding = _ref[0], distance = _ref[1]; + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; +} +function offset(_ref2) { + var state = _ref2.state, options = _ref2.options, name = _ref2.name; + var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function(acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2); + return acc; + }, {}); + var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } + state.modifiersData[name] = data; +} +var offset_default = { + name: "offset", + enabled: true, + phase: "main", + requires: ["popperOffsets"], + fn: offset +}; + +// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js +function popperOffsets(_ref) { + var state = _ref.state, name = _ref.name; + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + strategy: "absolute", + placement: state.placement + }); +} +var popperOffsets_default = { + name: "popperOffsets", + enabled: true, + phase: "read", + fn: popperOffsets, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getAltAxis.js +function getAltAxis(axis) { + return axis === "x" ? "y" : "x"; +} + +// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js +function preventOverflow(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary, + rootBoundary, + padding, + altBoundary + }); + var basePlacement = getBasePlacement(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets2 = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; + var data = { + x: 0, + y: 0 + }; + if (!popperOffsets2) { + return; + } + if (checkMainAxis) { + var _offsetModifierState$; + var mainSide = mainAxis === "y" ? top : left; + var altSide = mainAxis === "y" ? bottom : right; + var len = mainAxis === "y" ? "height" : "width"; + var offset2 = popperOffsets2[mainAxis]; + var min2 = offset2 + overflow[mainSide]; + var max2 = offset2 - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset2 + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2); + popperOffsets2[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset2; + } + if (checkAltAxis) { + var _offsetModifierState$2; + var _mainSide = mainAxis === "x" ? top : left; + var _altSide = mainAxis === "x" ? bottom : right; + var _offset = popperOffsets2[altAxis]; + var _len = altAxis === "y" ? "height" : "width"; + var _min = _offset + overflow[_mainSide]; + var _max = _offset - overflow[_altSide]; + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + popperOffsets2[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + state.modifiersData[name] = data; +} +var preventOverflow_default = { + name: "preventOverflow", + enabled: true, + phase: "main", + fn: preventOverflow, + requiresIfExists: ["offset"] +}; + +// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js +function getHTMLElementScroll(element) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js +function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } +} + +// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js +function isElementScaled(element) { + var rect = element.getBoundingClientRect(); + var scaleX = round(rect.width) / element.offsetWidth || 1; + var scaleY = round(rect.height) / element.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; +} +function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; + } + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; +} + +// node_modules/@popperjs/core/lib/utils/orderModifiers.js +function order(modifiers) { + var map = new Map(); + var visited = new Set(); + var result = []; + modifiers.forEach(function(modifier) { + map.set(modifier.name, modifier); + }); + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function(dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + if (depModifier) { + sort(depModifier); + } + } + }); + result.push(modifier); + } + modifiers.forEach(function(modifier) { + if (!visited.has(modifier.name)) { + sort(modifier); + } + }); + return result; +} +function orderModifiers(modifiers) { + var orderedModifiers = order(modifiers); + return modifierPhases.reduce(function(acc, phase) { + return acc.concat(orderedModifiers.filter(function(modifier) { + return modifier.phase === phase; + })); + }, []); +} + +// node_modules/@popperjs/core/lib/utils/debounce.js +function debounce(fn2) { + var pending; + return function() { + if (!pending) { + pending = new Promise(function(resolve) { + Promise.resolve().then(function() { + pending = void 0; + resolve(fn2()); + }); + }); + } + return pending; + }; +} + +// node_modules/@popperjs/core/lib/utils/mergeByName.js +function mergeByName(modifiers) { + var merged = modifiers.reduce(function(merged2, current) { + var existing = merged2[current.name]; + merged2[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged2; + }, {}); + return Object.keys(merged).map(function(key) { + return merged[key]; + }); +} + +// node_modules/@popperjs/core/lib/createPopper.js +var DEFAULT_OPTIONS = { + placement: "bottom", + modifiers: [], + strategy: "absolute" +}; +function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return !args.some(function(element) { + return !(element && typeof element.getBoundingClientRect === "function"); + }); +} +function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; + } + var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper2(reference2, popper2, options) { + if (options === void 0) { + options = defaultOptions; + } + var state = { + placement: "bottom", + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference2, + popper: popper2 + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance = { + state, + setOptions: function setOptions(setOptionsAction) { + var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options2); + state.scrollParents = { + reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], + popper: listScrollParents(popper2) + }; + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); + state.orderedModifiers = orderedModifiers.filter(function(m) { + return m.enabled; + }); + runModifierEffects(); + return instance.update(); + }, + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } + var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; + if (!areValidElements(reference3, popper3)) { + return; + } + state.rects = { + reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), + popper: getLayoutRect(popper3) + }; + state.reset = false; + state.placement = state.options.placement; + state.orderedModifiers.forEach(function(modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); + for (var index = 0; index < state.orderedModifiers.length; index++) { + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } + var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; + if (typeof fn2 === "function") { + state = fn2({ + state, + options: _options, + name, + instance + }) || state; + } + } + }, + update: debounce(function() { + return new Promise(function(resolve) { + instance.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; + if (!areValidElements(reference2, popper2)) { + return instance; + } + instance.setOptions(options).then(function(state2) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state2); + } + }); + function runModifierEffects() { + state.orderedModifiers.forEach(function(_ref) { + var name = _ref.name, _ref$options = _ref.options, options2 = _ref$options === void 0 ? {} : _ref$options, effect4 = _ref.effect; + if (typeof effect4 === "function") { + var cleanupFn = effect4({ + state, + name, + instance, + options: options2 + }); + var noopFn = function noopFn2() { + }; + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + function cleanupModifierEffects() { + effectCleanupFns.forEach(function(fn2) { + return fn2(); + }); + effectCleanupFns = []; + } + return instance; + }; +} + +// node_modules/@popperjs/core/lib/popper.js +var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default]; +var createPopper = /* @__PURE__ */ popperGenerator({ + defaultModifiers +}); + +// src/settings/suggesters/suggest.ts +var wrapAround = (value, size) => { + return (value % size + size) % size; +}; +var Suggest = class { + constructor(owner, containerEl, scope) { + this.owner = owner; + this.containerEl = containerEl; + containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this)); + containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this)); + scope.register([], "ArrowUp", (event) => { + if (!event.isComposing) { + this.setSelectedItem(this.selectedItem - 1, true); + return false; + } + }); + scope.register([], "ArrowDown", (event) => { + if (!event.isComposing) { + this.setSelectedItem(this.selectedItem + 1, true); + return false; + } + }); + scope.register([], "Enter", (event) => { + if (!event.isComposing) { + this.useSelectedItem(event); + return false; + } + }); + } + onSuggestionClick(event, el) { + event.preventDefault(); + const item = this.suggestions.indexOf(el); + this.setSelectedItem(item, false); + this.useSelectedItem(event); + } + onSuggestionMouseover(_event, el) { + const item = this.suggestions.indexOf(el); + this.setSelectedItem(item, false); + } + setSuggestions(values) { + this.containerEl.empty(); + const suggestionEls = []; + values.forEach((value) => { + const suggestionEl = this.containerEl.createDiv("suggestion-item"); + this.owner.renderSuggestion(value, suggestionEl); + suggestionEls.push(suggestionEl); + }); + this.values = values; + this.suggestions = suggestionEls; + this.setSelectedItem(0, false); + } + useSelectedItem(event) { + const currentValue = this.values[this.selectedItem]; + if (currentValue) { + this.owner.selectSuggestion(currentValue, event); + } + } + setSelectedItem(selectedIndex, scrollIntoView) { + const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length); + const prevSelectedSuggestion = this.suggestions[this.selectedItem]; + const selectedSuggestion = this.suggestions[normalizedIndex]; + prevSelectedSuggestion?.removeClass("is-selected"); + selectedSuggestion?.addClass("is-selected"); + this.selectedItem = normalizedIndex; + if (scrollIntoView) { + selectedSuggestion.scrollIntoView(false); + } + } +}; +var TextInputSuggest = class { + constructor(inputEl) { + this.inputEl = inputEl; + this.scope = new import_obsidian2.Scope(); + this.suggestEl = createDiv("suggestion-container"); + const suggestion = this.suggestEl.createDiv("suggestion"); + this.suggest = new Suggest(this, suggestion, this.scope); + this.scope.register([], "Escape", this.close.bind(this)); + this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); + this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); + this.inputEl.addEventListener("blur", this.close.bind(this)); + this.suggestEl.on("mousedown", ".suggestion-container", (event) => { + event.preventDefault(); + }); + } + onInputChanged() { + const inputStr = this.inputEl.value; + const suggestions = this.getSuggestions(inputStr); + if (!suggestions) { + this.close(); + return; + } + if (suggestions.length > 0) { + this.suggest.setSuggestions(suggestions); + this.open(app.dom.appContainerEl, this.inputEl); + } else { + this.close(); + } + } + open(container, inputEl) { + app.keymap.pushScope(this.scope); + container.appendChild(this.suggestEl); + this.popper = createPopper(inputEl, this.suggestEl, { + placement: "bottom-start", + modifiers: [ + { + name: "sameWidth", + enabled: true, + fn: ({ state, instance }) => { + const targetWidth = `${state.rects.reference.width}px`; + if (state.styles.popper.width === targetWidth) { + return; + } + state.styles.popper.width = targetWidth; + instance.update(); + }, + phase: "beforeWrite", + requires: ["computeStyles"] + } + ] + }); + } + close() { + app.keymap.popScope(this.scope); + this.suggest.setSuggestions([]); + if (this.popper) + this.popper.destroy(); + this.suggestEl.detach(); + } +}; + +// src/settings/suggesters/FolderSuggester.ts +var FolderSuggest = class extends TextInputSuggest { + getSuggestions(inputStr) { + const abstractFiles = app.vault.getAllLoadedFiles(); + const folders = []; + const lowerCaseInputStr = inputStr.toLowerCase(); + abstractFiles.forEach((folder) => { + if (folder instanceof import_obsidian3.TFolder && folder.path.toLowerCase().contains(lowerCaseInputStr)) { + folders.push(folder); + } + }); + return folders.slice(0, 1e3); + } + renderSuggestion(file, el) { + el.setText(file.path); + } + selectSuggestion(file) { + this.inputEl.value = file.path; + this.inputEl.trigger("input"); + this.close(); + } +}; + +// src/settings/suggesters/FileSuggester.ts +var import_obsidian5 = __toModule(require("obsidian")); + +// src/utils/Utils.ts +var import_obsidian4 = __toModule(require("obsidian")); +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function escape_RegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function generate_dynamic_command_regex() { + return /(<%(?:-|_)?\s*[*~]{0,1})\+((?:.|\s)*?%>)/g; +} +function resolve_tfolder(folder_str) { + folder_str = (0, import_obsidian4.normalizePath)(folder_str); + const folder = app.vault.getAbstractFileByPath(folder_str); + if (!folder) { + throw new TemplaterError(`Folder "${folder_str}" doesn't exist`); + } + if (!(folder instanceof import_obsidian4.TFolder)) { + throw new TemplaterError(`${folder_str} is a file, not a folder`); + } + return folder; +} +function resolve_tfile(file_str) { + file_str = (0, import_obsidian4.normalizePath)(file_str); + const file = app.vault.getAbstractFileByPath(file_str); + if (!file) { + throw new TemplaterError(`File "${file_str}" doesn't exist`); + } + if (!(file instanceof import_obsidian4.TFile)) { + throw new TemplaterError(`${file_str} is a folder, not a file`); + } + return file; +} +function get_tfiles_from_folder(folder_str) { + const folder = resolve_tfolder(folder_str); + const files = []; + import_obsidian4.Vault.recurseChildren(folder, (file) => { + if (file instanceof import_obsidian4.TFile) { + files.push(file); + } + }); + files.sort((a, b) => { + return a.path.localeCompare(b.path); + }); + return files; +} +function arraymove(arr, fromIndex, toIndex) { + if (toIndex < 0 || toIndex === arr.length) { + return; + } + const element = arr[fromIndex]; + arr[fromIndex] = arr[toIndex]; + arr[toIndex] = element; +} +function get_active_file(app2) { + return app2.workspace.activeEditor?.file ?? app2.workspace.getActiveFile(); +} +function get_folder_path_from_file_path(path) { + const path_separator = path.lastIndexOf("/"); + if (path_separator !== -1) + return path.slice(0, path_separator); + return ""; +} + +// src/settings/suggesters/FileSuggester.ts +var FileSuggestMode; +(function(FileSuggestMode2) { + FileSuggestMode2[FileSuggestMode2["TemplateFiles"] = 0] = "TemplateFiles"; + FileSuggestMode2[FileSuggestMode2["ScriptFiles"] = 1] = "ScriptFiles"; +})(FileSuggestMode || (FileSuggestMode = {})); +var FileSuggest = class extends TextInputSuggest { + constructor(inputEl, plugin, mode) { + super(inputEl); + this.inputEl = inputEl; + this.plugin = plugin; + this.mode = mode; + } + get_folder(mode) { + switch (mode) { + case 0: + return this.plugin.settings.templates_folder; + case 1: + return this.plugin.settings.user_scripts_folder; + } + } + get_error_msg(mode) { + switch (mode) { + case 0: + return `Templates folder doesn't exist`; + case 1: + return `User Scripts folder doesn't exist`; + } + } + getSuggestions(input_str) { + const all_files = errorWrapperSync(() => get_tfiles_from_folder(this.get_folder(this.mode)), this.get_error_msg(this.mode)); + if (!all_files) { + return []; + } + const files = []; + const lower_input_str = input_str.toLowerCase(); + all_files.forEach((file) => { + if (file instanceof import_obsidian5.TFile && file.extension === "md" && file.path.toLowerCase().contains(lower_input_str)) { + files.push(file); + } + }); + return files.slice(0, 1e3); + } + renderSuggestion(file, el) { + el.setText(file.path); + } + selectSuggestion(file) { + this.inputEl.value = file.path; + this.inputEl.trigger("input"); + this.close(); + } +}; + +// src/settings/Settings.ts +var DEFAULT_SETTINGS = { + command_timeout: 5, + templates_folder: "", + templates_pairs: [["", ""]], + trigger_on_file_creation: false, + auto_jump_to_cursor: false, + enable_system_commands: false, + shell_path: "", + user_scripts_folder: "", + enable_folder_templates: true, + folder_templates: [{ folder: "", template: "" }], + syntax_highlighting: true, + syntax_highlighting_mobile: false, + enabled_templates_hotkeys: [""], + startup_templates: [""] +}; +var TemplaterSettingTab = class extends import_obsidian6.PluginSettingTab { + constructor(plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + this.containerEl.empty(); + this.add_template_folder_setting(); + this.add_internal_functions_setting(); + this.add_syntax_highlighting_settings(); + this.add_auto_jump_to_cursor(); + this.add_trigger_on_new_file_creation_setting(); + this.add_templates_hotkeys_setting(); + if (this.plugin.settings.trigger_on_file_creation) { + this.add_folder_templates_setting(); + } + this.add_startup_templates_setting(); + this.add_user_script_functions_setting(); + this.add_user_system_command_functions_setting(); + this.add_donating_setting(); + } + add_template_folder_setting() { + new import_obsidian6.Setting(this.containerEl).setName("Template folder location").setDesc("Files in this folder will be available as templates.").addSearch((cb) => { + new FolderSuggest(cb.inputEl); + cb.setPlaceholder("Example: folder1/folder2").setValue(this.plugin.settings.templates_folder).onChange((new_folder) => { + this.plugin.settings.templates_folder = new_folder; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }); + } + add_internal_functions_setting() { + const desc = document.createDocumentFragment(); + desc.append("Templater provides multiples predefined variables / functions that you can use.", desc.createEl("br"), "Check the ", desc.createEl("a", { + href: "https://silentvoid13.github.io/Templater/", + text: "documentation" + }), " to get a list of all the available internal variables / functions."); + new import_obsidian6.Setting(this.containerEl).setName("Internal variables and functions").setDesc(desc); + } + add_syntax_highlighting_settings() { + const desktopDesc = document.createDocumentFragment(); + desktopDesc.append("Adds syntax highlighting for Templater commands in edit mode."); + const mobileDesc = document.createDocumentFragment(); + mobileDesc.append("Adds syntax highlighting for Templater commands in edit mode on mobile. Use with caution: this may break live preview on mobile platforms."); + new import_obsidian6.Setting(this.containerEl).setName("Syntax highlighting on desktop").setDesc(desktopDesc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.syntax_highlighting).onChange((syntax_highlighting) => { + this.plugin.settings.syntax_highlighting = syntax_highlighting; + this.plugin.save_settings(); + this.plugin.event_handler.update_syntax_highlighting(); + }); + }); + new import_obsidian6.Setting(this.containerEl).setName("Syntax highlighting on mobile").setDesc(mobileDesc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.syntax_highlighting_mobile).onChange((syntax_highlighting_mobile) => { + this.plugin.settings.syntax_highlighting_mobile = syntax_highlighting_mobile; + this.plugin.save_settings(); + this.plugin.event_handler.update_syntax_highlighting(); + }); + }); + } + add_auto_jump_to_cursor() { + const desc = document.createDocumentFragment(); + desc.append("Automatically triggers ", desc.createEl("code", { text: "tp.file.cursor" }), " after inserting a template.", desc.createEl("br"), "You can also set a hotkey to manually trigger ", desc.createEl("code", { text: "tp.file.cursor" }), "."); + new import_obsidian6.Setting(this.containerEl).setName("Automatic jump to cursor").setDesc(desc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.auto_jump_to_cursor).onChange((auto_jump_to_cursor) => { + this.plugin.settings.auto_jump_to_cursor = auto_jump_to_cursor; + this.plugin.save_settings(); + }); + }); + } + add_trigger_on_new_file_creation_setting() { + const desc = document.createDocumentFragment(); + desc.append("Templater will listen for the new file creation event, and replace every command it finds in the new file's content.", desc.createEl("br"), "This makes Templater compatible with other plugins like the Daily note core plugin, Calendar plugin, Review plugin, Note refactor plugin, ...", desc.createEl("br"), desc.createEl("b", { + text: "Warning: " + }), "This can be dangerous if you create new files with unknown / unsafe content on creation. Make sure that every new file's content is safe on creation."); + new import_obsidian6.Setting(this.containerEl).setName("Trigger Templater on new file creation").setDesc(desc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.trigger_on_file_creation).onChange((trigger_on_file_creation) => { + this.plugin.settings.trigger_on_file_creation = trigger_on_file_creation; + this.plugin.save_settings(); + this.plugin.event_handler.update_trigger_file_on_creation(); + this.display(); + }); + }); + } + add_templates_hotkeys_setting() { + new import_obsidian6.Setting(this.containerEl).setName("Template hotkeys").setHeading(); + const desc = document.createDocumentFragment(); + desc.append("Template hotkeys allows you to bind a template to a hotkey."); + new import_obsidian6.Setting(this.containerEl).setDesc(desc); + this.plugin.settings.enabled_templates_hotkeys.forEach((template, index) => { + const s = new import_obsidian6.Setting(this.containerEl).addSearch((cb) => { + new FileSuggest(cb.inputEl, this.plugin, FileSuggestMode.TemplateFiles); + cb.setPlaceholder("Example: folder1/template_file").setValue(template).onChange((new_template) => { + if (new_template && this.plugin.settings.enabled_templates_hotkeys.contains(new_template)) { + log_error(new TemplaterError("This template is already bound to a hotkey")); + return; + } + this.plugin.command_handler.add_template_hotkey(this.plugin.settings.enabled_templates_hotkeys[index], new_template); + this.plugin.settings.enabled_templates_hotkeys[index] = new_template; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }).addExtraButton((cb) => { + cb.setIcon("any-key").setTooltip("Configure Hotkey").onClick(() => { + app.setting.openTabById("hotkeys"); + const tab = app.setting.activeTab; + tab.searchInputEl.value = "Templater: Insert"; + tab.updateHotkeyVisibility(); + }); + }).addExtraButton((cb) => { + cb.setIcon("up-chevron-glyph").setTooltip("Move up").onClick(() => { + arraymove(this.plugin.settings.enabled_templates_hotkeys, index, index - 1); + this.plugin.save_settings(); + this.display(); + }); + }).addExtraButton((cb) => { + cb.setIcon("down-chevron-glyph").setTooltip("Move down").onClick(() => { + arraymove(this.plugin.settings.enabled_templates_hotkeys, index, index + 1); + this.plugin.save_settings(); + this.display(); + }); + }).addExtraButton((cb) => { + cb.setIcon("cross").setTooltip("Delete").onClick(() => { + this.plugin.command_handler.remove_template_hotkey(this.plugin.settings.enabled_templates_hotkeys[index]); + this.plugin.settings.enabled_templates_hotkeys.splice(index, 1); + this.plugin.save_settings(); + this.display(); + }); + }); + s.infoEl.remove(); + }); + new import_obsidian6.Setting(this.containerEl).addButton((cb) => { + cb.setButtonText("Add new hotkey for template").setCta().onClick(() => { + this.plugin.settings.enabled_templates_hotkeys.push(""); + this.plugin.save_settings(); + this.display(); + }); + }); + } + add_folder_templates_setting() { + this.containerEl.createEl("h2", { text: "Folder templates" }); + new import_obsidian6.Setting(this.containerEl).setName("Folder templates").setHeading(); + const descHeading = document.createDocumentFragment(); + descHeading.append("Folder Templates are triggered when a new ", descHeading.createEl("strong", { text: "empty " }), "file is created in a given folder.", descHeading.createEl("br"), "Templater will fill the empty file with the specified template.", descHeading.createEl("br"), "The deepest match is used. A global default template would be defined on the root ", descHeading.createEl("code", { text: "/" }), "."); + new import_obsidian6.Setting(this.containerEl).setDesc(descHeading); + const descUseNewFileTemplate = document.createDocumentFragment(); + descUseNewFileTemplate.append("When enabled Templater will make use of the folder templates defined below."); + new import_obsidian6.Setting(this.containerEl).setName("Enable folder templates").setDesc(descUseNewFileTemplate).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.enable_folder_templates).onChange((use_new_file_templates) => { + this.plugin.settings.enable_folder_templates = use_new_file_templates; + this.plugin.save_settings(); + this.display(); + }); + }); + if (!this.plugin.settings.enable_folder_templates) { + return; + } + new import_obsidian6.Setting(this.containerEl).setName("Add new").setDesc("Add new folder template").addButton((button) => { + button.setTooltip("Add additional folder template").setButtonText("+").setCta().onClick(() => { + this.plugin.settings.folder_templates.push({ + folder: "", + template: "" + }); + this.plugin.save_settings(); + this.display(); + }); + }); + this.plugin.settings.folder_templates.forEach((folder_template, index) => { + const s = new import_obsidian6.Setting(this.containerEl).addSearch((cb) => { + new FolderSuggest(cb.inputEl); + cb.setPlaceholder("Folder").setValue(folder_template.folder).onChange((new_folder) => { + if (new_folder && this.plugin.settings.folder_templates.some((e) => e.folder == new_folder)) { + log_error(new TemplaterError("This folder already has a template associated with it")); + return; + } + this.plugin.settings.folder_templates[index].folder = new_folder; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }).addSearch((cb) => { + new FileSuggest(cb.inputEl, this.plugin, FileSuggestMode.TemplateFiles); + cb.setPlaceholder("Template").setValue(folder_template.template).onChange((new_template) => { + this.plugin.settings.folder_templates[index].template = new_template; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }).addExtraButton((cb) => { + cb.setIcon("up-chevron-glyph").setTooltip("Move up").onClick(() => { + arraymove(this.plugin.settings.folder_templates, index, index - 1); + this.plugin.save_settings(); + this.display(); + }); + }).addExtraButton((cb) => { + cb.setIcon("down-chevron-glyph").setTooltip("Move down").onClick(() => { + arraymove(this.plugin.settings.folder_templates, index, index + 1); + this.plugin.save_settings(); + this.display(); + }); + }).addExtraButton((cb) => { + cb.setIcon("cross").setTooltip("Delete").onClick(() => { + this.plugin.settings.folder_templates.splice(index, 1); + this.plugin.save_settings(); + this.display(); + }); + }); + s.infoEl.remove(); + }); + } + add_startup_templates_setting() { + new import_obsidian6.Setting(this.containerEl).setName("Startup templates").setHeading(); + const desc = document.createDocumentFragment(); + desc.append("Startup templates are templates that will get executed once when Templater starts.", desc.createEl("br"), "These templates won't output anything.", desc.createEl("br"), "This can be useful to set up templates adding hooks to Obsidian events for example."); + new import_obsidian6.Setting(this.containerEl).setDesc(desc); + this.plugin.settings.startup_templates.forEach((template, index) => { + const s = new import_obsidian6.Setting(this.containerEl).addSearch((cb) => { + new FileSuggest(cb.inputEl, this.plugin, FileSuggestMode.TemplateFiles); + cb.setPlaceholder("Example: folder1/template_file").setValue(template).onChange((new_template) => { + if (new_template && this.plugin.settings.startup_templates.contains(new_template)) { + log_error(new TemplaterError("This startup template already exist")); + return; + } + this.plugin.settings.startup_templates[index] = new_template; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }).addExtraButton((cb) => { + cb.setIcon("cross").setTooltip("Delete").onClick(() => { + this.plugin.settings.startup_templates.splice(index, 1); + this.plugin.save_settings(); + this.display(); + }); + }); + s.infoEl.remove(); + }); + new import_obsidian6.Setting(this.containerEl).addButton((cb) => { + cb.setButtonText("Add new startup template").setCta().onClick(() => { + this.plugin.settings.startup_templates.push(""); + this.plugin.save_settings(); + this.display(); + }); + }); + } + add_user_script_functions_setting() { + new import_obsidian6.Setting(this.containerEl).setName("User script functions").setHeading(); + let desc = document.createDocumentFragment(); + desc.append("All JavaScript files in this folder will be loaded as CommonJS modules, to import custom user functions.", desc.createEl("br"), "The folder needs to be accessible from the vault.", desc.createEl("br"), "Check the ", desc.createEl("a", { + href: "https://silentvoid13.github.io/Templater/", + text: "documentation" + }), " for more information."); + new import_obsidian6.Setting(this.containerEl).setName("Script files folder location").setDesc(desc).addSearch((cb) => { + new FolderSuggest(cb.inputEl); + cb.setPlaceholder("Example: folder1/folder2").setValue(this.plugin.settings.user_scripts_folder).onChange((new_folder) => { + this.plugin.settings.user_scripts_folder = new_folder; + this.plugin.save_settings(); + }); + cb.containerEl.addClass("templater_search"); + }); + desc = document.createDocumentFragment(); + let name; + if (!this.plugin.settings.user_scripts_folder) { + name = "No user scripts folder set"; + } else { + const files = errorWrapperSync(() => get_tfiles_from_folder(this.plugin.settings.user_scripts_folder), `User scripts folder doesn't exist`); + if (!files || files.length === 0) { + name = "No user scripts detected"; + } else { + let count = 0; + for (const file of files) { + if (file.extension === "js") { + count++; + desc.append(desc.createEl("li", { + text: `tp.user.${file.basename}` + })); + } + } + name = `Detected ${count} User Script(s)`; + } + } + new import_obsidian6.Setting(this.containerEl).setName(name).setDesc(desc).addExtraButton((extra) => { + extra.setIcon("sync").setTooltip("Refresh").onClick(() => { + this.display(); + }); + }); + } + add_user_system_command_functions_setting() { + let desc = document.createDocumentFragment(); + desc.append("Allows you to create user functions linked to system commands.", desc.createEl("br"), desc.createEl("b", { + text: "Warning: " + }), "It can be dangerous to execute arbitrary system commands from untrusted sources. Only run system commands that you understand, from trusted sources."); + new import_obsidian6.Setting(this.containerEl).setName("User system command functions").setHeading(); + new import_obsidian6.Setting(this.containerEl).setName("Enable user system command functions").setDesc(desc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.enable_system_commands).onChange((enable_system_commands) => { + this.plugin.settings.enable_system_commands = enable_system_commands; + this.plugin.save_settings(); + this.display(); + }); + }); + if (this.plugin.settings.enable_system_commands) { + new import_obsidian6.Setting(this.containerEl).setName("Timeout").setDesc("Maximum timeout in seconds for a system command.").addText((text) => { + text.setPlaceholder("Timeout").setValue(this.plugin.settings.command_timeout.toString()).onChange((new_value) => { + const new_timeout = Number(new_value); + if (isNaN(new_timeout)) { + log_error(new TemplaterError("Timeout must be a number")); + return; + } + this.plugin.settings.command_timeout = new_timeout; + this.plugin.save_settings(); + }); + }); + desc = document.createDocumentFragment(); + desc.append("Full path to the shell binary to execute the command with.", desc.createEl("br"), "This setting is optional and will default to the system's default shell if not specified.", desc.createEl("br"), "You can use forward slashes ('/') as path separators on all platforms if in doubt."); + new import_obsidian6.Setting(this.containerEl).setName("Shell binary location").setDesc(desc).addText((text) => { + text.setPlaceholder("Example: /bin/bash, ...").setValue(this.plugin.settings.shell_path).onChange((shell_path) => { + this.plugin.settings.shell_path = shell_path; + this.plugin.save_settings(); + }); + }); + let i = 1; + this.plugin.settings.templates_pairs.forEach((template_pair) => { + const div2 = this.containerEl.createEl("div"); + div2.addClass("templater_div"); + const title = this.containerEl.createEl("h4", { + text: "User function n\xB0" + i + }); + title.addClass("templater_title"); + const setting2 = new import_obsidian6.Setting(this.containerEl).addExtraButton((extra) => { + extra.setIcon("cross").setTooltip("Delete").onClick(() => { + const index = this.plugin.settings.templates_pairs.indexOf(template_pair); + if (index > -1) { + this.plugin.settings.templates_pairs.splice(index, 1); + this.plugin.save_settings(); + this.display(); + } + }); + }).addText((text) => { + const t = text.setPlaceholder("Function name").setValue(template_pair[0]).onChange((new_value) => { + const index = this.plugin.settings.templates_pairs.indexOf(template_pair); + if (index > -1) { + this.plugin.settings.templates_pairs[index][0] = new_value; + this.plugin.save_settings(); + } + }); + t.inputEl.addClass("templater_template"); + return t; + }).addTextArea((text) => { + const t = text.setPlaceholder("System command").setValue(template_pair[1]).onChange((new_cmd) => { + const index = this.plugin.settings.templates_pairs.indexOf(template_pair); + if (index > -1) { + this.plugin.settings.templates_pairs[index][1] = new_cmd; + this.plugin.save_settings(); + } + }); + t.inputEl.setAttr("rows", 2); + t.inputEl.addClass("templater_cmd"); + return t; + }); + setting2.infoEl.remove(); + div2.appendChild(title); + div2.appendChild(this.containerEl.lastChild); + i += 1; + }); + const div = this.containerEl.createEl("div"); + div.addClass("templater_div2"); + const setting = new import_obsidian6.Setting(this.containerEl).addButton((button) => { + button.setButtonText("Add new user function").setCta().onClick(() => { + this.plugin.settings.templates_pairs.push(["", ""]); + this.plugin.save_settings(); + this.display(); + }); + }); + setting.infoEl.remove(); + div.appendChild(this.containerEl.lastChild); + } + } + add_donating_setting() { + const s = new import_obsidian6.Setting(this.containerEl).setName("Donate").setDesc("If you like this Plugin, consider donating to support continued development."); + const a1 = document.createElement("a"); + a1.setAttribute("href", "https://github.com/sponsors/silentvoid13"); + a1.addClass("templater_donating"); + const img1 = document.createElement("img"); + img1.src = "https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86"; + a1.appendChild(img1); + const a2 = document.createElement("a"); + a2.setAttribute("href", "https://www.paypal.com/donate?hosted_button_id=U2SRGAFYXT32Q"); + a2.addClass("templater_donating"); + const img2 = document.createElement("img"); + img2.src = "https://img.shields.io/badge/paypal-silentvoid13-yellow?style=social&logo=paypal"; + a2.appendChild(img2); + s.settingEl.appendChild(a1); + s.settingEl.appendChild(a2); + } +}; + +// src/handlers/FuzzySuggester.ts +var import_obsidian7 = __toModule(require("obsidian")); +var OpenMode; +(function(OpenMode2) { + OpenMode2[OpenMode2["InsertTemplate"] = 0] = "InsertTemplate"; + OpenMode2[OpenMode2["CreateNoteTemplate"] = 1] = "CreateNoteTemplate"; +})(OpenMode || (OpenMode = {})); +var FuzzySuggester = class extends import_obsidian7.FuzzySuggestModal { + constructor(plugin) { + super(app); + this.plugin = plugin; + this.setPlaceholder("Type name of a template..."); + } + getItems() { + if (!this.plugin.settings.templates_folder) { + return app.vault.getMarkdownFiles(); + } + const files = errorWrapperSync(() => get_tfiles_from_folder(this.plugin.settings.templates_folder), `Couldn't retrieve template files from templates folder ${this.plugin.settings.templates_folder}`); + if (!files) { + return []; + } + return files; + } + getItemText(item) { + let relativePath = item.path; + if (item.path.startsWith(this.plugin.settings.templates_folder)) { + relativePath = item.path.slice(this.plugin.settings.templates_folder.length + 1); + } + return relativePath.split(".").slice(0, -1).join("."); + } + onChooseItem(item) { + switch (this.open_mode) { + case 0: + this.plugin.templater.append_template_to_active_file(item); + break; + case 1: + this.plugin.templater.create_new_note_from_template(item, this.creation_folder); + break; + } + } + start() { + try { + this.open(); + } catch (e) { + log_error(e); + } + } + insert_template() { + this.open_mode = 0; + this.start(); + } + create_new_note_from_template(folder) { + this.creation_folder = folder; + this.open_mode = 1; + this.start(); + } +}; + +// src/utils/Constants.ts +var UNSUPPORTED_MOBILE_TEMPLATE = "Error_MobileUnsupportedTemplate"; +var ICON_DATA = ``; + +// src/core/Templater.ts +var import_obsidian12 = __toModule(require("obsidian")); + +// src/core/functions/internal_functions/InternalModule.ts +var InternalModule = class { + constructor(plugin) { + this.plugin = plugin; + this.static_functions = new Map(); + this.dynamic_functions = new Map(); + } + getName() { + return this.name; + } + async init() { + await this.create_static_templates(); + this.static_object = Object.fromEntries(this.static_functions); + } + async generate_object(new_config) { + this.config = new_config; + await this.create_dynamic_templates(); + return { + ...this.static_object, + ...Object.fromEntries(this.dynamic_functions) + }; + } +}; + +// src/core/functions/internal_functions/date/InternalModuleDate.ts +var InternalModuleDate = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "date"; + } + async create_static_templates() { + this.static_functions.set("now", this.generate_now()); + this.static_functions.set("tomorrow", this.generate_tomorrow()); + this.static_functions.set("weekday", this.generate_weekday()); + this.static_functions.set("yesterday", this.generate_yesterday()); + } + async create_dynamic_templates() { + } + async teardown() { + } + generate_now() { + return (format = "YYYY-MM-DD", offset2, reference2, reference_format) => { + if (reference2 && !window.moment(reference2, reference_format).isValid()) { + throw new TemplaterError("Invalid reference date format, try specifying one with the argument 'reference_format'"); + } + let duration; + if (typeof offset2 === "string") { + duration = window.moment.duration(offset2); + } else if (typeof offset2 === "number") { + duration = window.moment.duration(offset2, "days"); + } + return window.moment(reference2, reference_format).add(duration).format(format); + }; + } + generate_tomorrow() { + return (format = "YYYY-MM-DD") => { + return window.moment().add(1, "days").format(format); + }; + } + generate_weekday() { + return (format = "YYYY-MM-DD", weekday, reference2, reference_format) => { + if (reference2 && !window.moment(reference2, reference_format).isValid()) { + throw new TemplaterError("Invalid reference date format, try specifying one with the argument 'reference_format'"); + } + return window.moment(reference2, reference_format).weekday(weekday).format(format); + }; + } + generate_yesterday() { + return (format = "YYYY-MM-DD") => { + return window.moment().add(-1, "days").format(format); + }; + } +}; + +// src/core/functions/internal_functions/file/InternalModuleFile.ts +var import_obsidian8 = __toModule(require("obsidian")); +var DEPTH_LIMIT = 10; +var InternalModuleFile = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "file"; + this.include_depth = 0; + this.create_new_depth = 0; + this.linkpath_regex = new RegExp("^\\[\\[(.*)\\]\\]$"); + } + async create_static_templates() { + this.static_functions.set("creation_date", this.generate_creation_date()); + this.static_functions.set("create_new", this.generate_create_new()); + this.static_functions.set("cursor", this.generate_cursor()); + this.static_functions.set("cursor_append", this.generate_cursor_append()); + this.static_functions.set("exists", this.generate_exists()); + this.static_functions.set("find_tfile", this.generate_find_tfile()); + this.static_functions.set("folder", this.generate_folder()); + this.static_functions.set("include", this.generate_include()); + this.static_functions.set("last_modified_date", this.generate_last_modified_date()); + this.static_functions.set("move", this.generate_move()); + this.static_functions.set("path", this.generate_path()); + this.static_functions.set("rename", this.generate_rename()); + this.static_functions.set("selection", this.generate_selection()); + } + async create_dynamic_templates() { + this.dynamic_functions.set("content", await this.generate_content()); + this.dynamic_functions.set("tags", this.generate_tags()); + this.dynamic_functions.set("title", this.generate_title()); + } + async teardown() { + } + async generate_content() { + return await app.vault.read(this.config.target_file); + } + generate_create_new() { + return async (template, filename, open_new = false, folder) => { + this.create_new_depth += 1; + if (this.create_new_depth > DEPTH_LIMIT) { + this.create_new_depth = 0; + throw new TemplaterError("Reached create_new depth limit (max = 10)"); + } + const new_file = await this.plugin.templater.create_new_note_from_template(template, folder, filename, open_new); + this.create_new_depth -= 1; + return new_file; + }; + } + generate_creation_date() { + return (format = "YYYY-MM-DD HH:mm") => { + return window.moment(this.config.target_file.stat.ctime).format(format); + }; + } + generate_cursor() { + return (order2) => { + return `<% tp.file.cursor(${order2 ?? ""}) %>`; + }; + } + generate_cursor_append() { + return (content) => { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.editor) { + log_error(new TemplaterError("No active editor, can't append to cursor.")); + return; + } + const editor = active_editor.editor; + const doc = editor.getDoc(); + doc.replaceSelection(content); + return ""; + }; + } + generate_exists() { + return async (filepath) => { + const path = (0, import_obsidian8.normalizePath)(filepath); + return await app.vault.exists(path); + }; + } + generate_find_tfile() { + return (filename) => { + const path = (0, import_obsidian8.normalizePath)(filename); + return app.metadataCache.getFirstLinkpathDest(path, ""); + }; + } + generate_folder() { + return (relative = false) => { + const parent = this.config.target_file.parent; + let folder; + if (relative) { + folder = parent.path; + } else { + folder = parent.name; + } + return folder; + }; + } + generate_include() { + return async (include_link) => { + this.include_depth += 1; + if (this.include_depth > DEPTH_LIMIT) { + this.include_depth -= 1; + throw new TemplaterError("Reached inclusion depth limit (max = 10)"); + } + let inc_file_content; + if (include_link instanceof import_obsidian8.TFile) { + inc_file_content = await app.vault.read(include_link); + } else { + let match; + if ((match = this.linkpath_regex.exec(include_link)) === null) { + this.include_depth -= 1; + throw new TemplaterError("Invalid file format, provide an obsidian link between quotes."); + } + const { path, subpath } = (0, import_obsidian8.parseLinktext)(match[1]); + const inc_file = app.metadataCache.getFirstLinkpathDest(path, ""); + if (!inc_file) { + this.include_depth -= 1; + throw new TemplaterError(`File ${include_link} doesn't exist`); + } + inc_file_content = await app.vault.read(inc_file); + if (subpath) { + const cache = app.metadataCache.getFileCache(inc_file); + if (cache) { + const result = (0, import_obsidian8.resolveSubpath)(cache, subpath); + if (result) { + inc_file_content = inc_file_content.slice(result.start.offset, result.end?.offset); + } + } + } + } + try { + const parsed_content = await this.plugin.templater.parser.parse_commands(inc_file_content, this.plugin.templater.current_functions_object); + this.include_depth -= 1; + return parsed_content; + } catch (e) { + this.include_depth -= 1; + throw e; + } + }; + } + generate_last_modified_date() { + return (format = "YYYY-MM-DD HH:mm") => { + return window.moment(this.config.target_file.stat.mtime).format(format); + }; + } + generate_move() { + return async (path, file_to_move) => { + const file = file_to_move || this.config.target_file; + const new_path = (0, import_obsidian8.normalizePath)(`${path}.${file.extension}`); + const dirs = new_path.replace(/\\/g, "/").split("/"); + dirs.pop(); + if (dirs.length) { + const dir = dirs.join("/"); + if (!window.app.vault.getAbstractFileByPath(dir)) { + await window.app.vault.createFolder(dir); + } + } + await app.fileManager.renameFile(file, new_path); + return ""; + }; + } + generate_path() { + return (relative = false) => { + let vault_path = ""; + if (import_obsidian8.Platform.isMobileApp) { + const vault_adapter = app.vault.adapter.fs.uri; + const vault_base = app.vault.adapter.basePath; + vault_path = `${vault_adapter}/${vault_base}`; + } else { + if (app.vault.adapter instanceof import_obsidian8.FileSystemAdapter) { + vault_path = app.vault.adapter.getBasePath(); + } else { + throw new TemplaterError("app.vault is not a FileSystemAdapter instance"); + } + } + if (relative) { + return this.config.target_file.path; + } else { + return `${vault_path}/${this.config.target_file.path}`; + } + }; + } + generate_rename() { + return async (new_title) => { + if (new_title.match(/[\\/:]+/g)) { + throw new TemplaterError("File name cannot contain any of these characters: \\ / :"); + } + const new_path = (0, import_obsidian8.normalizePath)(`${this.config.target_file.parent.path}/${new_title}.${this.config.target_file.extension}`); + await app.fileManager.renameFile(this.config.target_file, new_path); + return ""; + }; + } + generate_selection() { + return () => { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.editor) { + throw new TemplaterError("Active editor is null, can't read selection."); + } + const editor = active_editor.editor; + return editor.getSelection(); + }; + } + generate_tags() { + const cache = app.metadataCache.getFileCache(this.config.target_file); + if (cache) { + return (0, import_obsidian8.getAllTags)(cache); + } + return null; + } + generate_title() { + return this.config.target_file.basename; + } +}; + +// src/core/functions/internal_functions/web/InternalModuleWeb.ts +var InternalModuleWeb = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "web"; + } + async create_static_templates() { + this.static_functions.set("daily_quote", this.generate_daily_quote()); + this.static_functions.set("random_picture", this.generate_random_picture()); + } + async create_dynamic_templates() { + } + async teardown() { + } + async getRequest(url) { + try { + const response = await fetch(url); + if (!response.ok) { + throw new TemplaterError("Error performing GET request"); + } + return response; + } catch (error) { + throw new TemplaterError("Error performing GET request"); + } + } + generate_daily_quote() { + return async () => { + try { + const response = await this.getRequest("https://api.quotable.io/random"); + const json = await response.json(); + const author = json.author; + const quote = json.content; + const new_content = `> [!quote] ${quote} +> \u2014 ${author}`; + return new_content; + } catch (error) { + new TemplaterError("Error generating daily quote"); + return "Error generating daily quote"; + } + }; + } + generate_random_picture() { + return async (size, query, include_size = false) => { + try { + const response = await this.getRequest(`https://templater-unsplash.fly.dev/${query ? "?q=" + query : ""}`).then((res) => res.json()); + let url = response.full; + if (size && !include_size) { + if (size.includes("x")) { + const [width, height] = size.split("x"); + url = url.concat(`&w=${width}&h=${height}`); + } else { + url = url.concat(`&w=${size}`); + } + } + if (include_size) { + return `![photo by ${response.photog} on Unsplash|${size}](${url})`; + } + return `![photo by ${response.photog} on Unsplash](${url})`; + } catch (error) { + new TemplaterError("Error generating random picture"); + return "Error generating random picture"; + } + }; + } +}; + +// src/core/functions/internal_functions/hooks/InternalModuleHooks.ts +var InternalModuleHooks = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "hooks"; + this.event_refs = []; + } + async create_static_templates() { + this.static_functions.set("on_all_templates_executed", this.generate_on_all_templates_executed()); + } + async create_dynamic_templates() { + } + async teardown() { + this.event_refs.forEach((eventRef) => { + eventRef.e.offref(eventRef); + }); + this.event_refs = []; + } + generate_on_all_templates_executed() { + return (callback_function) => { + const event_ref = app.workspace.on("templater:all-templates-executed", async () => { + await delay(1); + callback_function(); + }); + if (event_ref) { + this.event_refs.push(event_ref); + } + }; + } +}; + +// src/core/functions/internal_functions/frontmatter/InternalModuleFrontmatter.ts +var InternalModuleFrontmatter = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "frontmatter"; + } + async create_static_templates() { + } + async create_dynamic_templates() { + const cache = app.metadataCache.getFileCache(this.config.target_file); + this.dynamic_functions = new Map(Object.entries(cache?.frontmatter || {})); + } + async teardown() { + } +}; + +// src/core/functions/internal_functions/system/PromptModal.ts +var import_obsidian9 = __toModule(require("obsidian")); +var PromptModal = class extends import_obsidian9.Modal { + constructor(prompt_text, default_value, multi_line) { + super(app); + this.prompt_text = prompt_text; + this.default_value = default_value; + this.multi_line = multi_line; + this.submitted = false; + } + onOpen() { + this.titleEl.setText(this.prompt_text); + this.createForm(); + } + onClose() { + this.contentEl.empty(); + if (!this.submitted) { + this.reject(new TemplaterError("Cancelled prompt")); + } + } + createForm() { + const div = this.contentEl.createDiv(); + div.addClass("templater-prompt-div"); + let textInput; + if (this.multi_line) { + textInput = new import_obsidian9.TextAreaComponent(div); + const buttonDiv = this.contentEl.createDiv(); + buttonDiv.addClass("templater-button-div"); + const submitButton = new import_obsidian9.ButtonComponent(buttonDiv); + submitButton.buttonEl.addClass("mod-cta"); + submitButton.setButtonText("Submit").onClick((evt) => { + this.resolveAndClose(evt); + }); + } else { + textInput = new import_obsidian9.TextComponent(div); + } + this.value = this.default_value ?? ""; + textInput.inputEl.addClass("templater-prompt-input"); + textInput.setPlaceholder("Type text here"); + textInput.setValue(this.value); + textInput.onChange((value) => this.value = value); + textInput.inputEl.addEventListener("keydown", (evt) => this.enterCallback(evt)); + } + enterCallback(evt) { + if (evt.isComposing || evt.keyCode === 229) + return; + if (this.multi_line) { + if (import_obsidian9.Platform.isDesktop && evt.key === "Enter" && !evt.shiftKey) { + this.resolveAndClose(evt); + } + } else { + if (evt.key === "Enter") { + this.resolveAndClose(evt); + } + } + } + resolveAndClose(evt) { + this.submitted = true; + evt.preventDefault(); + this.resolve(this.value); + this.close(); + } + async openAndGetValue(resolve, reject) { + this.resolve = resolve; + this.reject = reject; + this.open(); + } +}; + +// src/core/functions/internal_functions/system/SuggesterModal.ts +var import_obsidian10 = __toModule(require("obsidian")); +var SuggesterModal = class extends import_obsidian10.FuzzySuggestModal { + constructor(text_items, items, placeholder, limit) { + super(app); + this.text_items = text_items; + this.items = items; + this.submitted = false; + this.setPlaceholder(placeholder); + limit && (this.limit = limit); + } + getItems() { + return this.items; + } + onClose() { + if (!this.submitted) { + this.reject(new TemplaterError("Cancelled prompt")); + } + } + selectSuggestion(value, evt) { + this.submitted = true; + this.close(); + this.onChooseSuggestion(value, evt); + } + getItemText(item) { + if (this.text_items instanceof Function) { + return this.text_items(item); + } + return this.text_items[this.items.indexOf(item)] || "Undefined Text Item"; + } + onChooseItem(item) { + this.resolve(item); + } + async openAndGetValue(resolve, reject) { + this.resolve = resolve; + this.reject = reject; + this.open(); + } +}; + +// src/core/functions/internal_functions/system/InternalModuleSystem.ts +var InternalModuleSystem = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "system"; + } + async create_static_templates() { + this.static_functions.set("clipboard", this.generate_clipboard()); + this.static_functions.set("prompt", this.generate_prompt()); + this.static_functions.set("suggester", this.generate_suggester()); + } + async create_dynamic_templates() { + } + async teardown() { + } + generate_clipboard() { + return async () => { + return await navigator.clipboard.readText(); + }; + } + generate_prompt() { + return async (prompt_text, default_value, throw_on_cancel = false, multi_line = false) => { + const prompt = new PromptModal(prompt_text, default_value, multi_line); + const promise = new Promise((resolve, reject) => prompt.openAndGetValue(resolve, reject)); + try { + return await promise; + } catch (error) { + if (throw_on_cancel) { + throw error; + } + return null; + } + }; + } + generate_suggester() { + return async (text_items, items, throw_on_cancel = false, placeholder = "", limit) => { + const suggester = new SuggesterModal(text_items, items, placeholder, limit); + const promise = new Promise((resolve, reject) => suggester.openAndGetValue(resolve, reject)); + try { + return await promise; + } catch (error) { + if (throw_on_cancel) { + throw error; + } + return null; + } + }; + } +}; + +// src/core/functions/internal_functions/config/InternalModuleConfig.ts +var InternalModuleConfig = class extends InternalModule { + constructor() { + super(...arguments); + this.name = "config"; + } + async create_static_templates() { + } + async create_dynamic_templates() { + } + async teardown() { + } + async generate_object(config) { + return config; + } +}; + +// src/core/functions/internal_functions/InternalFunctions.ts +var InternalFunctions = class { + constructor(plugin) { + this.plugin = plugin; + this.modules_array = []; + this.modules_array.push(new InternalModuleDate(this.plugin)); + this.modules_array.push(new InternalModuleFile(this.plugin)); + this.modules_array.push(new InternalModuleWeb(this.plugin)); + this.modules_array.push(new InternalModuleFrontmatter(this.plugin)); + this.modules_array.push(new InternalModuleHooks(this.plugin)); + this.modules_array.push(new InternalModuleSystem(this.plugin)); + this.modules_array.push(new InternalModuleConfig(this.plugin)); + } + async init() { + for (const mod of this.modules_array) { + await mod.init(); + } + } + async teardown() { + for (const mod of this.modules_array) { + await mod.teardown(); + } + } + async generate_object(config) { + const internal_functions_object = {}; + for (const mod of this.modules_array) { + internal_functions_object[mod.getName()] = await mod.generate_object(config); + } + return internal_functions_object; + } +}; + +// src/core/functions/user_functions/UserSystemFunctions.ts +var import_child_process = __toModule(require("child_process")); +var import_util = __toModule(require("util")); +var import_obsidian11 = __toModule(require("obsidian")); +var UserSystemFunctions = class { + constructor(plugin) { + this.plugin = plugin; + if (import_obsidian11.Platform.isMobileApp || !(app.vault.adapter instanceof import_obsidian11.FileSystemAdapter)) { + this.cwd = ""; + } else { + this.cwd = app.vault.adapter.getBasePath(); + this.exec_promise = (0, import_util.promisify)(import_child_process.exec); + } + } + async generate_system_functions(config) { + const user_system_functions = new Map(); + const internal_functions_object = await this.plugin.templater.functions_generator.generate_object(config, FunctionsMode.INTERNAL); + for (const template_pair of this.plugin.settings.templates_pairs) { + const template = template_pair[0]; + let cmd = template_pair[1]; + if (!template || !cmd) { + continue; + } + if (import_obsidian11.Platform.isMobileApp) { + user_system_functions.set(template, () => { + return new Promise((resolve) => resolve(UNSUPPORTED_MOBILE_TEMPLATE)); + }); + } else { + cmd = await this.plugin.templater.parser.parse_commands(cmd, internal_functions_object); + user_system_functions.set(template, async (user_args) => { + const process_env = { + ...process.env, + ...user_args + }; + const cmd_options = { + timeout: this.plugin.settings.command_timeout * 1e3, + cwd: this.cwd, + env: process_env, + ...this.plugin.settings.shell_path && { + shell: this.plugin.settings.shell_path + } + }; + try { + const { stdout } = await this.exec_promise(cmd, cmd_options); + return stdout.trimRight(); + } catch (error) { + throw new TemplaterError(`Error with User Template ${template}`, error); + } + }); + } + } + return user_system_functions; + } + async generate_object(config) { + const user_system_functions = await this.generate_system_functions(config); + return Object.fromEntries(user_system_functions); + } +}; + +// src/core/functions/user_functions/UserScriptFunctions.ts +var UserScriptFunctions = class { + constructor(plugin) { + this.plugin = plugin; + } + async generate_user_script_functions() { + const user_script_functions = new Map(); + const files = errorWrapperSync(() => get_tfiles_from_folder(this.plugin.settings.user_scripts_folder), `Couldn't find user script folder "${this.plugin.settings.user_scripts_folder}"`); + if (!files) { + return new Map(); + } + for (const file of files) { + if (file.extension.toLowerCase() === "js") { + await this.load_user_script_function(file, user_script_functions); + } + } + return user_script_functions; + } + async load_user_script_function(file, user_script_functions) { + const req = (s) => { + return window.require && window.require(s); + }; + const exp = {}; + const mod = { + exports: exp + }; + const file_content = await app.vault.read(file); + try { + const wrapping_fn = window.eval("(function anonymous(require, module, exports){" + file_content + "\n})"); + wrapping_fn(req, mod, exp); + } catch (err) { + throw new TemplaterError(`Failed to load user script at "${file.path}".`, err.message); + } + const user_function = exp["default"] || mod.exports; + if (!user_function) { + throw new TemplaterError(`Failed to load user script at "${file.path}". No exports detected.`); + } + if (!(user_function instanceof Function)) { + throw new TemplaterError(`Failed to load user script at "${file.path}". Default export is not a function.`); + } + user_script_functions.set(`${file.basename}`, user_function); + } + async generate_object() { + const user_script_functions = await this.generate_user_script_functions(); + return Object.fromEntries(user_script_functions); + } +}; + +// src/core/functions/user_functions/UserFunctions.ts +var UserFunctions = class { + constructor(plugin) { + this.plugin = plugin; + this.user_system_functions = new UserSystemFunctions(plugin); + this.user_script_functions = new UserScriptFunctions(plugin); + } + async generate_object(config) { + let user_system_functions = {}; + let user_script_functions = {}; + if (this.plugin.settings.enable_system_commands) { + user_system_functions = await this.user_system_functions.generate_object(config); + } + if (this.plugin.settings.user_scripts_folder) { + user_script_functions = await this.user_script_functions.generate_object(); + } + return { + ...user_system_functions, + ...user_script_functions + }; + } +}; + +// src/core/functions/FunctionsGenerator.ts +var obsidian_module = __toModule(require("obsidian")); +var FunctionsMode; +(function(FunctionsMode2) { + FunctionsMode2[FunctionsMode2["INTERNAL"] = 0] = "INTERNAL"; + FunctionsMode2[FunctionsMode2["USER_INTERNAL"] = 1] = "USER_INTERNAL"; +})(FunctionsMode || (FunctionsMode = {})); +var FunctionsGenerator = class { + constructor(plugin) { + this.plugin = plugin; + this.internal_functions = new InternalFunctions(this.plugin); + this.user_functions = new UserFunctions(this.plugin); + } + async init() { + await this.internal_functions.init(); + } + async teardown() { + await this.internal_functions.teardown(); + } + additional_functions() { + return { + obsidian: obsidian_module + }; + } + async generate_object(config, functions_mode = 1) { + const final_object = {}; + const additional_functions_object = this.additional_functions(); + const internal_functions_object = await this.internal_functions.generate_object(config); + let user_functions_object = {}; + Object.assign(final_object, additional_functions_object); + switch (functions_mode) { + case 0: + Object.assign(final_object, internal_functions_object); + break; + case 1: + user_functions_object = await this.user_functions.generate_object(config); + Object.assign(final_object, { + ...internal_functions_object, + user: user_functions_object + }); + break; + } + return final_object; + } +}; + +// node_modules/@silentvoid13/rusty_engine/rusty_engine.js +var import_meta = {}; +var wasm; +var heap = new Array(32).fill(void 0); +heap.push(void 0, null, true, false); +function getObject(idx) { + return heap[idx]; +} +var heap_next = heap.length; +function dropObject(idx) { + if (idx < 36) + return; + heap[idx] = heap_next; + heap_next = idx; +} +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} +var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }); +cachedTextDecoder.decode(); +var cachedUint8Memory0 = new Uint8Array(); +function getUint8Memory0() { + if (cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; +} +function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} +function addHeapObject(obj) { + if (heap_next === heap.length) + heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + heap[idx] = obj; + return idx; +} +var WASM_VECTOR_LEN = 0; +var cachedTextEncoder = new TextEncoder("utf-8"); +var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} : function(arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}; +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === void 0) { + const buf = cachedTextEncoder.encode(arg); + const ptr2 = malloc(buf.length); + getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr2; + } + let len = arg.length; + let ptr = malloc(len); + const mem = getUint8Memory0(); + let offset2 = 0; + for (; offset2 < len; offset2++) { + const code = arg.charCodeAt(offset2); + if (code > 127) + break; + mem[ptr + offset2] = code; + } + if (offset2 !== len) { + if (offset2 !== 0) { + arg = arg.slice(offset2); + } + ptr = realloc(ptr, len, len = offset2 + arg.length * 3); + const view = getUint8Memory0().subarray(ptr + offset2, ptr + len); + const ret = encodeString(arg, view); + offset2 += ret.written; + } + WASM_VECTOR_LEN = offset2; + return ptr; +} +function isLikeNone(x) { + return x === void 0 || x === null; +} +var cachedInt32Memory0 = new Int32Array(); +function getInt32Memory0() { + if (cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachedInt32Memory0; +} +function debugString(val) { + const type = typeof val; + if (type == "number" || type == "boolean" || val == null) { + return `${val}`; + } + if (type == "string") { + return `"${val}"`; + } + if (type == "symbol") { + const description = val.description; + if (description == null) { + return "Symbol"; + } else { + return `Symbol(${description})`; + } + } + if (type == "function") { + const name = val.name; + if (typeof name == "string" && name.length > 0) { + return `Function(${name})`; + } else { + return "Function"; + } + } + if (Array.isArray(val)) { + const length = val.length; + let debug = "["; + if (length > 0) { + debug += debugString(val[0]); + } + for (let i = 1; i < length; i++) { + debug += ", " + debugString(val[i]); + } + debug += "]"; + return debug; + } + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + return toString.call(val); + } + if (className == "Object") { + try { + return "Object(" + JSON.stringify(val) + ")"; + } catch (_) { + return "Object"; + } + } + if (val instanceof Error) { + return `${val.name}: ${val.message} +${val.stack}`; + } + return className; +} +function _assertClass(instance, klass) { + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } + return instance.ptr; +} +var stack_pointer = 32; +function addBorrowedObject(obj) { + if (stack_pointer == 1) + throw new Error("out of js stack"); + heap[--stack_pointer] = obj; + return stack_pointer; +} +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + wasm.__wbindgen_exn_store(addHeapObject(e)); + } +} +var ParserConfig = class { + static __wrap(ptr) { + const obj = Object.create(ParserConfig.prototype); + obj.ptr = ptr; + return obj; + } + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_parserconfig_free(ptr); + } + get interpolate() { + const ret = wasm.__wbg_get_parserconfig_interpolate(this.ptr); + return String.fromCodePoint(ret); + } + set interpolate(arg0) { + wasm.__wbg_set_parserconfig_interpolate(this.ptr, arg0.codePointAt(0)); + } + get execution() { + const ret = wasm.__wbg_get_parserconfig_execution(this.ptr); + return String.fromCodePoint(ret); + } + set execution(arg0) { + wasm.__wbg_set_parserconfig_execution(this.ptr, arg0.codePointAt(0)); + } + get single_whitespace() { + const ret = wasm.__wbg_get_parserconfig_single_whitespace(this.ptr); + return String.fromCodePoint(ret); + } + set single_whitespace(arg0) { + wasm.__wbg_set_parserconfig_single_whitespace(this.ptr, arg0.codePointAt(0)); + } + get multiple_whitespace() { + const ret = wasm.__wbg_get_parserconfig_multiple_whitespace(this.ptr); + return String.fromCodePoint(ret); + } + set multiple_whitespace(arg0) { + wasm.__wbg_set_parserconfig_multiple_whitespace(this.ptr, arg0.codePointAt(0)); + } + constructor(opt, clt, inte, ex, sw, mw, gv) { + const ptr0 = passStringToWasm0(opt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passStringToWasm0(clt, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + const ptr2 = passStringToWasm0(gv, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len2 = WASM_VECTOR_LEN; + const ret = wasm.parserconfig_new(ptr0, len0, ptr1, len1, inte.codePointAt(0), ex.codePointAt(0), sw.codePointAt(0), mw.codePointAt(0), ptr2, len2); + return ParserConfig.__wrap(ret); + } + get opening_tag() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parserconfig_opening_tag(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + set opening_tag(val) { + const ptr0 = passStringToWasm0(val, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.parserconfig_set_opening_tag(this.ptr, ptr0, len0); + } + get closing_tag() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parserconfig_closing_tag(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + set closing_tag(val) { + const ptr0 = passStringToWasm0(val, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.parserconfig_set_closing_tag(this.ptr, ptr0, len0); + } + get global_var() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.parserconfig_global_var(retptr, this.ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(r0, r1); + } + } + set global_var(val) { + const ptr0 = passStringToWasm0(val, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.parserconfig_set_global_var(this.ptr, ptr0, len0); + } +}; +var Renderer = class { + static __wrap(ptr) { + const obj = Object.create(Renderer.prototype); + obj.ptr = ptr; + return obj; + } + __destroy_into_raw() { + const ptr = this.ptr; + this.ptr = 0; + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_renderer_free(ptr); + } + constructor(config) { + _assertClass(config, ParserConfig); + var ptr0 = config.ptr; + config.ptr = 0; + const ret = wasm.renderer_new(ptr0); + return Renderer.__wrap(ret); + } + render_content(content, context) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passStringToWasm0(content, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.renderer_render_content(retptr, this.ptr, ptr0, len0, addBorrowedObject(context)); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + heap[stack_pointer++] = void 0; + } + } +}; +async function load(module2, imports) { + if (typeof Response === "function" && module2 instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === "function") { + try { + return await WebAssembly.instantiateStreaming(module2, imports); + } catch (e) { + if (module2.headers.get("Content-Type") != "application/wasm") { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + } else { + throw e; + } + } + } + const bytes = await module2.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + } else { + const instance = await WebAssembly.instantiate(module2, imports); + if (instance instanceof WebAssembly.Instance) { + return { instance, module: module2 }; + } else { + return instance; + } + } +} +function getImports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_string_get = function(arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === "string" ? obj : void 0; + var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }; + imports.wbg.__wbg_call_97ae9d8645dc388b = function() { + return handleError(function(arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); + }, arguments); + }; + imports.wbg.__wbg_new_8d2af00bc1e329ee = function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }; + imports.wbg.__wbg_message_fe2af63ccc8985bc = function(arg0) { + const ret = getObject(arg0).message; + return addHeapObject(ret); + }; + imports.wbg.__wbg_newwithargs_8fe23e3842840c8e = function(arg0, arg1, arg2, arg3) { + const ret = new Function(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3)); + return addHeapObject(ret); + }; + imports.wbg.__wbg_call_168da88779e35f61 = function() { + return handleError(function(arg0, arg1, arg2) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); + }, arguments); + }; + imports.wbg.__wbg_call_3999bee59e9f7719 = function() { + return handleError(function(arg0, arg1, arg2, arg3) { + const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3)); + return addHeapObject(ret); + }, arguments); + }; + imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { + const ret = debugString(getObject(arg1)); + const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + return imports; +} +function initMemory(imports, maybe_memory) { +} +function finalizeInit(instance, module2) { + wasm = instance.exports; + init.__wbindgen_wasm_module = module2; + cachedInt32Memory0 = new Int32Array(); + cachedUint8Memory0 = new Uint8Array(); + return wasm; +} +async function init(input) { + if (typeof input === "undefined") { + input = new URL("rusty_engine_bg.wasm", import_meta.url); + } + const imports = getImports(); + if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) { + input = fetch(input); + } + initMemory(imports); + const { instance, module: module2 } = await load(await input, imports); + return finalizeInit(instance, module2); +} +var rusty_engine_default = init; + +// wasm-embed:/home/runner/work/Templater/Templater/node_modules/@silentvoid13/rusty_engine/rusty_engine_bg.wasm +var rusty_engine_bg_default = __toBinary("AGFzbQEAAAABvwEaYAJ/fwBgAn9/AX9gAX8Bf2ADf39/AX9gA39/fwBgAX8AYAV/f39/fwBgBH9/f38AYAR/f39/AX9gAABgBX9/f39/AX9gAX8BfmAAAX9gBn9/f39/fwBgB39/f39/f38AYAV/f35/fwBgBX9/fX9/AGAFf398f38AYAR/fn9/AGAFf35/f38AYAR/fX9/AGAEf3x/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gCn9/f39/f39/f38Bf2ACfn8BfwLkAgsDd2JnGl9fd2JpbmRnZW5fb2JqZWN0X2Ryb3BfcmVmAAUDd2JnFV9fd2JpbmRnZW5fc3RyaW5nX25ldwABA3diZxVfX3diaW5kZ2VuX3N0cmluZ19nZXQAAAN3YmcbX193YmdfY2FsbF85N2FlOWQ4NjQ1ZGMzODhiAAEDd2JnGl9fd2JnX25ld184ZDJhZjAwYmMxZTMyOWVlAAEDd2JnHl9fd2JnX21lc3NhZ2VfZmUyYWY2M2NjYzg5ODViYwACA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AgggACAGNgIMIAYgBzYCDCAGIAA2AggLQcCxwAAgBTYCAEG4scAAIAI2AgAgAxC8ASEDDAYLQaiuwAAgASACcjYCACAHCyEBIAcgBjYCCCABIAY2AgwgBiAHNgIMIAYgATYCCAtBwLHAACAFNgIAQbixwAAgAzYCAAwBCyAAIAMgBGoQjQELIAAQvAEiAw0BCwJAAkACQAJAAkACQAJAAkBBuLHAACgCACIAIARJBEBBvLHAACgCACIAIARLDQIgC0EIQQgQlwEgBGpBFEEIEJcBakEQQQgQlwFqQYCABBCXARBxIAsoAgAiCA0BQQAhAwwJC0HAscAAKAIAIQIgACAEayIBQRBBCBCXAUkEQEHAscAAQQA2AgBBuLHAACgCACEAQbixwABBADYCACACIAAQjQEgAhC8ASEDDAkLIAIgBBC6ASEAQbixwAAgATYCAEHAscAAIAA2AgAgACABEJQBIAIgBBCmASACELwBIQMMCAsgCygCCCEMQcixwAAgCygCBCIKQcixwAAoAgBqIgE2AgBBzLHAAEHMscAAKAIAIgAgASAAIAFLGzYCAAJAAkBBxLHAACgCAARAQdCxwAAhAANAIAAQpwEgCEYNAiAAKAIIIgANAAsMAgtB5LHAACgCACIARSAIIABJcg0DDAcLIAAQsQENACAAELIBIAxHDQAgACIBKAIAIgVBxLHAACgCACICTQR/IAUgASgCBGogAksFQQALDQMLQeSxwABB5LHAACgCACIAIAggCCAASxs2AgAgCCAKaiEBQdCxwAAhAAJAAkADQCABIAAoAgBHBEAgACgCCCIADQEMAgsLIAAQsQENACAAELIBIAxGDQELQcSxwAAoAgAhCUHQscAAIQACQANAIAAoAgAgCU0EQCAAEKcBIAlLDQILIAAoAggiAA0AC0EAIQALIAkgABCnASIGQRRBCBCXASIPa0FpaiIBELwBIgBBCBCXASAAayABaiIAIABBEEEIEJcBIAlqSRsiDRC8ASEOIA0gDxC6ASEAQQhBCBCXASEDQRRBCBCXASEFQRBBCBCXASECQcSxwAAgCCAIELwBIgFBCBCXASABayIBELoBIgc2AgBBvLHAACAKQQhqIAIgAyAF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BIAMsAAFBv39KDQEMCAtBASEPIAUNAgwBCyAIQQFqIQggA0EBaiEDIAdBf2ohBwsgAkFAayADIAcgFBAfAkACQAJAAkACQCACKAJAIgcEQCACKAJMIQUgAigCSCEGIBYoAgACQCACKAJEIgNBf2oiAUUEQCAHLQAAIQkMAQsgA0UNBCABIAdqLAAAIglBv39MDQQLIAhqIQRBASEIIAlB/wFxIgkgCigCJEYNAUEAIQggCigCICAJRg0BIAMgBGohE0ECIQgMAgsgESANIA4gCyAIEBwgAikDMCEXIABBEGogAigCODYCACAAQQhqIBc3AgAgAEKBgICAMDcCAAwHCyADIARqIRMgAUUNAiABIQMLIANBA3EhCQJAIANBf2pBA0kEQEEAIQQgByEBDAELIANBfHEhDEEAIQQgByEBA0AgBCABLQAAQQpGaiABQQFqLQAAQQpGaiABQQJqLQAAQQpGaiABQQNqLQAAQQpGaiEEIAFBBGohASAMQXxqIgwNAAsLIAlFDQIDQCAEIAEtAABBCkZqIQQgAUEBaiEBIAlBf2oiCQ0ACwwCCyAHIAMgASADEHsAC0EAIQNBACEECyACKAIQIgEgAigCDEYEQCACQQhqIAEQPSACKAIQIQELIAQgC2ohCyACKAIIIAFBBHRqIgEgCDoADiABIBA6AA0gASAHNgIEIAFBATYCACABQQxqIA86AAAgAUEIaiADNgIAIAIgAigCEEEBajYCECACQRhqIAYgBSAKEB8gAigCGCIBRQ0DDAELCyARIA0gDiALIAgQHCACQQI2AiwgAkHCAGogEkECai0AACIBOgAAIAIgEi8AACIHOwFAIAJBOGooAgAhAyACKQMwIRcgAEECOgAEIAAgBzsABSAAQQdqIAE6AAAgAEEQaiADNgIAIABBCGogFzcCACAAQQE2AgALIAIoAgxFDQEgAigCCBAVDAELIAUEQCACKAIQIgEgAigCDEYEQCACQQhqIAEQPSACKAIQIQELIAIoAgggAUEEdGoiASAGNgIEIAFBADYCACABQQhqIAU2AgAgAiACKAIQQQFqNgIQCyAAIAIpAwg3AgQgAEEANgIAIABBDGogAkEQaigCADYCAAsgAk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EIAkAgAigCCCIBRQ0AIAFBBHQhCkGQhMAAIQZBACEBQQAhBANAAn8gASAIaiIHQQRqIgkgBygCAEUNABoCQCAERQ0AIANBEGogBCgCACAEKAIEQQAgBiAGLQAAQQJGG0EBEBAgA0EIaiADKAIQIAMoAhRBACAHQQ1qIgQgBC0AAEECRhtBABAQIANBGGogAygCCCADKAIMEBIgA0EBNgI0IANBATYCLCADIAU2AiggAyADQRhqNgIwIAMgADYCRCADQQI2AlwgA0IDNwJMIANBmITAADYCSCADIANBKGo2AlggA0HEAGpBmIrAACADQcgAahAeDQUgAygCHEUNACADKAIYEBULIAdBDmohBgJAIAdBDGotAABFBEAgA0ECNgIsIAMgCTYCKCADIAA2AhggA0EBNgJcIANCAjcCTCADQfSEwAA2AkggAyADQShqNgJYIANBGGpBmIrAACADQcgAahAeDQcgA0ECNgI0IANBoIXAADYCMCADQQE2AiwgAyAFNgIoIAMgADYCGCADQQI2AlwgA0IDNwJMIANBmITAADYCSCADIANBKGo2AlggA0EYakGYisAAIANByABqEB5FDQFBq4HAAEErIANByABqQdiBwABBqIXAABBSAAsgA0ECNgIsIAMgCTYCKCADIAA2AhggA0EBNgJcIANCAjcCTCADQcSEwAA2AkggAyADQShqNgJYIANBGGpBmIrAACADQcgAahAeDQcLQQALIQQgCiABQRBqIgFHDQALIARFDQAgAyAEKAIAIAQoAgRBACAGIAYtAABBAkYbQQEQECADQRhqIAMoAgAgAygCBBASIANBNGpBATYCACADQQE2AiwgAyAFNgIoIAMgA0EYajYCMCADIAA2AkQgA0HcAGpBAjYCACADQgM3AkwgA0GYhMAANgJIIAMgA0EoajYCWCADQcQAakGYisAAIANByABqEB4NBSADKAIcRQ0AIAMoAhgQFQsgAEEEaigCACAAQQhqIgQoAgAiAWtBJ00EQCAAIAFBKBBBIAQoAgAhAQsgBCABQShqNgIAIAAoAgAgAWoiAUHIhcAAKQAANwAAIAFBCGpB0IXAACkAADcAACABQRBqQdiFwAApAAA3AAAgAUEYakHghcAAKQAANwAAIAFBIGpB6IXAACkAADcAACADQTxqQQI2AgAgA0E0akEBNgIAIANBoIXAADYCOCADIAU2AjAgA0EBNgIsIAMgBTYCKCADIAA2AhggA0HcAGoiAUEDNgIAIANCBDcCTCADQZiGwAA2AkggAyADQShqNgJYIANBGGpBmIrAACADQcgAahAeDQUgA0EBNgIsIAMgBTYCKCADIAA2AhggAUEBNgIAIANCAjcCTCADQdCGwAA2AkggAyADQShqNgJYIANBGGpBmIrAACADQcgAahAeDQYgAkEEaigCAARAIAgQFQsgA0HgAGokAA8LQauBwABBKyADQcgAakHYgcAAQYCEwAAQUgALQauBwABBKyADQcgAakHYgcAAQbCEwAAQUgALQauBwABBKyADQcgAakHYgcAAQYSFwAAQUgALQauBwABBKyADQcgAakHYgcAAQdSEwAAQUgALQauBwABBKyADQcgAakHYgcAAQbiFwAAQUgALQauBwABBKyADQcgAakHYgcAAQbiGwAAQUgALQauBwABBKyADQcgAakHYgcAAQeCGwAAQUgAL7QkCCH8GfiMAQdAAayIDJAACQAJAAkAQVCIEBEAgA0EgakIANwMAIANBHGpBkIrAADYCACAEIAQpAwAiC0IBfDcDACADQQA2AhggAyALNwMIIAMgBEEIaikDADcDECADQqeAgIDwBDcDSCADQo2AgICgDjcDQCADQoqAgIDgDTcDOCADQtyAgIDACzcDMCADQQhqIANBMGoQGSADQQA2AjggA0IENwMwIAJFBEAgAEEANgIIIABCATcCAEEEIQRBBCEBDAQLIAEgAmohCEEAIQIDQAJ/IAEsAAAiBEF/SgRAIARB/wFxIQQgAUEBagwBCyABLQABQT9xIQUgBEEfcSEGIARBX00EQCAGQQZ0IAVyIQQgAUECagwBCyABLQACQT9xIAVBBnRyIQUgBEFwSQRAIAUgBkEMdHIhBCABQQNqDAELIAZBEnRBgIDwAHEgAS0AA0E/cSAFQQZ0cnIiBEGAgMQARg0EIAFBBGoLIQEgAyAENgIsAkAgA0EIaiADQSxqECJFBEAgAygCLCECIAMoAjgiBCADKAI0RgRAIANBMGogBBA+IAMoAjghBA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RHckUNASABQQE6ACUgBCACawshAyAIRQ0AIAIgCGohCyADRQRAQQAhAgwBCyADQX9qIgEgAyABIAtqLQAAQQ1GGyECCyAAIAI2AgQgACALNgIAIAVBEGokAAv+BAEKfyMAQTBrIgMkACADQSRqIAE2AgAgA0EDOgAoIANCgICAgIAENwMIIAMgADYCICADQQA2AhggA0EANgIQAkACQAJAIAIoAggiCkUEQCACQRRqKAIAIgRFDQEgAigCACEBIAIoAhAhACAEQX9qQf////8BcUEBaiIHIQQDQCABQQRqKAIAIgUEQCADKAIgIAEoAgAgBSADKAIkKAIMEQMADQQLIAAoAgAgA0EIaiAAQQRqKAIAEQEADQMgAEEIaiEAIAFBCGohASAEQX9qIgQNAAsMAQsgAkEMaigCACIARQ0AIABBBXQhCyAAQX9qQf///z9xQQFqIQcgAigCACEBA0AgAUEEaigCACIABEAgAygCICABKAIAIAAgAygCJCgCDBEDAA0DCyADIAQgCmoiBUEcai0AADoAKCADIAVBBGopAgBCIIk3AwggBUEYaigCACEGIAIoAhAhCEEAIQlBACEAAkACQAJAIAVBFGooAgBBAWsOAgACAQsgBkEDdCAIaiIMKAIEQTdHDQEgDCgCACgCACEGC0EBIQALIAMgBjYCFCADIAA2AhAgBUEQaigCACEAAkACQAJAIAVBDGooAgBBAWsOAgACAQsgAEEDdCAIaiIGKAIEQTdHDQEgBigCACgCACEAC0EBIQkLIAMgADYCHCADIAk2AhggCCAFKAIAQQN0aiIAKAIAIANBCGogACgCBBEBAA0CIAFBCGohASALIARBIGoiBEcNAAsLQQAhACAHIAIoAgRJIgFFDQEgAygCICACKAIAIAdBA3RqQQAgARsiASgCACABKAIEIAMoAiQoAgwRAwBFDQELQQEhAAsgA0EwaiQAIAALwgQBCH8jAEHQAGsiBCQAIARBEGogASACIAMoAgAgA0EIaigCABAOAkACQAJAAkACQAJAIAQoAhBFBEAgBEEeai0AAA0EIARBxABqKAIAIQYgBCgCQCEHIARBHGotAABFIQggBCgCFCEDA0ACQCADRQ0AIAYgA00EQC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GAAXI6AA0gAiABQQZ2QcABcjoADEECDAILIAAoAggiAyAAQQRqKAIARgRAIAAgAxBDIAAoAgghAwsgACADQQFqNgIIIAAoAgAgA2ogAToAAAwCCyABQYCABE8EQCACIAFBP3FBgAFyOgAPIAIgAUEGdkE/cUGAAXI6AA4gAiABQQx2QT9xQYABcjoADSACIAFBEnZBB3FB8AFyOgAMQQQMAQsgAiABQT9xQYABcjoADiACIAFBDHZB4AFyOgAMIAIgAUEGdkE/cUGAAXI6AA1BAwshASAAQQRqKAIAIABBCGoiBCgCACIDayABSQRAIAAgAyABEEIgBCgCACEDCyAAKAIAIANqIAJBDGogARC5ARogBCABIANqNgIACyACQRBqJAAL1wIBA38jAEEQayICJAACQAJ/AkACQCABQYABTwRAIAJBADYCDCABQYAQSQ0BIAFBgIAETw0CIAIgAUE/cUGAAXI6AA4gAiABQQx2QeABcjoADCACIAFBBnZBP3FBgAFyOgANQQMMAwsgACgCCCIDIABBBGooAgBGBEAgACADEEMgACgCCCEDCyAAIANBAWo2AgggACgCACADaiABOgAADAMLIAIgAUE/cUGAAXI6AA0gAiABQQZ2QcABcjoADEECDAELIAIgAUE/cUGAAXI6AA8gAiABQQZ2QT9xQYABcjoADiACIAFBDHZBP3FBgAFyOgANIAIgAUESdkEHcUHwAXI6AAxBBAshASAAQQRqKAIAIABBCGoiBCgCACIDayABSQRAIAAgAyABEEIgBCgCACEDCyAAKAIAIANqIAJBDGogARC5ARogBCABIANqNgIACyACQRBqJAALtgIBB38CQCACQQ9NBEAgACEDDAELIABBACAAa0EDcSIEaiEFIAQEQCAAIQMgASEGA0AgAyAGLQAAOgAAIAZBAWohBiADQQFqIgMgBUkNAAsLIAUgAiAEayIIQXxxIgdqIQMCQCABIARqIgRBA3EEQCAHQQFIDQEgBEEDdCICQRhxIQkgBEF8cSIGQQRqIQFBACACa0EYcSECIAYoAgAhBgNAIAUgBiAJdiABKAIAIgYgAnRyNgIAIAFBBGohASAFQQRqIgUgA0kNAAsMAQsgB0EBS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iASADIAEgA0sbIgFBBCABQQRLGyIBQf////8AcSABRkECdCEDIAFBBHQhBgJAIAVFBEBBACEEDAELIAIgBUEEdDYCFCACIAAoAgA2AhALIAIgBDYCGCACIAYgAyACQRBqEEsgAigCAARAIAJBCGooAgAiAEUNASACKAIEIAAQswEACyACKAIEIQMgAEEEaiABNgIAIAAgAzYCACACQSBqJAAPCxBzAAvTAQEFfyMAQSBrIgIkAAJAIAFBAWoiAyABSQ0AQQQhBCAAQQRqKAIAIgVBAXQiASADIAEgA0sbIgFBBCABQQRLGyIBQf////8DcSABRkECdCEDIAFBAnQhBgJAIAVFBEBBACEEDAELIAIgBUECdDYCFCACIAAoAgA2AhALIAIgBDYCGCACIAYgAyACQRBqEEsgAigCAARAIAJBCGooAgAiAEUNASACKAIEIAAQswEACyACKAIEIQMgAEEEaiABNgIAIAAgAzYCACACQSBqJAAPCxBzAAu3AQEEfyAAKAIAIgEgACgCBEYEQEGAgMQADwsgACABQQFqNgIAIAEtAAAiA0EYdEEYdUF/TAR/IAAgAUECajYCACABLQABQT9xIQIgA0EfcSEEIANB3wFNBEAgBEEGdCACcg8LIAAgAUEDajYCACABLQACQT9xIAJBBnRyIQIgA0HwAUkEQCACIARBDHRyDwsgACABQQRqNgIAIARBEnRBgIDwAHEgAS0AA0E/cSACQQZ0cnIFIAMLC68BAQN/IwBBIGsiAiQAAkAgAUEBaiIDIAFJDQAgAEEEaigCACIBQQF0IgQgAyAEIANLGyIDQQggA0EISxshAyACIAEEfyACIAE2AhQgAiAAKAIANgIQQQEFQQALNgIYIAIgA0EBIAJBEGoQSyACKAIABEAgAkEIaigCACIARQ0BIAIoAgQgABCzAQALIAIoAgQhASAAQQRqIAM2AgAgACABNgIAIAJBIGokAA8LEHMAC68BAQJ/IwBBIGsiAyQAAkAgASACaiICIAFJDQAgAEEEaigCACIBQQF0IgQgAiAEIAJLGyICQQggAkEISxshBCADIAEEfyADIAE2AhQgAyAAKAIANgIQQQEFQQALNgIYIAMgBEEBIANBEGoQSyADKAIABEAgA0EIaigCACIARQ0BIAMoAgQgABCzAQALIAMoAgQhASAAQQRqIAQ2AgAgACABNgIAIANBIGokAA8LEHMAC60BAQJ/IwBBIGsiAyQAAkAgASACaiICIAFJDQAgAEEEaigCACIBQQF0IgQgAiAEIAJLGyICQQggAkEISxshBCADIAEEfyADIAE2AhQgAyAAKAIANgIQQQEFQQALNgIYIAMgBCADQRBqEEogAygCAARAIANBCGooAgAiAEUNASADKAIEIAAQswEACyADKAIEIQEgAEEEaiAENgIAIAAgATYCACADQSBqJAAPCxBzAAutAQEDfyMAQSBrIgIkAAJAIAFBAWoiAyABSQ0AIABBBGooAgAiAUEBdCIEIAMgBCADSxsiA0EIIANBCEsbIQMgAiABBH8gAiABNgIUIAIgACgCADYCEEEBBUEACzYCGCACIAMgAkEQahBKIAIoAgAEQCACQQhqKAIAIgBFDQEgAigCBCAAELMBAAsgAigCBCEBIABBBGogAzYCACAAIAE2AgAgAkEgaiQADwsQcwAL7wEBA38jAEEgayIFJABBjK7AAEGMrsAAKAIAIgdBAWo2AgBB7LHAAEHsscAAKAIAQQFqIgY2AgACQAJAIAdBAEggBkECS3INACAFIAQ6ABggBSADNgIUIAUgAjYCEEGArsAAKAIAIgJBf0wNAEGArsAAIAJBAWoiAjYCAEGArsAAQYiuwAAoAgAiAwR/QYSuwAAoAgAgBSAAIAEoAhARAAAgBSAFKQMANwMIIAVBCGogAygCFBEAAEGArsAAKAIABSACC0F/ajYCACAGQQFLDQAgBA0BCwALIwBBEGsiAiQAIAIgATYCDCACIAA2AggAC58BAQN/AkAgAUEPTQRAIAAhAgwBCyAAQQAgAGtBA3EiBGohAyAEBEAgACECA0AgAkH/AToAACACQQFqIgIgA0kNAAsLIAMgASAEayIBQXxxIgRqIQIgBEEBTgRAA0AgA0F/NgIAIANBBGoiAyACSQ0ACwsgAUEDcSEBCyABBEAgASACaiEBA0AgAkH/AToAACACQQFqIgIgAUkNAAsLIAALrAEBA38jAEEQayIDJAACQAJAIAEEQCABKAIAIgJBf0YNASABIAJBAWo2AgAgAyABQQRqEGEgASABKAIAQX9qNgIAIAMoAgAhAQJAIAMoAgQiAiADKAIIIgRNBEAgASECDAELIARFBEBBASECIAEQFQwBCyABIAJBASAEEJkBIgJFDQMLIAAgBDYCBCAAIAI2AgAgA0EQaiQADwsQrQEACxCuAQALIARBARCzAQALrAEBA38jAEEQayIDJAACQAJAIAEEQCABKAIAIgJBf0YNASABIAJBAWo2AgAgAyABQRBqEGEgASABKAIAQX9qNgIAIAMoAgAhAQJAIAMoAgQiAiADKAIIIgRNBEAgASECDAELIARFBEBBASECIAEQFQwBCyABIAJBASAEEJkBIgJFDQMLIAAgBDYCBCAAIAI2AgAgA0EQaiQADwsQrQEACxCuAQALIARBARCzAQALrAEBA38jAEEQayIDJAACQAJAIAEEQCABKAIAIgJBf0YNASABIAJBAWo2AgAgAyABQSxqEGEgASABKAIAQX9qNgIAIAMoAgAhAQJAIAMoAgQiAiADKAIIIgRNBEAgASECDAELIARFBEBBASECIAEQFQwBCyABIAJBASAEEJkBIgJFDQMLIAAgBDYCBCAAIAI2AgAgA0EQaiQADwsQrQEACxCuAQALIARBARCzAQALrAEBA38jAEEwayICJAAgAUEEaiEDIAEoAgRFBEAgASgCACEBIAJBEGoiBEEANgIAIAJCATcDCCACIAJBCGo2AhQgAkEoaiABQRBqKQIANwMAIAJBIGogAUEIaikCADcDACACIAEpAgA3AxggAkEUakGAjsAAIAJBGGoQHhogA0EIaiAEKAIANgIAIAMgAikDCDcCAAsgAEHoj8AANgIEIAAgAzYCACACQTBqJAALkAEBAn8CQAJ/AkACQAJAAn9BASIDIAFBAEgNABogAigCCEUNAiACKAIEIgQNASABDQNBAQwECyEDQQAhAQwECyACKAIAIARBASABEJkBDAILIAENAEEBDAELIAFBARCeAQsiAgRAIAAgAjYCBEEAIQMMAQsgACABNgIEQQEhAQsgACADNgIAIABBCGogATYCAAunAQECfwJAAkACQAJAAkACQAJAAn8gAgRAQQEiBCABQQBIDQEaIA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yACQSBqJAAgAwtvAQF/IwBBMGsiAiQAIAIgATYCBCACIAA2AgAgAkEcakECNgIAIAJBLGpBAzYCACACQgI3AgwgAkGklsAANgIIIAJBAzYCJCACIAJBIGo2AhggAiACQQRqNgIoIAIgAjYCICACQQhqQdSWwAAQdAALbwEBfyMAQTBrIgIkACACIAE2AgQgAiAANgIAIAJBHGpBAjYCACACQSxqQQM2AgAgAkICNwIMIAJBuJfAADYCCCACQQM2AiQgAiACQSBqNgIYIAIgAkEEajYCKCACIAI2AiAgAkEIakHIl8AAEHQAC28BAX8jAEEwayICJAAgAiABNgIEIAIgADYCACACQRxqQQI2AgAgAkEsakEDNgIAIAJCAjcCDCACQfSWwAA2AgggAkEDNgIkIAIgAkEgajYCGCACIAJBBGo2AiggAiACNgIgIAJBCGpBhJfAABB0AAtsAQF/IwBBMGsiAyQAIAMgATYCBCADIAA2AgAgA0EcakECNgIAIANBLGpBAzYCACADQgI3AgwgA0HAk8AANgIIIANBAzYCJCADIANBIGo2AhggAyADNgIoIAMgA0EEajYCICADQQhqIAIQdAALVgECfyMAQSBrIgIkACAAQRxqKAIAIQMgACgCGCACQRhqIAFBEGopAgA3AwAgAkEQaiABQQhqKQIANwMAIAIgASkCADcDCCADIAJBCGoQHiACQSBqJAALWQEBfyMAQSBrIgIkACACIAAoAgA2AgQgAkEYaiABQRBqKQIANwMAIAJBEGogAUEIaikCADcDACACIAEpAgA3AwggAkEEakGYisAAIAJBCGoQHiACQSBqJAALWQEBfyMAQSBrIgIkACACIAAoAgA2AgQgAkEYaiABQRBqKQIANwMAIAJBEGogAUEIaikCADcDACACIAEpAgA3AwggAkEEakGAjsAAIAJBCGoQHiACQSBqJAALZwAjAEEwayIBJABB2K3AAC0AAARAIAFBHGpBATYCACABQgI3AgwgAUH0jsAANgIIIAFBAzYCJCABIAA2AiwgASABQSBqNgIYIAEgAUEsajYCICABQQhqQZyPwAAQdAALIAFBMGokAAtZAQF/IwBBIGsiAiQAIAIgACgCADYCBCACQRhqI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kACAAQQhqIAEQfSAAQQhqEFMgAEEQaiQACysAAkAgAARAIAAoAgANASAAQQA2AgAgAEEcaiABNgIADwsQrQEACxCuAQALKwACQCAABEAgACgCAA0BIABBADYCACAAQSBqIAE2AgAPCxCtAQALEK4BAAsrAAJAIAAEQCAAKAIADQEgAEEANgIAIABBJGogATYCAA8LEK0BAAsQrgEACysAAkAgAARAIAAoAgANASAAQQA2AgAgAEEoaiABNgIADwsQrQEACxCuAQALQAEBfyMAQRBrIgQkACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgAgBCgCACAEKAIEIAQoAgggBCgCDBATAAs3ACAAQQM6ACAgAEKAgICAgAQ3AgAgACABNgIYIABBADYCECAAQQA2AgggAEEcakHEh8AANgIACzUBAX8gASgCGEHDjsAAQQsgAUEcaigCACgCDBEDACECIABBADoABSAAIAI6AAQgACABNgIACyUAAkAgAARAIAAoAgBBf0YNASAAQRxqKAIADwsQrQEACxCuAQALJQACQCAABEAgACgCAEF/Rg0BIABBIGooAgAPCxCtAQALEK4BAAslAAJAIAAEQCAAKAIAQX9GDQEgAEEkaigCAA8LEK0BAAsQrgEACyUAAkAgAARAIAAoAgBBf0YNASAAQShqKAIADwsQrQEACxCuAQALJwAgACAAKAIEQQFxIAFyQQJyNgIEIAAgAWoiACAAKAIEQQFyNgIECzoBAn9B3K3AAC0AACEBQdytwABBADoAAEHgrcAAKAIAIQJB4K3AAEEANgIAIAAgAjYCBCAAIAE2AgALIAEBfwJAIAAoAgQiAUUNACAAQQhqKAIARQ0AIAEQFQsLHwACQCABQXxNBEAgACABQQQgAhCZASIADQELAAsgAAsjACACIAIoAgRBfnE2AgQgACABQQFyNgIEIAAgAWogATYCAAslACAARQRAQciMwABBMBCsAQALIAAgAiADIAQgBSABKAIQEQoACyMAIABFBEBByIzAAEEwEKwBAAsgACACIAMgBCABKAIQEQgACyMAIABFBEBByIzAAEEwEKwBAAsgACACIAMgBCABKAIQEQcACyMAIABFBEBByIzAAEEwEKwBAAsgACACIAMgBCABKAIQERUACyMAIABFBEBByIzAAEEwEKwBAAsgACACIAMgBCABKAIQERIACyMAIABFBEBByIzAAEEwEKwBAAsgACACIAMgBCABKAIQERQACx4AIAAgAUEDcjYCBCAAIAFqIgAgACgCBEEBcjYCBAsUACAAQQRqKAIABEAgACgCABAVCwshACAARQRAQciMwABBMBCsAQALIAAgAiADIAEoAhARBAALHwAgAEUEQEHIjMAAQTAQrAEACyAAIAIgASgCEBEBAAsZAQF/IAAoAhAiAQR/IAEFIABBFGooAgALCxkAIAAoAgAiACgCACAAQQhqKAIAIAEQtwELEgBBAEEZIABBAXZrIABBH0YbCxYAIAAgAUEBcjYCBCAAIAFqIAE2AgALHAAgASgCGEHgpsAAQQUgAUEcaigCACgCDBEDAAsTACAAKAIAIgBBJE8EQCAAEAALCxAAIAAgAWpBf2pBACABa3ELFAAgACgCACAAQQhqKAIAIAEQtwELDAAgACABIAIgAxAYCwsAIAEEQCAAEBULCw8AIABBAXQiAEEAIABrcgsUACAAKAIAIAEgACgCBCgCDBEBAAsRACAAKAIAIAAoAgQgARC3AQsIACAAIAEQJwsWAEHgrcAAIAA2AgBB3K3AAEEBOgAACw0AIAAoAgAgARAuQQALEwAgAEH4j8AANgIEIAAgATYCAAsNACAALQAEQQJxQQF2CxAAIAEgACgCACAAKAIEEBYLCgBBACAAayAAcQsLACAALQAEQQNxRQsMACAAIAFBA3I2AgQLDQAgACgCACAAKAIEagsNACAAKAIAIAEQL0EACw4AIAAoAgAaA0AMAAsACwsAIAA1AgAgARAyCwsAIAAjAGokACMACwkAIAAgARAKAAsNAEGUjcAAQRsQrAEACw4AQa+NwABBzwAQrAEACwoAIAAoAgRBeHELCgAgACgCBEEBcQsKACAAKAIMQQFxCwoAIAAoAgxBAXYLGQAgACABQfytwAAoAgAiAEEjIAAbEQAAAAsJACAAIAEQWAALCQAgACABEFoACwkAIAAgARBZAAsKACACIAAgARAWCwoAIAAgASACEGwLCgAgACABIAIQMAsHACAAIAFqCwcAIAAgA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GVBQADAQIFBCgDBAGlAgAEAAKZCzEEewE2DykBAgIKAzEEAgIHAT0DJAUBCD4BDAI0CQoEAgFfAwIBAQIGAaABAwgVAjkCAQEBARYBDgcDBcMIAgMBARcBUQECBgEBAgEBAgEC6wECBAYCAQIbAlUIAgEBAmoBAQECBgEBZQMCBAEFAAkBAvUBCgIBAQQBkAQCAgQBIAooBgIECAEJBgIDLg0BAgAHAQYBAVIWAgcBAgECegYDAQECAQcBAUgCAwEBAQACAAU7BwABPwRRAQACAC4CFwABAQMEBQgIAgceBJQDADcEMggBDgEWBQEPAAcBEQIHAQIBBQAHAAE9BAAHbQcAYIDwAACAFgAAACAgAQAwYAEBMHECCQUSAWQBGgEAAQALHQIFAS8BAAEAewlwcm9kdWNlcnMCCGxhbmd1YWdlAQRSdXN0AAxwcm9jZXNzZWQtYnkDBXJ1c3RjHTEuNjQuMCAoYTU1ZGQ3MWQ1IDIwMjItMDktMTkpBndhbHJ1cwYwLjE5LjAMd2FzbS1iaW5kZ2VuEjAuMi44MyAoZWJhNjkxZjM4KQ=="); + +// src/core/parser/Parser.ts +var Parser = class { + async init() { + await rusty_engine_default(rusty_engine_bg_default); + const config = new ParserConfig("<%", "%>", "\0", "*", "-", "_", "tR"); + this.renderer = new Renderer(config); + } + async parse_commands(content, context) { + return this.renderer.render_content(content, context); + } +}; + +// src/core/Templater.ts +var RunMode; +(function(RunMode2) { + RunMode2[RunMode2["CreateNewFromTemplate"] = 0] = "CreateNewFromTemplate"; + RunMode2[RunMode2["AppendActiveFile"] = 1] = "AppendActiveFile"; + RunMode2[RunMode2["OverwriteFile"] = 2] = "OverwriteFile"; + RunMode2[RunMode2["OverwriteActiveFile"] = 3] = "OverwriteActiveFile"; + RunMode2[RunMode2["DynamicProcessor"] = 4] = "DynamicProcessor"; + RunMode2[RunMode2["StartupTemplate"] = 5] = "StartupTemplate"; +})(RunMode || (RunMode = {})); +var Templater = class { + constructor(plugin) { + this.plugin = plugin; + this.functions_generator = new FunctionsGenerator(this.plugin); + this.parser = new Parser(); + } + async setup() { + this.files_with_pending_templates = new Set(); + await this.parser.init(); + await this.functions_generator.init(); + this.plugin.registerMarkdownPostProcessor((el, ctx) => this.process_dynamic_templates(el, ctx)); + } + create_running_config(template_file, target_file, run_mode) { + const active_file = get_active_file(app); + return { + template_file, + target_file, + run_mode, + active_file + }; + } + async read_and_parse_template(config) { + const template_content = await app.vault.read(config.template_file); + return this.parse_template(config, template_content); + } + async parse_template(config, template_content) { + const functions_object = await this.functions_generator.generate_object(config, FunctionsMode.USER_INTERNAL); + this.current_functions_object = functions_object; + const content = await this.parser.parse_commands(template_content, functions_object); + return content; + } + start_templater_task(path) { + this.files_with_pending_templates.add(path); + } + async end_templater_task(path) { + this.files_with_pending_templates.delete(path); + if (this.files_with_pending_templates.size === 0) { + app.workspace.trigger("templater:all-templates-executed"); + await this.functions_generator.teardown(); + } + } + async create_new_note_from_template(template, folder, filename, open_new_note = true) { + if (!folder) { + const new_file_location = app.vault.getConfig("newFileLocation"); + switch (new_file_location) { + case "current": { + const active_file = get_active_file(app); + if (active_file) { + folder = active_file.parent; + } + break; + } + case "folder": + folder = app.fileManager.getNewFileParent(""); + break; + case "root": + folder = app.vault.getRoot(); + break; + default: + break; + } + } + const extension = template instanceof import_obsidian12.TFile ? template.extension || "md" : "md"; + const created_note = await errorWrapper(async () => { + const folderPath = folder instanceof import_obsidian12.TFolder ? folder.path : folder; + const path2 = app.vault.getAvailablePath((0, import_obsidian12.normalizePath)(`${folderPath ?? ""}/${filename || "Untitled"}`), extension); + const folder_path = get_folder_path_from_file_path(path2); + if (folder_path && !app.vault.getAbstractFileByPathInsensitive(folder_path)) { + await app.vault.createFolder(folder_path); + } + return app.vault.create(path2, ""); + }, `Couldn't create ${extension} file.`); + if (created_note == null) { + return; + } + const { path } = created_note; + this.start_templater_task(path); + let running_config; + let output_content; + if (template instanceof import_obsidian12.TFile) { + running_config = this.create_running_config(template, created_note, 0); + output_content = await errorWrapper(async () => this.read_and_parse_template(running_config), "Template parsing error, aborting."); + } else { + running_config = this.create_running_config(void 0, created_note, 0); + output_content = await errorWrapper(async () => this.parse_template(running_config, template), "Template parsing error, aborting."); + } + if (output_content == null) { + await app.vault.delete(created_note); + await this.end_templater_task(path); + return; + } + await app.vault.modify(created_note, output_content); + app.workspace.trigger("templater:new-note-from-template", { + file: created_note, + content: output_content + }); + if (open_new_note) { + const active_leaf = app.workspace.getLeaf(false); + if (!active_leaf) { + log_error(new TemplaterError("No active leaf")); + return; + } + await active_leaf.openFile(created_note, { + state: { mode: "source" } + }); + await this.plugin.editor_handler.jump_to_next_cursor_location(created_note, true); + active_leaf.setEphemeralState({ + rename: "all" + }); + } + await this.end_templater_task(path); + return created_note; + } + async append_template_to_active_file(template_file) { + const active_view = app.workspace.getActiveViewOfType(import_obsidian12.MarkdownView); + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.file || !active_editor.editor) { + log_error(new TemplaterError("No active editor, can't append templates.")); + return; + } + const { path } = active_editor.file; + this.start_templater_task(path); + const running_config = this.create_running_config(template_file, active_editor.file, 1); + const output_content = await errorWrapper(async () => this.read_and_parse_template(running_config), "Template parsing error, aborting."); + if (output_content == null) { + await this.end_templater_task(path); + return; + } + const editor = active_editor.editor; + const doc = editor.getDoc(); + const oldSelections = doc.listSelections(); + doc.replaceSelection(output_content); + if (active_editor.file) { + await app.vault.append(active_editor.file, ""); + } + app.workspace.trigger("templater:template-appended", { + view: active_view, + editor: active_editor, + content: output_content, + oldSelections, + newSelections: doc.listSelections() + }); + await this.plugin.editor_handler.jump_to_next_cursor_location(active_editor.file, true); + await this.end_templater_task(path); + } + async write_template_to_file(template_file, file) { + const { path } = file; + this.start_templater_task(path); + const active_editor = app.workspace.activeEditor; + const active_file = get_active_file(app); + const running_config = this.create_running_config(template_file, file, 2); + const output_content = await errorWrapper(async () => this.read_and_parse_template(running_config), "Template parsing error, aborting."); + if (output_content == null) { + await this.end_templater_task(path); + return; + } + await app.vault.modify(file, output_content); + if (active_file?.path === file.path && active_editor && active_editor.editor) { + const editor = active_editor.editor; + editor.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 0 }); + } + app.workspace.trigger("templater:new-note-from-template", { + file, + content: output_content + }); + await this.plugin.editor_handler.jump_to_next_cursor_location(file, true); + await this.end_templater_task(path); + } + overwrite_active_file_commands() { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.file) { + log_error(new TemplaterError("Active editor is null, can't overwrite content")); + return; + } + this.overwrite_file_commands(active_editor.file, true); + } + async overwrite_file_commands(file, active_file = false) { + const { path } = file; + this.start_templater_task(path); + const running_config = this.create_running_config(file, file, active_file ? 3 : 2); + const output_content = await errorWrapper(async () => this.read_and_parse_template(running_config), "Template parsing error, aborting."); + if (output_content == null) { + await this.end_templater_task(path); + return; + } + await app.vault.modify(file, output_content); + app.workspace.trigger("templater:overwrite-file", { + file, + content: output_content + }); + await this.plugin.editor_handler.jump_to_next_cursor_location(file, true); + await this.end_templater_task(path); + } + async process_dynamic_templates(el, ctx) { + const dynamic_command_regex = generate_dynamic_command_regex(); + const walker = document.createNodeIterator(el, NodeFilter.SHOW_TEXT); + let node; + let pass = false; + let functions_object; + while (node = walker.nextNode()) { + let content = node.nodeValue; + if (content !== null) { + let match = dynamic_command_regex.exec(content); + if (match !== null) { + const file = app.metadataCache.getFirstLinkpathDest("", ctx.sourcePath); + if (!file || !(file instanceof import_obsidian12.TFile)) { + return; + } + if (!pass) { + pass = true; + const config = this.create_running_config(file, file, 4); + functions_object = await this.functions_generator.generate_object(config, FunctionsMode.USER_INTERNAL); + this.current_functions_object = functions_object; + } + } + while (match != null) { + const complete_command = match[1] + match[2]; + const command_output = await errorWrapper(async () => { + return await this.parser.parse_commands(complete_command, functions_object); + }, `Command Parsing error in dynamic command '${complete_command}'`); + if (command_output == null) { + return; + } + const start2 = dynamic_command_regex.lastIndex - match[0].length; + const end2 = dynamic_command_regex.lastIndex; + content = content.substring(0, start2) + command_output + content.substring(end2); + dynamic_command_regex.lastIndex += command_output.length - match[0].length; + match = dynamic_command_regex.exec(content); + } + node.nodeValue = content; + } + } + } + get_new_file_template_for_folder(folder) { + do { + const match = this.plugin.settings.folder_templates.find((e) => e.folder == folder.path); + if (match && match.template) { + return match.template; + } + folder = folder.parent; + } while (folder); + } + static async on_file_creation(templater, file) { + if (!(file instanceof import_obsidian12.TFile) || file.extension !== "md") { + return; + } + const template_folder = (0, import_obsidian12.normalizePath)(templater.plugin.settings.templates_folder); + if (file.path.includes(template_folder) && template_folder !== "/") { + return; + } + await delay(300); + if (templater.files_with_pending_templates.has(file.path)) { + return; + } + if (file.stat.size == 0 && templater.plugin.settings.enable_folder_templates) { + const folder_template_match = templater.get_new_file_template_for_folder(file.parent); + if (!folder_template_match) { + return; + } + const template_file = await errorWrapper(async () => { + return resolve_tfile(folder_template_match); + }, `Couldn't find template ${folder_template_match}`); + if (template_file == null) { + return; + } + await templater.write_template_to_file(template_file, file); + } else { + if (file.stat.size <= 1e5) { + await templater.overwrite_file_commands(file); + } else { + console.log(`Templater skipped parsing ${file.path} because file size exceeds 10000`); + } + } + } + async execute_startup_scripts() { + for (const template of this.plugin.settings.startup_templates) { + if (!template) { + continue; + } + const file = errorWrapperSync(() => resolve_tfile(template), `Couldn't find startup template "${template}"`); + if (!file) { + continue; + } + const { path } = file; + this.start_templater_task(path); + const running_config = this.create_running_config(file, file, 5); + await errorWrapper(async () => this.read_and_parse_template(running_config), `Startup Template parsing error, aborting.`); + await this.end_templater_task(path); + } + } +}; + +// src/handlers/EventHandler.ts +var import_obsidian13 = __toModule(require("obsidian")); +var EventHandler = class { + constructor(plugin, templater, settings) { + this.plugin = plugin; + this.templater = templater; + this.settings = settings; + } + setup() { + this.plugin.app.workspace.onLayoutReady(() => { + this.update_trigger_file_on_creation(); + }); + this.update_syntax_highlighting(); + this.update_file_menu(); + } + update_syntax_highlighting() { + const desktopShouldHighlight = this.plugin.editor_handler.desktopShouldHighlight(); + const mobileShouldHighlight = this.plugin.editor_handler.mobileShouldHighlight(); + if (desktopShouldHighlight || mobileShouldHighlight) { + this.plugin.editor_handler.enable_highlighter(); + } else { + this.plugin.editor_handler.disable_highlighter(); + } + } + update_trigger_file_on_creation() { + if (this.settings.trigger_on_file_creation) { + this.trigger_on_file_creation_event = this.plugin.app.vault.on("create", (file) => Templater.on_file_creation(this.templater, file)); + this.plugin.registerEvent(this.trigger_on_file_creation_event); + } else { + if (this.trigger_on_file_creation_event) { + this.plugin.app.vault.offref(this.trigger_on_file_creation_event); + this.trigger_on_file_creation_event = void 0; + } + } + } + update_file_menu() { + this.plugin.registerEvent(this.plugin.app.workspace.on("file-menu", (menu, file) => { + if (file instanceof import_obsidian13.TFolder) { + menu.addItem((item) => { + item.setTitle("Create new note from template").setIcon("templater-icon").onClick(() => { + this.plugin.fuzzy_suggester.create_new_note_from_template(file); + }); + }); + } + })); + } +}; + +// src/handlers/CommandHandler.ts +var CommandHandler = class { + constructor(plugin) { + this.plugin = plugin; + } + setup() { + this.plugin.addCommand({ + id: "insert-templater", + name: "Open insert template modal", + icon: "templater-icon", + hotkeys: [ + { + modifiers: ["Alt"], + key: "e" + } + ], + callback: () => { + this.plugin.fuzzy_suggester.insert_template(); + } + }); + this.plugin.addCommand({ + id: "replace-in-file-templater", + name: "Replace templates in the active file", + icon: "templater-icon", + hotkeys: [ + { + modifiers: ["Alt"], + key: "r" + } + ], + callback: () => { + this.plugin.templater.overwrite_active_file_commands(); + } + }); + this.plugin.addCommand({ + id: "jump-to-next-cursor-location", + name: "Jump to next cursor location", + icon: "text-cursor", + hotkeys: [ + { + modifiers: ["Alt"], + key: "Tab" + } + ], + callback: () => { + this.plugin.editor_handler.jump_to_next_cursor_location(); + } + }); + this.plugin.addCommand({ + id: "create-new-note-from-template", + name: "Create new note from template", + icon: "templater-icon", + hotkeys: [ + { + modifiers: ["Alt"], + key: "n" + } + ], + callback: () => { + this.plugin.fuzzy_suggester.create_new_note_from_template(); + } + }); + this.register_templates_hotkeys(); + } + register_templates_hotkeys() { + this.plugin.settings.enabled_templates_hotkeys.forEach((template) => { + if (template) { + this.add_template_hotkey(null, template); + } + }); + } + add_template_hotkey(old_template, new_template) { + this.remove_template_hotkey(old_template); + if (new_template) { + this.plugin.addCommand({ + id: new_template, + name: `Insert ${new_template}`, + icon: "templater-icon", + callback: () => { + const template = errorWrapperSync(() => resolve_tfile(new_template), `Couldn't find the template file associated with this hotkey`); + if (!template) { + return; + } + this.plugin.templater.append_template_to_active_file(template); + } + }); + } + } + remove_template_hotkey(template) { + if (template) { + app.commands.removeCommand(`${this.plugin.manifest.id}:${template}`); + } + } +}; + +// src/editor/Editor.ts +var import_obsidian16 = __toModule(require("obsidian")); + +// src/editor/CursorJumper.ts +var import_obsidian14 = __toModule(require("obsidian")); +var CursorJumper = class { + constructor() { + } + async jump_to_next_cursor_location() { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.editor) { + return; + } + const content = active_editor.editor.getValue(); + const { new_content, positions } = this.replace_and_get_cursor_positions(content); + if (positions) { + const fold_info = active_editor instanceof import_obsidian14.MarkdownView ? active_editor.currentMode.getFoldInfo() : null; + active_editor.editor.setValue(new_content); + if (fold_info && Array.isArray(fold_info.folds)) { + positions.forEach((position) => { + fold_info.folds = fold_info.folds.filter((fold) => fold.from > position.line || fold.to < position.line); + }); + if (active_editor instanceof import_obsidian14.MarkdownView) { + active_editor.currentMode.applyFoldInfo(fold_info); + } + } + this.set_cursor_location(positions); + } + if (app.vault.getConfig("vimMode")) { + const cm = active_editor.editor.cm.cm; + window.CodeMirrorAdapter.Vim.handleKey(cm, "i", "mapping"); + } + } + get_editor_position_from_index(content, index) { + const substr = content.slice(0, index); + let l = 0; + let offset2 = -1; + let r = -1; + for (; (r = substr.indexOf("\n", r + 1)) !== -1; l++, offset2 = r) + ; + offset2 += 1; + const ch = content.slice(offset2, index).length; + return { line: l, ch }; + } + replace_and_get_cursor_positions(content) { + let cursor_matches = []; + let match; + const cursor_regex = new RegExp("<%\\s*tp.file.cursor\\((?[0-9]*)\\)\\s*%>", "g"); + while ((match = cursor_regex.exec(content)) != null) { + cursor_matches.push(match); + } + if (cursor_matches.length === 0) { + return {}; + } + cursor_matches.sort((m1, m2) => { + return Number(m1.groups && m1.groups["order"]) - Number(m2.groups && m2.groups["order"]); + }); + const match_str = cursor_matches[0][0]; + cursor_matches = cursor_matches.filter((m) => { + return m[0] === match_str; + }); + const positions = []; + let index_offset = 0; + for (const match2 of cursor_matches) { + const index = match2.index - index_offset; + positions.push(this.get_editor_position_from_index(content, index)); + content = content.replace(new RegExp(escape_RegExp(match2[0])), ""); + index_offset += match2[0].length; + if (match2[1] === "") { + break; + } + } + return { new_content: content, positions }; + } + set_cursor_location(positions) { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.editor) { + return; + } + const editor = active_editor.editor; + const selections = []; + for (const pos of positions) { + selections.push({ from: pos }); + } + const transaction = { + selections + }; + editor.transaction(transaction); + } +}; + +// src/editor/Autocomplete.ts +var import_obsidian15 = __toModule(require("obsidian")); + +// toml:/home/runner/work/Templater/Templater/docs/documentation.toml +var tp = { config: { name: "config", description: "This module exposes Templater's running configuration.\n\nThis is mostly useful when writing scripts requiring some context information.\n", functions: { template_file: { name: "template_file", description: "The `TFile` object representing the template file.", definition: "tp.config.template_file" }, target_file: { name: "target_file", description: "The `TFile` object representing the target file where the template will be inserted.", definition: "tp.config.target_file" }, run_mode: { name: "run_mode", description: "The `RunMode`, representing the way Templater was launched (Create new from template, Append to active file, ...).", definition: "tp.config.run_mode" }, active_file: { name: "active_file", description: "The active file (if existing) when launching Templater.", definition: "tp.config.active_file?" } } }, date: { name: "date", description: "This module contains every internal function related to dates.", functions: { now: { name: "now", description: "Retrieves the date.", definition: 'tp.date.now(format: string = "YYYY-MM-DD", offset?: number\u23AEstring, reference?: string, reference_format?: string)', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }, { name: "offset", description: "Duration to offset the date from. If a number is provided, duration will be added to the date in days. You can also specify the offset as a string using the ISO 8601 format." }, { name: "reference", description: "The date referential, e.g. set this to the note's title." }, { name: "reference_format", description: "The format for the reference date. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/)." }], examples: [{ name: "Date now", example: "<% tp.date.now() %>" }, { name: "Date now with format", example: '<% tp.date.now("Do MMMM YYYY") %>' }, { name: "Last week", example: '<% tp.date.now("YYYY-MM-DD", -7) %>' }, { name: "Next week", example: '<% tp.date.now("YYYY-MM-DD", 7) %>' }, { name: "Last month", example: '<% tp.date.now("YYYY-MM-DD", "P-1M") %>' }, { name: "Next year", example: '<% tp.date.now("YYYY-MM-DD", "P1Y") %>' }, { name: "File's title date + 1 day (tomorrow)", example: '<% tp.date.now("YYYY-MM-DD", 1, tp.file.title, "YYYY-MM-DD") %>' }, { name: "File's title date - 1 day (yesterday)", example: '<% tp.date.now("YYYY-MM-DD", -1, tp.file.title, "YYYY-MM-DD") %>' }] }, tomorrow: { name: "tomorrow", description: "Retrieves tomorrow's date.", definition: 'tp.date.tomorrow(format: string = "YYYY-MM-DD")', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }], examples: [{ name: "Date tomorrow", example: "<% tp.date.tomorrow() %>" }, { name: "Date tomorrow with format", example: '<% tp.date.tomorrow("Do MMMM YYYY") %>' }] }, yesterday: { name: "yesterday", description: "Retrieves yesterday's date.", definition: 'tp.date.yesterday(format: string = "YYYY-MM-DD")', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }], examples: [{ name: "Date yesterday", example: "<% tp.date.yesterday() %>" }, { name: "Date yesterday with format", example: '<% tp.date.yesterday("Do MMMM YYYY") %>' }] }, weekday: { name: "weekday", description: "", definition: 'tp.date.weekday(format: string = "YYYY-MM-DD", weekday: number, reference?: string, reference_format?: string)', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }, { name: "weekday", description: "Week day number. If the locale assigns Monday as the first day of the week, `0` will be Monday, `-7` will be last week's day." }, { name: "reference", description: "The date referential, e.g. set this to the note's title." }, { name: "reference_format", description: "The format for the reference date. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/)." }], examples: [{ name: "This week's Monday", example: '<% tp.date.weekday("YYYY-MM-DD", 0) %>' }, { name: "Next Monday", example: '<% tp.date.weekday("YYYY-MM-DD", 7) %>' }, { name: "File's title Monday", example: '<% tp.date.weekday("YYYY-MM-DD", 0, tp.file.title, "YYYY-MM-DD") %>' }, { name: "File's title previous Monday", example: '<% tp.date.weekday("YYYY-MM-DD", -7, tp.file.title, "YYYY-MM-DD") %>' }] } }, momentjs: { examples: [{ name: "Date now", example: '<% moment(tp.file.title, "YYYY-MM-DD").format("YYYY-MM-DD") %>' }, { name: "Get start of month from note title", example: '<% moment(tp.file.title, "YYYY-MM-DD").startOf("month").format("YYYY-MM-DD") %>' }, { name: "Get end of month from note title", example: '<% moment(tp.file.title, "YYYY-MM-DD").endOf("month").format("YYYY-MM-DD") %>' }] } }, file: { name: "file", description: "This module contains every internal function related to files.", functions: { content: { name: "content", description: "The string contents of the file at the time that Templater was executed. Manipulating this string will *not* update the current file.", definition: "tp.file.content", examples: [{ name: "Retrieve file content", example: "<% tp.file.content %>" }] }, create_new: { name: "create_new", description: "Creates a new file using a specified template or with a specified content.", definition: "tp.file.create_new(template: TFile \u23AE string, filename?: string, open_new: boolean = false, folder?: TFolder | string)", args: [{ name: "template", description: "Either the template used for the new file content, or the file content as a string. If it is the template to use, you retrieve it with `tp.file.find_tfile(TEMPLATENAME)`." }, { name: "filename", description: 'The filename of the new file, defaults to "Untitled".' }, { name: "open_new", description: "Whether to open or not the newly created file. Warning: if you use this option, since commands are executed asynchronously, the file can be opened first and then other commands are appended to that new file and not the previous file." }, { name: "folder", description: 'The folder to put the new file in, defaults to Obsidian\'s default location. If you want the file to appear in a different folder, specify it with `"PATH/TO/FOLDERNAME"` or `app.vault.getAbstractFileByPath("PATH/TO/FOLDERNAME")`.' }], examples: [{ name: "File creation", example: '<%* await tp.file.create_new("MyFileContent", "MyFilename") %>' }, { name: "File creation with template", example: '<%* await tp.file.create_new(tp.file.find_tfile("MyTemplate"), "MyFilename") %>' }, { name: "File creation and open created note", example: '<%* await tp.file.create_new("MyFileContent", "MyFilename", true) %>' }, { name: "File creation in current folder", example: '<%* await tp.file.create_new("MyFileContent", "MyFilename", false, tp.file.folder(true)) %>' }, { name: "File creation in specified folder with string path", example: '<%* await tp.file.create_new("MyFileContent", "MyFilename", false, "Path/To/MyFolder") %>' }, { name: "File creation in specified folder with TFolder", example: '<%* await tp.file.create_new("MyFileContent", "MyFilename", false, app.vault.getAbstractFileByPath("MyFolder")) %>' }, { name: "File creation and append link to current note", example: '[[<% (await tp.file.create_new("MyFileContent", "MyFilename")).basename %>]]' }] }, creation_date: { name: "creation_date", description: "Retrieves the file's creation date.", definition: 'tp.file.creation_date(format: string = "YYYY-MM-DD HH:mm")', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD HH:mm"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }], examples: [{ name: "File creation date", example: "<% tp.file.creation_date() %>" }, { name: "File creation date with format", example: '<% tp.file.creation_date("dddd Do MMMM YYYY HH:mm") %>' }] }, cursor: { name: "cursor", description: "Sets the cursor to this location after the template has been inserted. \n\nYou can navigate between the different cursors using the configured hotkey in Obsidian settings.\n", definition: "tp.file.cursor(order?: number)", args: [{ name: "order", description: "The order of the different cursors jump, e.g. it will jump from 1 to 2 to 3, and so on.\nIf you specify multiple tp.file.cursor with the same order, the editor will switch to multi-cursor.\n" }], examples: [{ name: "File cursor", example: "<% tp.file.cursor() %>" }, { name: "File multi-cursor", example: "<% tp.file.cursor(1) %>Content<% tp.file.cursor(1) %>" }] }, cursor_append: { name: "cursor_append", description: "Appends some content after the active cursor in the file.", definition: "tp.file.cursor_append(content: string)", args: [{ name: "content", description: "The content to append after the active cursor." }], examples: [{ name: "File cursor append", example: '<% tp.file.cursor_append("Some text") %>' }] }, exists: { name: "exists", description: "Check to see if a file exists by it's file path. The full path to the file, relative to the Vault and containing the extension, must be provided.", definition: "tp.file.exists(filepath: string)", args: [{ name: "filepath", description: "The full file path of the file we want to check existence for." }], examples: [{ name: "File existence", example: '<% await tp.file.exists("MyFolder/MyFile.md") %>' }, { name: "File existence of current file", example: '<% await tp.file.exists(tp.file.folder(true) + "/" + tp.file.title + ".md") %>' }] }, find_tfile: { name: "find_tfile", description: "Search for a file and returns its `TFile` instance.", definition: "tp.file.find_tfile(filename: string)", args: [{ name: "filename", description: "The filename we want to search and resolve as a `TFile`." }], examples: [{ name: "File find TFile", example: '<% tp.file.find_tfile("MyFile").basename %>' }] }, folder: { name: "folder", description: "Retrieves the file's folder name.", definition: "tp.file.folder(relative: boolean = false)", args: [{ name: "relative", description: "If set to `true`, appends the vault relative path to the folder name. If `false`, only retrieves name of folder. Defaults to `false`." }], examples: [{ name: "File folder (Folder)", example: "<% tp.file.folder() %>" }, { name: "File folder with relative path (Path/To/Folder)", example: "<% tp.file.folder(true) %>" }] }, include: { name: "include", description: "Includes the file's link content. Templates in the included content will be resolved.", definition: "tp.file.include(include_link: string \u23AE TFile)", args: [{ name: "include_link", description: 'The link to the file to include, e.g. `"[[MyFile]]"`, or a TFile object. Also supports sections or blocks inclusions.' }], examples: [{ name: "File include", example: '<% tp.file.include("[[Template1]]") %>' }, { name: "File include TFile", example: '<% tp.file.include(tp.file.find_tfile("MyFile")) %>' }, { name: "File include section", example: '<% tp.file.include("[[MyFile#Section1]]") %>' }, { name: "File include block", example: '<% tp.file.include("[[MyFile#^block1]]") %>' }] }, last_modified_date: { name: "last_modified_date", description: "Retrieves the file's last modification date.", definition: 'tp.file.last_modified_date(format: string = "YYYY-MM-DD HH:mm")', args: [{ name: "format", description: 'The format for the date. Defaults to `"YYYY-MM-DD HH:mm"`. Refer to [format reference](https://momentjs.com/docs/#/displaying/format/).' }], examples: [{ name: "File last modified date", example: "<% tp.file.last_modified_date() %>" }, { name: "File last modified date with format", example: '<% tp.file.last_modified_date("dddd Do MMMM YYYY HH:mm") %>' }] }, move: { name: "move", description: "Moves the file to the desired vault location.", definition: "tp.file.move(new_path: string, file_to_move?: TFile)", args: [{ name: "new_path", description: 'The new vault relative path of the file, without the file extension. Note: the new path needs to include the folder and the filename, e.g. `"/Notes/MyNote"`.' }, { name: "file_to_move", description: "The file to move, defaults to the current file." }], examples: [{ name: "File move", example: '<% await tp.file.move("/A/B/" + tp.file.title) %>' }, { name: "File move and rename", example: '<% await tp.file.move("/A/B/NewTitle") %>' }] }, path: { name: "path", description: "Retrieves the file's absolute path on the system.", definition: "tp.file.path(relative: boolean = false)", args: [{ name: "relative", description: "If set to `true`, only retrieves the vault's relative path." }], examples: [{ name: "File path", example: "<% tp.file.path() %>" }, { name: "File relative path (relative to vault root)", example: "<% tp.file.path(true) %>" }] }, rename: { name: "rename", description: "Renames the file (keeps the same file extension).", definition: "tp.file.rename(new_title: string)", args: [{ name: "new_title", description: "The new file title." }], examples: [{ name: "File rename", example: '<% await tp.file.rename("MyNewName") %>' }, { name: "File append a 2 to the file name", example: '<% await tp.file.rename(tp.file.title + "2") %>' }] }, selection: { name: "selection", description: "Retrieves the active file's text selection.", definition: "tp.file.selection()", examples: [{ name: "File selection", example: "<% tp.file.selection() %>" }] }, tags: { name: "tags", description: "Retrieves the file's tags (array of string).", definition: "tp.file.tags", examples: [{ name: "File tags", example: "<% tp.file.tags %>" }] }, title: { name: "title", definition: "tp.file.title", description: "Retrieves the file's title.", examples: [{ name: "File title", example: "<% tp.file.title %>" }, { name: "Strip the Zettelkasten ID of title (if space separated)", example: '<% tp.file.title.split(" ")[1] %>' }] } } }, frontmatter: { name: "frontmatter", description: "This modules exposes all the frontmatter variables of a file as variables." }, hooks: { name: "hooks", description: "This module exposes hooks that allow you to execute code when a Templater event occurs.", functions: { on_all_templates_executed: { name: "on_all_templates_executed", description: "Hooks into when all actively running templates have finished executing. Most of the time this will be a single template, unless you are using `tp.file.include` or `tp.file.create_new`.\n\nMultiple invokations of this method will have their callback functions run in parallel.", definition: "tp.hooks.on_all_templates_executed(callback_function: () => any)", args: [{ name: "callback_function", description: "Callback function that will be executed when all actively running templates have finished executing." }] } } }, obsidian: { name: "obsidian", description: "This module exposes all the functions and classes from the Obsidian API." }, system: { name: "system", description: "This module contains system related functions.", functions: { clipboard: { name: "clipboard", description: "Retrieves the clipboard's content.", definition: "tp.system.clipboard()", examples: [{ name: "Clipboard", example: "<% tp.system.clipboard() %>" }] }, prompt: { name: "prompt", description: "Spawns a prompt modal and returns the user's input.", definition: "tp.system.prompt(prompt_text?: string, default_value?: string, throw_on_cancel: boolean = false, multiline?: boolean = false)", args: [{ name: "prompt_text", description: "Text placed above the input field." }, { name: "default_value", description: "A default value for the input field." }, { name: "throw_on_cancel", description: "Throws an error if the prompt is canceled, instead of returning a `null` value." }, { name: "multiline", description: "If set to `true`, the input field will be a multiline textarea. Defaults to `false`." }], examples: [{ name: "Prompt", example: '<% tp.system.prompt("Please enter a value") %>' }, { name: "Prompt with default value", example: '<% tp.system.prompt("What is your mood today?", "happy") %>' }, { name: "Multiline prompt", example: '<% tp.system.prompt("What is your mood today?", null, false, true) %>' }] }, suggester: { name: "suggester", description: "Spawns a suggester prompt and returns the user's chosen item.", definition: 'tp.system.suggester(text_items: string[] \u23AE ((item: T) => string), items: T[], throw_on_cancel: boolean = false, placeholder: string = "", limit?: number = undefined)', args: [{ name: "text_items", description: "Array of strings representing the text that will be displayed for each item in the suggester prompt. This can also be a function that maps an item to its text representation." }, { name: "items", description: "Array containing the values of each item in the correct order." }, { name: "throw_on_cancel", description: "Throws an error if the prompt is canceled, instead of returning a `null` value." }, { name: "placeholder", description: "Placeholder string of the prompt." }, { name: "limit", description: "Limit the number of items rendered at once (useful to improve performance when displaying large lists)." }], examples: [{ name: "Suggester", example: '<% tp.system.suggester(["Happy", "Sad", "Confused"], ["Happy", "Sad", "Confused"]) %>' }, { name: "Suggester with mapping function (same as above example)", example: '<% tp.system.suggester((item) => item, ["Happy", "Sad", "Confused"]) %>' }, { name: "Suggester for files", example: "[[<% (await tp.system.suggester((item) => item.basename, app.vault.getMarkdownFiles())).basename %>]]" }, { name: "Suggester for tags", example: '<% tp.system.suggester(item => item, Object.keys(app.metadataCache.getTags()).map(x => x.replace("#", ""))) %>' }] } } }, web: { name: "web", description: "This modules contains every internal function related to the web (making web requests).", functions: { daily_quote: { name: "daily_quote", description: "Retrieves and parses the daily quote from the API `https://api.quotable.io` as a callout.", definition: "tp.web.daily_quote()", examples: [{ name: "Daily quote", example: "<% tp.web.daily_quote() %>" }] }, random_picture: { name: "random_picture", description: "Gets a random image from `https://unsplash.com/`.", definition: "tp.web.random_picture(size?: string, query?: string, include_size?: boolean)", args: [{ name: "size", description: "Image size in the format `x`." }, { name: "query", description: "Limits selection to photos matching a search term. Multiple search terms can be passed separated by a comma." }, { name: "include_size", description: "Optional argument to include the specified size in the image link markdown. Defaults to false." }], examples: [{ name: "Random picture", example: "<% tp.web.random_picture() %>" }, { name: "Random picture with size", example: '<% tp.web.random_picture("200x200") %>' }, { name: "Random picture with size and query", example: '<% tp.web.random_picture("200x200", "landscape,water") %>' }] } } } }; +var documentation_default = { tp }; + +// src/editor/TpDocumentation.ts +var module_names = [ + "config", + "date", + "file", + "frontmatter", + "hooks", + "obsidian", + "system", + "user", + "web" +]; +var module_names_checker = new Set(module_names); +function is_module_name(x) { + return typeof x === "string" && module_names_checker.has(x); +} +function is_function_documentation(x) { + if (x.definition) { + return true; + } + return false; +} +var Documentation = class { + constructor(settings) { + this.settings = settings; + this.documentation = documentation_default; + } + get_all_modules_documentation() { + return Object.values(this.documentation.tp); + } + get_all_functions_documentation(module_name) { + if (module_name === "user") { + if (!this.settings || !this.settings.user_scripts_folder) + return; + const files = errorWrapperSync(() => get_tfiles_from_folder(this.settings.user_scripts_folder), `User Scripts folder doesn't exist`); + if (!files || files.length === 0) + return; + return files.reduce((processedFiles, file) => { + if (file.extension !== "js") + return processedFiles; + return [ + ...processedFiles, + { + name: file.basename, + definition: "", + description: "", + example: "" + } + ]; + }, []); + } + if (!this.documentation.tp[module_name].functions) { + return; + } + return Object.values(this.documentation.tp[module_name].functions); + } + get_module_documentation(module_name) { + return this.documentation.tp[module_name]; + } + get_function_documentation(module_name, function_name) { + return this.documentation.tp[module_name].functions[function_name]; + } + get_argument_documentation(module_name, function_name, argument_name) { + const function_doc = this.get_function_documentation(module_name, function_name); + if (!function_doc || !function_doc.args) { + return null; + } + return function_doc.args[argument_name]; + } +}; + +// src/editor/Autocomplete.ts +var Autocomplete = class extends import_obsidian15.EditorSuggest { + constructor(settings) { + super(app); + this.tp_keyword_regex = /tp\.(?[a-z]*)?(?\.(?[a-z_]*)?)?$/; + this.documentation = new Documentation(settings); + } + onTrigger(cursor, editor, _file) { + const range = editor.getRange({ line: cursor.line, ch: 0 }, { line: cursor.line, ch: cursor.ch }); + const match = this.tp_keyword_regex.exec(range); + if (!match) { + return null; + } + let query; + const module_name = match.groups && match.groups["module"] || ""; + this.module_name = module_name; + if (match.groups && match.groups["fn_trigger"]) { + if (module_name == "" || !is_module_name(module_name)) { + return null; + } + this.function_trigger = true; + this.function_name = match.groups["fn"] || ""; + query = this.function_name; + } else { + this.function_trigger = false; + query = this.module_name; + } + const trigger_info = { + start: { line: cursor.line, ch: cursor.ch - query.length }, + end: { line: cursor.line, ch: cursor.ch }, + query + }; + this.latest_trigger_info = trigger_info; + return trigger_info; + } + getSuggestions(context) { + let suggestions; + if (this.module_name && this.function_trigger) { + suggestions = this.documentation.get_all_functions_documentation(this.module_name); + } else { + suggestions = this.documentation.get_all_modules_documentation(); + } + if (!suggestions) { + return []; + } + return suggestions.filter((s) => s.name.startsWith(context.query)); + } + renderSuggestion(value, el) { + el.createEl("b", { text: value.name }); + el.createEl("br"); + if (this.function_trigger && is_function_documentation(value)) { + el.createEl("code", { text: value.definition }); + } + if (value.description) { + el.createEl("div", { text: value.description }); + } + } + selectSuggestion(value, _evt) { + const active_editor = app.workspace.activeEditor; + if (!active_editor || !active_editor.editor) { + return; + } + active_editor.editor.replaceRange(value.name, this.latest_trigger_info.start, this.latest_trigger_info.end); + if (this.latest_trigger_info.start.ch == this.latest_trigger_info.end.ch) { + const cursor_pos = this.latest_trigger_info.end; + cursor_pos.ch += value.name.length; + active_editor.editor.setCursor(cursor_pos); + } + } +}; + +// src/editor/mode/javascript.js +(function(mod) { + mod(window.CodeMirror); +})(function(CodeMirror) { + "use strict"; + CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + var keywords = function() { + function kw(type2) { + return { type: type2, style: "keyword" }; + } + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); + var operator = kw("operator"), atom = { type: "atom", style: "atom" }; + return { + if: kw("if"), + while: A, + with: A, + else: B, + do: B, + try: B, + finally: B, + return: D, + break: D, + continue: D, + new: kw("new"), + delete: C, + void: C, + throw: C, + debugger: kw("debugger"), + var: kw("var"), + const: kw("var"), + let: kw("var"), + function: kw("function"), + catch: kw("catch"), + for: kw("for"), + switch: kw("switch"), + case: kw("case"), + default: kw("default"), + in: operator, + typeof: operator, + instanceof: operator, + true: atom, + false: atom, + null: atom, + undefined: atom, + NaN: atom, + Infinity: atom, + this: kw("this"), + class: kw("class"), + super: kw("atom"), + yield: C, + export: kw("export"), + import: kw("import"), + extends: C, + await: C + }; + }(); + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) + return; + if (next == "[") + inSet = true; + else if (inSet && next == "]") + inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + var type, content; + function ret(tp2, style, cont2) { + type = tp2; + content = cont2; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property"); + } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") + stream.eat("="); + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch); + if (ch == ">") + stream.eat(ch); + } + } + if (ch == "?" && stream.eat(".")) + return ret("."); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(); + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word]; + return ret(kw.type, kw.style, word); + } + if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) + return ret("async", "keyword", word); + } + return ret("variable", "variable", word); + } + } + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) + break; + escaped = !escaped && next == "\\"; + } + if (!escaped) + state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = ch == "*"; + } + return ret("comment", "comment"); + } + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + var brackets = "([{}])"; + function findFatArrow(stream, state) { + if (state.fatArrowAt) + state.fatArrowAt = null; + var arrow2 = stream.string.indexOf("=>", stream.start); + if (arrow2 < 0) + return; + if (isTS) { + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow2)); + if (m) + arrow2 = m.index; + } + var depth = 0, sawSomething = false; + for (var pos = arrow2 - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { + ++pos; + break; + } + if (--depth == 0) { + if (ch == "(") + sawSomething = true; + break; + } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (; ; --pos) { + if (pos == 0) + return; + var next = stream.string.charAt(pos - 1); + if (next == ch && stream.string.charAt(pos - 2) != "\\") { + pos--; + break; + } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) + state.fatArrowAt = pos; + } + var atomicTypes = { + atom: true, + number: true, + variable: true, + string: true, + regexp: true, + this: true, + import: true, + "jsonld-keyword": true + }; + function JSLexical(indented, column, type2, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type2; + this.prev = prev; + this.info = info; + if (align != null) + this.align = align; + } + function inScope(state, varname) { + if (!trackScope) + return false; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) + return true; + for (var cx2 = state.context; cx2; cx2 = cx2.prev) { + for (var v = cx2.vars; v; v = v.next) + if (v.name == varname) + return true; + } + } + function parseJS(state, style, type2, content2, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + cx.marked = null, cx.cc = cc; + cx.style = style; + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + while (true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type2, content2)) { + while (cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) + return cx.marked; + if (type2 == "variable" && inScope(state, content2)) + return "variable-2"; + return style; + } + } + } + var cx = { state: null, column: null, marked: null, cc: null }; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) + cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) + if (v.name == name) + return true; + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) + return; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + var newContext = registerVarScoped(varname, state.context); + if (newContext != null) { + state.context = newContext; + return; + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars); + return; + } + } + if (parserConfig.globalVars && !inList(varname, state.globalVars)) + state.globalVars = new Var(varname, state.globalVars); + } + function registerVarScoped(varname, context) { + if (!context) { + return null; + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev); + if (!inner) + return null; + if (inner == context.prev) + return context; + return new Context(inner, context.vars, true); + } else if (inList(varname, context.vars)) { + return context; + } else { + return new Context(context.prev, new Var(varname, context.vars), false); + } + } + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; + } + function Context(prev, vars, block2) { + this.prev = prev; + this.vars = vars; + this.block = block2; + } + function Var(name, next) { + this.name = name; + this.next = next; + } + var defaultVars = new Var("this", new Var("arguments", null)); + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false); + cx.state.localVars = defaultVars; + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true); + cx.state.localVars = null; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + popcontext.lex = true; + function pushlex(type2, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") + indent = state.lexical.indented; + else + for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + function expect(wanted) { + function exp(type2) { + if (type2 == wanted) + return cont(); + else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") + return pass(); + else + return cont(exp); + } + return exp; + } + function statement(type2, value) { + if (type2 == "var") + return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type2 == "keyword a") + return cont(pushlex("form"), parenExpr, statement, poplex); + if (type2 == "keyword b") + return cont(pushlex("form"), statement, poplex); + if (type2 == "keyword d") + return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type2 == "debugger") + return cont(expect(";")); + if (type2 == "{") + return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type2 == ";") + return cont(); + if (type2 == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type2 == "function") + return cont(functiondef); + if (type2 == "for") + return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); + } + if (type2 == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword"; + return cont(statement); + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword"; + if (value == "enum") + return cont(enumdef); + else if (value == "type") + return cont(typename, expect("operator"), typeexpr, expect(";")); + else + return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); + } else if (isTS && value == "namespace") { + cx.marked = "keyword"; + return cont(pushlex("form"), expression, statement, poplex); + } else if (isTS && value == "abstract") { + cx.marked = "keyword"; + return cont(statement); + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type2 == "switch") + return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); + if (type2 == "case") + return cont(expression, expect(":")); + if (type2 == "default") + return cont(expect(":")); + if (type2 == "catch") + return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type2 == "export") + return cont(pushlex("stat"), afterExport, poplex); + if (type2 == "import") + return cont(pushlex("stat"), afterImport, poplex); + if (type2 == "async") + return cont(statement); + if (value == "@") + return cont(expression, statement); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type2) { + if (type2 == "(") + return cont(funarg, expect(")")); + } + function expression(type2, value) { + return expressionInner(type2, value, false); + } + function expressionNoComma(type2, value) { + return expressionInner(type2, value, true); + } + function parenExpr(type2) { + if (type2 != "(") + return pass(); + return cont(pushlex(")"), maybeexpression, expect(")"), poplex); + } + function expressionInner(type2, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type2 == "(") + return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); + else if (type2 == "variable") + return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type2)) + return cont(maybeop); + if (type2 == "function") + return cont(functiondef, maybeop); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form"), classExpression, poplex); + } + if (type2 == "keyword c" || type2 == "async") + return cont(noComma ? expressionNoComma : expression); + if (type2 == "(") + return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type2 == "operator" || type2 == "spread") + return cont(noComma ? expressionNoComma : expression); + if (type2 == "[") + return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type2 == "{") + return contCommasep(objprop, "}", null, maybeop); + if (type2 == "quasi") + return pass(quasi, maybeop); + if (type2 == "new") + return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type2) { + if (type2.match(/[;\}\)\],]/)) + return pass(); + return pass(expression); + } + function maybeoperatorComma(type2, value) { + if (type2 == ",") + return cont(maybeexpression); + return maybeoperatorNoComma(type2, value, false); + } + function maybeoperatorNoComma(type2, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type2 == "=>") + return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type2 == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") + return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") + return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type2 == "quasi") { + return pass(quasi, me); + } + if (type2 == ";") + return; + if (type2 == "(") + return contCommasep(expressionNoComma, ")", "call", me); + if (type2 == ".") + return cont(property, me); + if (type2 == "[") + return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { + cx.marked = "keyword"; + return cont(typeexpr, me); + } + if (type2 == "regexp") { + cx.state.lastType = cx.marked = "operator"; + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); + return cont(expr); + } + } + function quasi(type2, value) { + if (type2 != "quasi") + return pass(); + if (value.slice(value.length - 2) != "${") + return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expression); + } + function arrowBodyNoComma(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type2) { + if (type2 == ".") + return cont(noComma ? targetNoComma : target); + else if (type2 == "variable" && isTS) + return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma); + else + return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorComma); + } + } + function targetNoComma(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorNoComma); + } + } + function maybelabel(type2) { + if (type2 == ":") + return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type2) { + if (type2 == "variable") { + cx.marked = "property"; + return cont(); + } + } + function objprop(type2, value) { + if (type2 == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") + return cont(getterSetter); + var m; + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) + cx.state.fatArrowAt = cx.stream.pos + m[0].length; + return cont(afterprop); + } else if (type2 == "number" || type2 == "string") { + cx.marked = jsonldMode ? "property" : cx.style + " property"; + return cont(afterprop); + } else if (type2 == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type2 == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == ":") { + return pass(afterprop); + } + } + function getterSetter(type2) { + if (type2 != "variable") + return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type2) { + if (type2 == ":") + return cont(expressionNoComma); + if (type2 == "(") + return pass(functiondef); + } + function commasep(what, end2, sep) { + function proceed(type2, value) { + if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") + lex.pos = (lex.pos || 0) + 1; + return cont(function(type3, value2) { + if (type3 == end2 || value2 == end2) + return pass(); + return pass(what); + }, proceed); + } + if (type2 == end2 || value == end2) + return cont(); + if (sep && sep.indexOf(";") > -1) + return pass(what); + return cont(expect(end2)); + } + return function(type2, value) { + if (type2 == end2 || value == end2) + return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end2, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end2, info), commasep(what, end2), poplex); + } + function block(type2) { + if (type2 == "}") + return cont(); + return pass(statement, block); + } + function maybetype(type2, value) { + if (isTS) { + if (type2 == ":") + return cont(typeexpr); + if (value == "?") + return cont(maybetype); + } + } + function maybetypeOrIn(type2, value) { + if (isTS && (type2 == ":" || value == "in")) + return cont(typeexpr); + } + function mayberettype(type2) { + if (isTS && type2 == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) + return cont(expression, isKW, typeexpr); + else + return cont(typeexpr); + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword"; + return cont(); + } + } + function typeexpr(type2, value) { + if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { + cx.marked = "keyword"; + return cont(value == "typeof" ? expressionNoComma : typeexpr); + } + if (type2 == "variable" || value == "void") { + cx.marked = "type"; + return cont(afterType); + } + if (value == "|" || value == "&") + return cont(typeexpr); + if (type2 == "string" || type2 == "number" || type2 == "atom") + return cont(afterType); + if (type2 == "[") + return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); + if (type2 == "{") + return cont(pushlex("}"), typeprops, poplex, afterType); + if (type2 == "(") + return cont(commasep(typearg, ")"), maybeReturnType, afterType); + if (type2 == "<") + return cont(commasep(typeexpr, ">"), typeexpr); + if (type2 == "quasi") { + return pass(quasiType, afterType); + } + } + function maybeReturnType(type2) { + if (type2 == "=>") + return cont(typeexpr); + } + function typeprops(type2) { + if (type2.match(/[\}\)\]]/)) + return cont(); + if (type2 == "," || type2 == ";") + return cont(typeprops); + return pass(typeprop, typeprops); + } + function typeprop(type2, value) { + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(typeprop); + } else if (value == "?" || type2 == "number" || type2 == "string") { + return cont(typeprop); + } else if (type2 == ":") { + return cont(typeexpr); + } else if (type2 == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); + } else if (type2 == "(") { + return pass(functiondecl, typeprop); + } else if (!type2.match(/[;\}\)\],]/)) { + return cont(); + } + } + function quasiType(type2, value) { + if (type2 != "quasi") + return pass(); + if (value.slice(value.length - 2) != "${") + return cont(quasiType); + return cont(typeexpr, continueQuasiType); + } + function continueQuasiType(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); + } + } + function typearg(type2, value) { + if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") + return cont(typearg); + if (type2 == ":") + return cont(typeexpr); + if (type2 == "spread") + return cont(typearg); + return pass(typeexpr); + } + function afterType(type2, value) { + if (value == "<") + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + if (value == "|" || type2 == "." || value == "&") + return cont(typeexpr); + if (type2 == "[") + return cont(typeexpr, expect("]"), afterType); + if (value == "extends" || value == "implements") { + cx.marked = "keyword"; + return cont(typeexpr); + } + if (value == "?") + return cont(typeexpr, expect(":"), typeexpr); + } + function maybeTypeArgs(_, value) { + if (value == "<") + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault); + } + function maybeTypeDefault(_, value) { + if (value == "=") + return cont(typeexpr); + } + function vardef(_, value) { + if (value == "enum") { + cx.marked = "keyword"; + return cont(enumdef); + } + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type2, value) { + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(pattern); + } + if (type2 == "variable") { + register(value); + return cont(); + } + if (type2 == "spread") + return cont(pattern); + if (type2 == "[") + return contCommasep(eltpattern, "]"); + if (type2 == "{") + return contCommasep(proppattern, "}"); + } + function proppattern(type2, value) { + if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type2 == "variable") + cx.marked = "property"; + if (type2 == "spread") + return cont(pattern); + if (type2 == "}") + return pass(); + if (type2 == "[") + return cont(expression, expect("]"), expect(":"), proppattern); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") + return cont(expressionNoComma); + } + function vardefCont(type2) { + if (type2 == ",") + return cont(vardef); + } + function maybeelse(type2, value) { + if (type2 == "keyword b" && value == "else") + return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type2, value) { + if (value == "await") + return cont(forspec); + if (type2 == "(") + return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type2) { + if (type2 == "var") + return cont(vardef, forspec2); + if (type2 == "variable") + return cont(forspec2); + return pass(forspec2); + } + function forspec2(type2, value) { + if (type2 == ")") + return cont(); + if (type2 == ";") + return cont(forspec2); + if (value == "in" || value == "of") { + cx.marked = "keyword"; + return cont(expression, forspec2); + } + return pass(expression, forspec2); + } + function functiondef(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondef); + } + if (type2 == "variable") { + register(value); + return cont(functiondef); + } + if (type2 == "(") + return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") + return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); + } + function functiondecl(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondecl); + } + if (type2 == "variable") { + register(value); + return cont(functiondecl); + } + if (type2 == "(") + return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") + return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); + } + function typename(type2, value) { + if (type2 == "keyword" || type2 == "variable") { + cx.marked = "type"; + return cont(typename); + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + } + } + function funarg(type2, value) { + if (value == "@") + cont(expression, funarg); + if (type2 == "spread") + return cont(funarg); + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(funarg); + } + if (isTS && type2 == "this") + return cont(maybetype, maybeAssign); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type2, value) { + if (type2 == "variable") + return className(type2, value); + return classNameAfter(type2, value); + } + function className(type2, value) { + if (type2 == "variable") { + register(value); + return cont(classNameAfter); + } + } + function classNameAfter(type2, value) { + if (value == "<") + return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); + if (value == "extends" || value == "implements" || isTS && type2 == ",") { + if (value == "implements") + cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type2 == "{") + return cont(pushlex("}"), classBody, poplex); + } + function classBody(type2, value) { + if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type2 == "number" || type2 == "string") + return cont(classfield, classBody); + if (type2 == "[") + return cont(expression, maybetype, expect("]"), classfield, classBody); + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type2 == "(") + return pass(functiondecl, classBody); + if (type2 == ";" || type2 == ",") + return cont(classBody); + if (type2 == "}") + return cont(); + if (value == "@") + return cont(expression, classBody); + } + function classfield(type2, value) { + if (value == "!") + return cont(classfield); + if (value == "?") + return cont(classfield); + if (type2 == ":") + return cont(typeexpr, maybeAssign); + if (value == "=") + return cont(expressionNoComma); + var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"; + return pass(isInterface ? functiondecl : functiondef); + } + function afterExport(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(maybeFrom, expect(";")); + } + if (value == "default") { + cx.marked = "keyword"; + return cont(expression, expect(";")); + } + if (type2 == "{") + return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type2, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(expect("variable")); + } + if (type2 == "variable") + return pass(expressionNoComma, exportField); + } + function afterImport(type2) { + if (type2 == "string") + return cont(); + if (type2 == "(") + return pass(expression); + if (type2 == ".") + return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type2, value) { + if (type2 == "{") + return contCommasep(importSpec, "}"); + if (type2 == "variable") + register(value); + if (value == "*") + cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type2) { + if (type2 == ",") + return cont(importSpec, maybeMoreImports); + } + function maybeAs(_type, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(importSpec); + } + } + function maybeFrom(_type, value) { + if (value == "from") { + cx.marked = "keyword"; + return cont(expression); + } + } + function arrayLiteral(type2) { + if (type2 == "]") + return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); + } + function enummember() { + return pass(pattern, maybeAssign); + } + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); + } + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); + } + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) + return null; + var style = state.tokenize(stream, state); + if (type == "comment") + return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + indent: function(state, textAfter) { + if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) + return CodeMirror.Pass; + if (state.tokenize != tokenBase) + return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top2; + if (!/^\s*else\b/.test(textAfter)) + for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) + lexical = lexical.prev; + else if (c != maybeelse && c != popcontext) + break; + } + while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top2 = state.cc[state.cc.length - 1]) && (top2 == maybeoperatorComma || top2 == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type2 = lexical.type, closing = firstChar == type2; + if (type2 == "vardef") + return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); + else if (type2 == "form" && firstChar == "{") + return lexical.indented; + else if (type2 == "form") + return lexical.indented + indentUnit; + else if (type2 == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) + return lexical.column + (closing ? 0 : 1); + else + return lexical.indented + (closing ? 0 : indentUnit); + }, + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: jsonMode ? "json" : "javascript", + jsonldMode, + jsonMode, + expressionAllowed, + skipExpression: function(state) { + parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); + } + }; + }); + CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("text/ecmascript", "javascript"); + CodeMirror.defineMIME("application/javascript", "javascript"); + CodeMirror.defineMIME("application/x-javascript", "javascript"); + CodeMirror.defineMIME("application/ecmascript", "javascript"); + CodeMirror.defineMIME("application/json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/x-json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/manifest+json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/ld+json", { + name: "javascript", + jsonld: true + }); + CodeMirror.defineMIME("text/typescript", { + name: "javascript", + typescript: true + }); + CodeMirror.defineMIME("application/typescript", { + name: "javascript", + typescript: true + }); +}); + +// src/editor/mode/custom_overlay.js +(function(mod) { + mod(window.CodeMirror); +})(function(CodeMirror) { + "use strict"; + CodeMirror.customOverlayMode = function(base, overlay, combine) { + return { + startState: function() { + return { + base: CodeMirror.startState(base), + overlay: CodeMirror.startState(overlay), + basePos: 0, + baseCur: null, + overlayPos: 0, + overlayCur: null, + streamSeen: null + }; + }, + copyState: function(state) { + return { + base: CodeMirror.copyState(base, state.base), + overlay: CodeMirror.copyState(overlay, state.overlay), + basePos: state.basePos, + baseCur: null, + overlayPos: state.overlayPos, + overlayCur: null + }; + }, + token: function(stream, state) { + if (stream != state.streamSeen || Math.min(state.basePos, state.overlayPos) < stream.start) { + state.streamSeen = stream; + state.basePos = state.overlayPos = stream.start; + } + if (stream.start == state.basePos) { + state.baseCur = base.token(stream, state.base); + state.basePos = stream.pos; + } + if (stream.start == state.overlayPos) { + stream.pos = stream.start; + state.overlayCur = overlay.token(stream, state.overlay); + state.overlayPos = stream.pos; + } + stream.pos = Math.min(state.basePos, state.overlayPos); + if (state.baseCur && state.overlayCur && state.baseCur.contains("line-HyperMD-codeblock")) { + state.overlayCur = state.overlayCur.replace("line-templater-inline", ""); + state.overlayCur += ` line-background-HyperMD-codeblock-bg`; + } + if (state.overlayCur == null) + return state.baseCur; + else if (state.baseCur != null && state.overlay.combineTokens || combine && state.overlay.combineTokens == null) + return state.baseCur + " " + state.overlayCur; + else + return state.overlayCur; + }, + indent: base.indent && function(state, textAfter, line) { + return base.indent(state.base, textAfter, line); + }, + electricChars: base.electricChars, + innerMode: function(state) { + return { state: state.base, mode: base }; + }, + blankLine: function(state) { + let baseToken, overlayToken; + if (base.blankLine) + baseToken = base.blankLine(state.base); + if (overlay.blankLine) + overlayToken = overlay.blankLine(state.overlay); + return overlayToken == null ? baseToken : combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken; + } + }; + }; +}); + +// src/editor/Editor.ts +var import_language = __toModule(require("@codemirror/language")); +var import_state = __toModule(require("@codemirror/state")); +var TEMPLATER_MODE_NAME = "templater"; +var TP_CMD_TOKEN_CLASS = "templater-command"; +var TP_INLINE_CLASS = "templater-inline"; +var TP_OPENING_TAG_TOKEN_CLASS = "templater-opening-tag"; +var TP_CLOSING_TAG_TOKEN_CLASS = "templater-closing-tag"; +var TP_INTERPOLATION_TAG_TOKEN_CLASS = "templater-interpolation-tag"; +var TP_EXEC_TAG_TOKEN_CLASS = "templater-execution-tag"; +var Editor2 = class { + constructor(plugin) { + this.plugin = plugin; + this.cursor_jumper = new CursorJumper(); + this.activeEditorExtensions = []; + } + desktopShouldHighlight() { + return import_obsidian16.Platform.isDesktopApp && this.plugin.settings.syntax_highlighting; + } + mobileShouldHighlight() { + return import_obsidian16.Platform.isMobileApp && this.plugin.settings.syntax_highlighting_mobile; + } + async setup() { + this.plugin.registerEditorSuggest(new Autocomplete(this.plugin.settings)); + await this.registerCodeMirrorMode(); + this.templaterLanguage = import_state.Prec.high(import_language.StreamLanguage.define(window.CodeMirror.getMode({}, TEMPLATER_MODE_NAME))); + if (this.templaterLanguage === void 0) { + log_error(new TemplaterError("Unable to enable syntax highlighting. Could not define language.")); + } + this.plugin.registerEditorExtension(this.activeEditorExtensions); + if (this.desktopShouldHighlight() || this.mobileShouldHighlight()) { + await this.enable_highlighter(); + } + } + async enable_highlighter() { + if (this.activeEditorExtensions.length === 0 && this.templaterLanguage) { + this.activeEditorExtensions.push(this.templaterLanguage); + this.plugin.app.workspace.updateOptions(); + } + } + async disable_highlighter() { + if (this.activeEditorExtensions.length > 0) { + this.activeEditorExtensions.pop(); + this.plugin.app.workspace.updateOptions(); + } + } + async jump_to_next_cursor_location(file = null, auto_jump = false) { + if (auto_jump && !this.plugin.settings.auto_jump_to_cursor) { + return; + } + if (file && get_active_file(this.plugin.app) !== file) { + return; + } + await this.cursor_jumper.jump_to_next_cursor_location(); + } + async registerCodeMirrorMode() { + if (!this.desktopShouldHighlight() && !this.mobileShouldHighlight()) { + return; + } + const js_mode = window.CodeMirror.getMode({}, "javascript"); + if (js_mode.name === "null") { + log_error(new TemplaterError("Javascript syntax mode couldn't be found, can't enable syntax highlighting.")); + return; + } + const overlay_mode = window.CodeMirror.customOverlayMode; + if (overlay_mode == null) { + log_error(new TemplaterError("Couldn't find customOverlayMode, can't enable syntax highlighting.")); + return; + } + window.CodeMirror.defineMode(TEMPLATER_MODE_NAME, function(config) { + const templaterOverlay = { + startState: function() { + const js_state = window.CodeMirror.startState(js_mode); + return { + ...js_state, + inCommand: false, + tag_class: "", + freeLine: false + }; + }, + copyState: function(state) { + const js_state = window.CodeMirror.startState(js_mode); + const new_state = { + ...js_state, + inCommand: state.inCommand, + tag_class: state.tag_class, + freeLine: state.freeLine + }; + return new_state; + }, + blankLine: function(state) { + if (state.inCommand) { + return `line-background-templater-command-bg`; + } + return null; + }, + token: function(stream, state) { + if (stream.sol() && state.inCommand) { + state.freeLine = true; + } + if (state.inCommand) { + let keywords = ""; + if (stream.match(/[-_]{0,1}%>/, true)) { + state.inCommand = false; + state.freeLine = false; + const tag_class = state.tag_class; + state.tag_class = ""; + return `line-${TP_INLINE_CLASS} ${TP_CMD_TOKEN_CLASS} ${TP_CLOSING_TAG_TOKEN_CLASS} ${tag_class}`; + } + const js_result = js_mode.token && js_mode.token(stream, state); + if (stream.peek() == null && state.freeLine) { + keywords += ` line-background-templater-command-bg`; + } + if (!state.freeLine) { + keywords += ` line-${TP_INLINE_CLASS}`; + } + return `${keywords} ${TP_CMD_TOKEN_CLASS} ${js_result}`; + } + const match = stream.match(/<%[-_]{0,1}\s*([*+]{0,1})/, true); + if (match != null) { + switch (match[1]) { + case "*": + state.tag_class = TP_EXEC_TAG_TOKEN_CLASS; + break; + default: + state.tag_class = TP_INTERPOLATION_TAG_TOKEN_CLASS; + break; + } + state.inCommand = true; + return `line-${TP_INLINE_CLASS} ${TP_CMD_TOKEN_CLASS} ${TP_OPENING_TAG_TOKEN_CLASS} ${state.tag_class}`; + } + while (stream.next() != null && !stream.match(/<%/, false)) + ; + return null; + } + }; + return overlay_mode(window.CodeMirror.getMode(config, "hypermd"), templaterOverlay); + }); + } +}; + +// src/main.ts +var TemplaterPlugin = class extends import_obsidian17.Plugin { + async onload() { + await this.load_settings(); + this.templater = new Templater(this); + await this.templater.setup(); + this.editor_handler = new Editor2(this); + await this.editor_handler.setup(); + this.fuzzy_suggester = new FuzzySuggester(this); + this.event_handler = new EventHandler(this, this.templater, this.settings); + this.event_handler.setup(); + this.command_handler = new CommandHandler(this); + this.command_handler.setup(); + (0, import_obsidian17.addIcon)("templater-icon", ICON_DATA); + this.addRibbonIcon("templater-icon", "Templater", async () => { + this.fuzzy_suggester.insert_template(); + }).setAttribute("id", "rb-templater-icon"); + this.addSettingTab(new TemplaterSettingTab(this)); + app.workspace.onLayoutReady(() => { + this.templater.execute_startup_scripts(); + }); + } + onunload() { + this.templater.functions_generator.teardown(); + } + async save_settings() { + await this.saveData(this.settings); + } + async load_settings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } +}; diff --git a/src/content/blog/.obsidian/plugins/templater-obsidian/manifest.json b/src/content/blog/.obsidian/plugins/templater-obsidian/manifest.json new file mode 100644 index 0000000..2c43dad --- /dev/null +++ b/src/content/blog/.obsidian/plugins/templater-obsidian/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "templater-obsidian", + "name": "Templater", + "version": "2.4.1", + "description": "Create and use templates", + "minAppVersion": "1.5.0", + "author": "SilentVoid", + "authorUrl": "https://github.com/SilentVoid13", + "helpUrl": "https://silentvoid13.github.io/Templater/", + "isDesktopOnly": false +} diff --git a/src/content/blog/.obsidian/plugins/templater-obsidian/styles.css b/src/content/blog/.obsidian/plugins/templater-obsidian/styles.css new file mode 100644 index 0000000..c9ece98 --- /dev/null +++ b/src/content/blog/.obsidian/plugins/templater-obsidian/styles.css @@ -0,0 +1,220 @@ +.templater_search { + width: calc(100% - 20px); +} + +.templater_div { + border-top: 1px solid var(--background-modifier-border); +} + +.templater_div > .setting-item { + border-top: none !important; + align-self: center; +} + +.templater_div > .setting-item > .setting-item-control { + justify-content: space-around; + padding: 0; + width: 100%; +} + +.templater_div + > .setting-item + > .setting-item-control + > .setting-editor-extra-setting-button { + align-self: center; +} + +.templater_donating { + margin: 10px; +} + +.templater_title { + margin: 0; + padding: 0; + margin-top: 5px; + text-align: center; +} + +.templater_template { + align-self: center; + margin-left: 5px; + margin-right: 5px; + width: 70%; +} + +.templater_cmd { + margin-left: 5px; + margin-right: 5px; + font-size: 14px; + width: 100%; +} + +.templater_div2 > .setting-item { + align-content: center; + justify-content: center; +} + +.templater-prompt-div { + display: flex; +} + +.templater-prompt-form { + display: flex; + flex-grow: 1; +} + +.templater-prompt-input { + flex-grow: 1; +} + +.templater-button-div { + display: flex; + flex-direction: column; + align-items: center; + margin-top: 1rem; +} + +textarea.templater-prompt-input { + height: 10rem; +} + +textarea.templater-prompt-input:focus { + border-color: var(--interactive-accent); +} + +.cm-s-obsidian .templater-command-bg { + left: 0px; + right: 0px; + background-color: var(--background-primary-alt); +} + +.cm-s-obsidian .cm-templater-command { + font-size: 0.85em; + font-family: var(--font-monospace); + line-height: 1.3; +} + +.cm-s-obsidian .templater-inline .cm-templater-command { + background-color: var(--background-primary-alt); +} + +.cm-s-obsidian .cm-templater-command.cm-templater-opening-tag { + font-weight: bold; +} + +.cm-s-obsidian .cm-templater-command.cm-templater-closing-tag { + font-weight: bold; +} + +.cm-s-obsidian .cm-templater-command.cm-templater-interpolation-tag { + color: var(--code-property, #008bff); +} + +.cm-s-obsidian .cm-templater-command.cm-templater-execution-tag { + color: var(--code-function, #c0d700); +} + +.cm-s-obsidian .cm-templater-command.cm-keyword { + color: var(--code-keyword, #00a7aa); + font-weight: normal; +} + +.cm-s-obsidian .cm-templater-command.cm-atom { + color: var(--code-normal, #f39b35); +} + +.cm-s-obsidian .cm-templater-command.cm-value, +.cm-s-obsidian .cm-templater-command.cm-number, +.cm-s-obsidian .cm-templater-command.cm-type { + color: var(--code-value, #a06fca); +} + +.cm-s-obsidian .cm-templater-command.cm-def, +.cm-s-obsidian .cm-templater-command.cm-type.cm-def { + color: var(--code-normal, var(--text-normal)); +} + +.cm-s-obsidian .cm-templater-command.cm-property, +.cm-s-obsidian .cm-templater-command.cm-property.cm-def, +.cm-s-obsidian .cm-templater-command.cm-attribute { + color: var(--code-function, #98e342); +} + +.cm-s-obsidian .cm-templater-command.cm-variable, +.cm-s-obsidian .cm-templater-command.cm-variable-2, +.cm-s-obsidian .cm-templater-command.cm-variable-3, +.cm-s-obsidian .cm-templater-command.cm-meta { + color: var(--code-property, #d4d4d4); +} + +.cm-s-obsidian .cm-templater-command.cm-callee, +.cm-s-obsidian .cm-templater-command.cm-operator, +.cm-s-obsidian .cm-templater-command.cm-qualifier, +.cm-s-obsidian .cm-templater-command.cm-builtin { + color: var(--code-operator, #fc4384); +} + +.cm-s-obsidian .cm-templater-command.cm-tag { + color: var(--code-tag, #fc4384); +} + +.cm-s-obsidian .cm-templater-command.cm-comment, +.cm-s-obsidian .cm-templater-command.cm-comment.cm-tag, +.cm-s-obsidian .cm-templater-command.cm-comment.cm-attribute { + color: var(--code-comment, #696d70); +} + +.cm-s-obsidian .cm-templater-command.cm-string, +.cm-s-obsidian .cm-templater-command.cm-string-2 { + color: var(--code-string, #e6db74); +} + +.cm-s-obsidian .cm-templater-command.cm-header, +.cm-s-obsidian .cm-templater-command.cm-hr { + color: var(--code-keyword, #da7dae); +} + +.cm-s-obsidian .cm-templater-command.cm-link { + color: var(--code-normal, #696d70); +} + +.cm-s-obsidian .cm-templater-command.cm-error { + border-bottom: 1px solid #c42412; +} + +.CodeMirror-hints { + position: absolute; + z-index: 10; + overflow: hidden; + list-style: none; + + margin: 0; + padding: 2px; + + -webkit-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2); + box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.2); + border-radius: 3px; + border: 1px solid silver; + + background: white; + font-size: 90%; + font-family: monospace; + + max-height: 20em; + overflow-y: auto; +} + +.CodeMirror-hint { + margin: 0; + padding: 0 4px; + border-radius: 2px; + white-space: pre; + color: black; + cursor: pointer; +} + +li.CodeMirror-hint-active { + background: #08f; + color: white; +} diff --git a/src/content/blog/.obsidian/templates.json b/src/content/blog/.obsidian/templates.json new file mode 100644 index 0000000..c73ceea --- /dev/null +++ b/src/content/blog/.obsidian/templates.json @@ -0,0 +1,3 @@ +{ + "folder": "_templates" +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/themes/Lunar Witch b/src/content/blog/.obsidian/themes/Lunar Witch new file mode 160000 index 0000000..be9db88 --- /dev/null +++ b/src/content/blog/.obsidian/themes/Lunar Witch @@ -0,0 +1 @@ +Subproject commit be9db886ee504a5b261304a072efed8dd95477d9 diff --git a/src/content/blog/.obsidian/workspace-mobile.json b/src/content/blog/.obsidian/workspace-mobile.json new file mode 100644 index 0000000..55f6867 --- /dev/null +++ b/src/content/blog/.obsidian/workspace-mobile.json @@ -0,0 +1,189 @@ +{ + "main": { + "id": "7663cfdec50a2e60", + "type": "split", + "children": [ + { + "id": "88b63dcf6741e6f9", + "type": "tabs", + "children": [ + { + "id": "4e7fb0fa8a91a644", + "type": "leaf", + "state": { + "type": "empty", + "state": {} + } + }, + { + "id": "9906b890c36b6299", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "disorganized-notes.md", + "mode": "source", + "source": false + } + } + }, + { + "id": "d09a5378edd6a804", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "Cluster(fuck).md", + "mode": "source", + "source": false + } + } + } + ], + "currentTab": 2 + } + ], + "direction": "vertical" + }, + "left": { + "id": "f4b976b97e7fd228", + "type": "mobile-drawer", + "children": [ + { + "id": "9a9092e5af389cad", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": { + "sortOrder": "alphabetical" + } + } + }, + { + "id": "2d68e3a0b9422237", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + } + } + }, + { + "id": "5f7d922fec445f5f", + "type": "leaf", + "state": { + "type": "tag", + "state": { + "sortOrder": "frequency", + "useHierarchy": true + } + } + }, + { + "id": "d6ada5d7cc6d1556", + "type": "leaf", + "state": { + "type": "all-properties", + "state": { + "sortOrder": "frequency", + "showSearch": false, + "searchQuery": "" + } + } + }, + { + "id": "4a8876ca2b9a89ff", + "type": "leaf", + "state": { + "type": "bookmarks", + "state": {} + } + } + ], + "currentTab": 0 + }, + "right": { + "id": "218c19081cc9759e", + "type": "mobile-drawer", + "children": [ + { + "id": "960abadb2f6d83be", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "file": "Cluster(fuck).md", + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + } + } + }, + { + "id": "f1269aab005c7711", + "type": "leaf", + "state": { + "type": "outgoing-link", + "state": { + "file": "Cluster(fuck).md", + "linksCollapsed": false, + "unlinkedCollapsed": true + } + } + }, + { + "id": "e52f324db672aadb", + "type": "leaf", + "state": { + "type": "outline", + "state": { + "file": "Cluster(fuck).md" + } + } + } + ], + "currentTab": 0 + }, + "left-ribbon": { + "hiddenItems": { + "templater-obsidian:Templater": false, + "switcher:Open quick switcher": false, + "graph:Open graph view": false, + "canvas:Create new canvas": false, + "daily-notes:Open today's daily note": false, + "templates:Insert template": false, + "command-palette:Open command palette": false + } + }, + "active": "d09a5378edd6a804", + "lastOpenFiles": [ + "images/image-7.png", + "disorganized-notes.md", + "Cluster(fuck).md", + "gpg.md", + "_drafts/hypercomplex-interest.md", + "_drafts/olc-codes.md", + "hypercomplex-interest.md", + "_drafts/numbers.md", + "traefik-setup.mdx", + "traefik-setup.md", + "self-hosting.md", + "post-1.md", + "olc-codes.md", + "modern-unix.md", + "numbers.md", + "btrfs.md", + "Numbers.md", + "post-1.mdx" + ] +} \ No newline at end of file diff --git a/src/content/blog/.obsidian/workspace.json b/src/content/blog/.obsidian/workspace.json new file mode 100644 index 0000000..9e74f80 --- /dev/null +++ b/src/content/blog/.obsidian/workspace.json @@ -0,0 +1,195 @@ +{ + "main": { + "id": "ab75e1a8295cbca5", + "type": "split", + "children": [ + { + "id": "a4abf8e6b36b57d5", + "type": "tabs", + "children": [ + { + "id": "a519de38d2e49486", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "Cluster(fuck).md", + "mode": "source", + "source": false + } + } + } + ] + } + ], + "direction": "vertical" + }, + "left": { + "id": "bded18fe7fea77f1", + "type": "split", + "children": [ + { + "id": "2aae19a12ff084d4", + "type": "tabs", + "children": [ + { + "id": "e720579404769582", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": { + "sortOrder": "alphabetical" + } + } + }, + { + "id": "6ebf02f3e8539b39", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + } + } + }, + { + "id": "8ebfcda9ac2bec1f", + "type": "leaf", + "state": { + "type": "bookmarks", + "state": {} + } + } + ] + } + ], + "direction": "horizontal", + "width": 200 + }, + "right": { + "id": "8305c95260129b96", + "type": "split", + "children": [ + { + "id": "2fe64cfa3b21eac0", + "type": "tabs", + "children": [ + { + "id": "96089a301fb95140", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "file": "Cluster(fuck).md", + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + } + } + }, + { + "id": "07b1190b9f080756", + "type": "leaf", + "state": { + "type": "outgoing-link", + "state": { + "file": "Cluster(fuck).md", + "linksCollapsed": false, + "unlinkedCollapsed": true + } + } + }, + { + "id": "7039859502237cad", + "type": "leaf", + "state": { + "type": "tag", + "state": { + "sortOrder": "frequency", + "useHierarchy": true + } + } + }, + { + "id": "a83852de6ab674f8", + "type": "leaf", + "state": { + "type": "outline", + "state": { + "file": "Cluster(fuck).md" + } + } + }, + { + "id": "b1ea4546b2c351a8", + "type": "leaf", + "state": { + "type": "all-properties", + "state": { + "sortOrder": "frequency", + "showSearch": false, + "searchQuery": "" + } + } + } + ] + } + ], + "direction": "horizontal", + "width": 300, + "collapsed": true + }, + "left-ribbon": { + "hiddenItems": { + "switcher:Open quick switcher": false, + "graph:Open graph view": false, + "canvas:Create new canvas": false, + "daily-notes:Open today's daily note": false, + "templates:Insert template": false, + "command-palette:Open command palette": false, + "templater-obsidian:Templater": false + } + }, + "active": "a519de38d2e49486", + "lastOpenFiles": [ + "traefik-setup.md", + "images/minecraft-srv-01.png", + "_drafts/olc-codes.md", + "_drafts/numbers.md", + "images/btrfs.md", + "_drafts/eigencode.md", + "_drafts/hypercomplex-interest.md", + "_drafts/luka_pona.md", + "_drafts/modern-unix.md", + "_drafts/monogatari.md", + "_drafts/nonfree.md", + "_drafts/self-hosting.md", + "_drafts/Wolfgrads bot.md", + "disorganized-notes.md", + "Cluster(fuck).md", + "gpg.md", + "modern-unix.md", + "post-1.md", + "self-hosting.md", + "_templates/post-template.md", + "test post.md", + "_templates", + "btrfs.sync-conflict-20240624-164405-EI6QHE3.md", + "btrfs.sync-conflict-20240624-164402-EI6QHE3.md", + "post-1.mdx", + "traefik-setup.mdx", + "drafts/self-hosting.md", + "drafts/modern-unix.md", + "drafts/Wolfgrads bot.md", + "drafts" + ] +} \ No newline at end of file diff --git a/src/content/blog/.trash/post-1.mdx b/src/content/blog/.trash/post-1.mdx new file mode 100644 index 0000000..a2a471c --- /dev/null +++ b/src/content/blog/.trash/post-1.mdx @@ -0,0 +1,41 @@ +--- +title: "Generating an SSH Resident Key" +author: "ArgentumCation" +layout: ../../layouts/Layout.astro +pubDate: "19 Mar, 2023" +slug: "post-1" +--- + +import { Accordion, AccordionItem } from "accessible-astro-components"; + +## Here's how to create a resident SSH Key using a security key + +```bash +ssh-keygen -t ed25519-sk -Oresident +``` + +## If that one doesn't work, + +```bash +ssh-keygen -t ed25519-sk -Oresident -Oapplication=ssh:key +``` + +{ +// ```js +// import { defineConfig } from "astro/config"; +// import mdx from "@astrojs/mdx"; + +// export default defineConfig({ +// markdown: { +// syntaxHighlight: "prism", +// }, +// integrations: [ +// mdx({ +// // Markdown config now ignored +// extendMarkdownConfig: true, +// // No `remarkPlugins` applied +// }), +// ], +// }); +// ``` +} diff --git a/src/content/blog/.trash/traefik-setup.mdx b/src/content/blog/.trash/traefik-setup.mdx new file mode 100644 index 0000000..e3bdc4d --- /dev/null +++ b/src/content/blog/.trash/traefik-setup.mdx @@ -0,0 +1,143 @@ +--- +title: "Getting up and running with Traefik" +author: "ArgentumCation" +layout: ../../layouts/Layout.astro +pubDate: "03 Apr, 2023" +slug: "traefik-setup" +--- + +- Okay so you've got a server now and need a reverse proxy +- Traefik is pretty decent at that, it'll set up your HTTPS certs and auto generate routes from your docker images +- only problem is its an absolute bitch to set up +- Here's a stripped down `docker-compose.yml` to give you an idea of how I have it set up +- The end result should be a lighttpd server running on `blog.argentumcation.com` +```yaml +# Just setting some default values for my containers +x-service_defaults: + &service_defaults + env_file: .env + restart: unless-stopped + extra_hosts: + - host.docker.internal:host-gateway +services: + traefik: + <<: *service_defaults + container_name: traefik + env_file: + - .env + # Cloudflare API token to add new paths + - $ENV_DIR/traefik.secrets.env + hostname: traefik + image: traefik:latest + labels: + - traefik.http.services.traefik-docker.loadbalancer.server.port=8080 + # For the management interface + - '8080:8080' + # To let traefik receive incoming HTTP traffic + - '80:80' + # To let traefik receive incoming HTTPS traffic + - '443:443' + volumes: + # This lets traefik see your docker services + - $DOCKER_SOCK:/var/run/docker.sock:ro + # Traefik Configs + - $CONF_DIR/traefik/traefik.yml:/traefik.yml + - $CONF_DIR/traefik/traefik_dynamic.yml:/etc/traefik/traefik_dynamic.yml + # Let's Encrypt folder (for storing HTTPS cert related stuff) + - $CONF_DIR/letsencrypt:/letsencrypt + # Example container we're proxying with traefik + lighttpd: + <<: *service_defaults + container_name: public_lighttpd + image: sebp/lighttpd + labels: + # This is the hostname that traefik will proxy to this container + - traefik.http.routers.lighttpd-docker.rule=Host(`blog.$PUBLIC`) + # This is the port the container is listening on, often traefik can detect this + # automatically, but we'll just be explicit here + - traefik.http.services.lighttpd-docker.loadbalancer.server.port=80 +``` +- `traefik.secrets.env` contains my cloudflare API key so that Traefik can automatically add DNS routes +- For reference, here's my `.env` file +```sh +# GENERAL +PUBLIC=argentumcation.com +TZ=America/New_York + +#for container specific env vars +ENV_DIR=./env + +CONF_DIR=./config + +DOCKER_DIR=/home/mira/docker +DOCKER_SOCK=/var/run/docker.sock + +# So my containers run as a non-root user +UID=1000 +GID=1000 +PUID=1000 +PGID=1000 +USER_UID=1000 +USER_GID=1000 +``` +- And of course, the actual traefik configuration files: + - `traefik.yml`: +```yaml +accessLog: + filePath: ./traefik-access.log + +api: + dashboard: true + debug: true + insecure: true +certificatesResolvers: + letsencrypt: + acme: + dnschallenge: + provider: cloudflare #look, I know, don't judge me + email: [redacted] + storage: /letsencrypt/acme.json +entryPoints: + web: + address: ":80" + forwardedHeaders: + insecure: true + http: + middlewares: + - https_redirect@file + + websecure: + address: ":443" + forwardedHeaders: + insecure: true + http: + tls: + certresolver: letsencrypt + domains: + - main: argentumcation.com + sans: + - "*.argentumcation.com" +log: + level: INFO +providers: + docker: + # Routes will be set to [container-name].argentumcation.com by default + defaultRule: Host(`{{ index .Labels "com.docker.compose.service" }}.argentumcation.com`) + endpoint: unix:///var/run/docker.sock + exposedByDefault: true # exposes auto-discovered containers by default, not secure but I'm lazy + network: docker_default + watch: true + file: + directory: /etc/traefik/ + watch: true + +``` + - `traefik-dynamic.yml` +```yaml +http: + middlewares: #This should redirect incoming http connections to https + https_redirect: + redirectscheme: + scheme: https + permanent: true +``` \ No newline at end of file diff --git a/src/content/blog/Cluster(fuck).md b/src/content/blog/Cluster(fuck).md new file mode 100644 index 0000000..7e5af98 --- /dev/null +++ b/src/content/blog/Cluster(fuck).md @@ -0,0 +1,37 @@ +--- +author: ArgentumCation +title: Cluster(fuck) +pubDate: 01 Jan, 1970 +slug: cluster +--- + + +| Hostname | IPv4 | Hardware | Function | OS | Arch | Cores | Ram | USB power? | Power | +| -------------- | ---- | -------------- | --------------- | -------------- | ------------------------ | ----- | ---- | ---------- | ------- | +| | -- | Meraki MR44 | | | | | | | 15/30W? | +| | 248 | Meraki MX68W | | | | | | | 19-87W | +| | | TODO | Switch | | | | | | | +| | | TODO | Switch | | | | | | | +| Amylin | 65 | Nest Pro | WAP | | | | | | | +| Auxin | 153 | | NAS | Nix | x86_64 | 8 | 48 | | | +| Cortisol | 119 | Framework 13 | Personal laptop | Arch | x86_64 | 16 | 32 | X | | +| Epinephrine | | | Desktop | Arch + Windows | x86_64 | TODO | TODO | | | +| Ethylene | 213 | Pi Zero W | | Raspi | arm | 1 | 0.5 | X | 1W | +| Florigen | 108 | Pixel 9 Pro XL | Phone | Android | aarch64 | | | X | | +| Galanin | 129 | Thinkpad x270 | | Nix | x86_64 | 4 | 16 | X | 45/65W | +| Gastrin | 187 | HP x360 G3 EE | Kitchen tablet | Nix | x86_64 | 2 | 4 | X | 45W | +| Histamine | 27 | iPad Air 2 | Tablet | iOS | aarch64 | | | \* | | +| Kinetin | | Milk V Duo | | Buildroot? | RV64
    (or aarch64)
    | TODO | 0.25 | X | 5W | +| Leptin | 117 | iMac | Darwin builds | mac | aarch64 | 8 | 8 | | | +| Melatonin | | Erista | Switch | Horizon | aarch64 | | | X | | +| Mellinoë | 226 | | Work laptop | | x86_64 | | | X | | +| Norepinephrine | 179 | | Phone | Android | aarch64 | | | X | | +| Orexin | 224 | Inspiron 7577 | | Nix | x86_64 | 8 | 16 | \* | 130W | +| Pectin | 79 | Ender 3 V3 | 3D printer | Klipper | | | | | | +| Relaxin | 182 | Pi B+ | | Raspi | arm | 1 | 0.5 | X | 2W | +| Rhodopsin | | | TV | | | | | | | +| Ribosome/mRNA | 64 | -- | | -- | -- | -- | -- | -- | -- | +| Strigolactone | 214 | Pi Pico W | power button | ESP32Home | | | | | | +| Vasopressin | 1 | Pi 4 | Router | OpenWRT | aarch64 | 4 | 8 | X | 6W | +| Zeatin | | Milk V Duo S | | Buildroot? | aarch64
    (or RV64) | TODO | 0.5 | X | 5W | + diff --git a/src/content/blog/_drafts/eigencode.md b/src/content/blog/_drafts/eigencode.md new file mode 100644 index 0000000..9a85d70 --- /dev/null +++ b/src/content/blog/_drafts/eigencode.md @@ -0,0 +1 @@ +- Okay so like the existence of Unicode is fucking based, and we have the Private Use Area (PUA) for things that the diff --git a/src/content/blog/_drafts/luka_pona.md b/src/content/blog/_drafts/luka_pona.md new file mode 100644 index 0000000..b7c4ea5 --- /dev/null +++ b/src/content/blog/_drafts/luka_pona.md @@ -0,0 +1,22 @@ +- wan: 1 +- tu: 2 +- tawa: L +- kiwen: fist with extended thumb +- supa: flat, fingers together +- nena: fingers together, bent at knuckle +- sike: 0 +- telo: fingers spread +- lili: ok + +| english | toki pona | handshape | location | orientation | movement | +| ---------------- | --------- | --------- | ----------- | ----------- | ---------- | +| no/none | ala | supa | at shoulder | face down | | +| at/in/exist/true | lon | wan | | | flick down | +| which/what | seme | | | | | +| side/next to | poka | | | | | +| bump/hill/nose | nena | | | | | +| down | anpa | | | | | +| face/front | sinpin | | | | | +| hand/arm/five | luka | | | | | +| body/torso | sijelo | | | | | +| eyes | oko | | | | | diff --git a/src/content/blog/_drafts/olc-codes.md b/src/content/blog/_drafts/olc-codes.md index b72149c..2566071 100644 --- a/src/content/blog/_drafts/olc-codes.md +++ b/src/content/blog/_drafts/olc-codes.md @@ -1,3 +1,36 @@ - 87G8P632+H8X2Q262 - 87000000+ -- P632+ \ No newline at end of file +- P632+ + +> [!NOTE] foo +> bar + +> [!TLDR] foo +> bar + +> [!tip] foo +> bar + +> [!done] foo +> bar + +> [!faq] foo +> bar + +> [!WARNING] foo +> bar + +> [!fail] foo +> bar + +> [!bug] foo +> bar + +> [!example] foo +> bar + +> [!quote] foo +> bar + +> blockquote +> \ No newline at end of file diff --git a/src/content/blog/_templates/post-template.md b/src/content/blog/_templates/post-template.md new file mode 100644 index 0000000..2321cdd --- /dev/null +++ b/src/content/blog/_templates/post-template.md @@ -0,0 +1,8 @@ +--- +title: <% tp.file.title %> +pubDate: <%tp.file.creation_date("YYYY-MM-DDTHH:mm:ssZ")%> +layout: ../../layouts/Layout.astro +slug: <% encodeURI(tp.file.title.toLowerCase().replaceAll(/[ -]/g,'_')) %> +author: ArgentumCation +--- +# <% tp.file.title %> diff --git a/src/content/blog/disorganized-notes.md b/src/content/blog/disorganized-notes.md index 5960a03..022fd55 100644 --- a/src/content/blog/disorganized-notes.md +++ b/src/content/blog/disorganized-notes.md @@ -7,38 +7,46 @@ slug: disorganized-notes --- # NixOS/Nix + - Show channels: `sudo nix-channel --list` - add unstable channel: `sudo nix-channel --add https://nixos.org/channels/nixpkgs-unstable unstable` - update repos: `sudo nix-channel --update; sudo nix search -u` +--- + # Vim + - Sort selected lines: `:sort` - Open man page: `:man [command]` or `\K` - Open URL: `gx` - Move between splits: `ctrl+w [direction]` -- [vim-commentary](https://github.com/tpope/vim-commentary): `gc [motion]` to comment out -- Case switching: - - `gU` to uppercase - - `gu` to lowercase - -`g~` to toggle +- [vim-commentary](https://github.com/tpope/vim-commentary): `gc [motion]` to comment out +- Case switching: + - `gU` to uppercase + - `gu` to lowercase -`g~` to toggle - Substitute: - - `/g` **global** - sub all in line - - `:%s/` - substitute in all lines - - `:5,12s/` substitute from lines 5 to 12 - - `:.,+2s/` substitute this line (`.`) and the next 2 - - `:g/^foo/s/bar/baz/g` substitute all instances of bar with baz on lines beginning with foo - - `/c` - ask for confirmation + - `/g` **global** - sub all in line + - `:%s/` - substitute in all lines + - `:5,12s/` substitute from lines 5 to 12 + - `:.,+2s/` substitute this line (`.`) and the next 2 + - `:g/^foo/s/bar/baz/g` substitute all instances of bar with baz on lines beginning with foo + - `/c` - ask for confirmation - Windows - - `:sp [filename]` horizontal split, optionally open file - - `vsp` vertical split - - `ctrl+w w` move between windows - - `ctrl+w =` resize windows to be equal - - `ctrl+w q` close window - - `ctrl+w ` move window + - `:sp [filename]` horizontal split, optionally open file + - `vsp` vertical split + - `ctrl+w w` move between windows + - `ctrl+w =` resize windows to be equal + - `ctrl+w q` close window + - `ctrl+w ` move window + # McFly +--- + # SSH + - Set up port forwarding in existing connection: + ```sh $ ~C ssh> -D [port number] @@ -47,8 +55,59 @@ ssh> -D [port number] $ ``` +--- + # Shell + - `!!:s/foo/bar/`, replace first instance of `foo` with `bar` in the previous command - `^foo^bar` same thing but shorter and less flexible - `!foo` rerun last command containing `foo` -- \ No newline at end of file + +--- + +# K8s + +- **Pod**: Group of containers + - Seems like this is what gets distributed across nodes + - Seems like this is the same as an **application** +- **Service**: handles networking for applications + +- **Helm**: the package manager + +- k3s is a lighter weight version +- kind runs k8s in docker +- minikube is another option, maintained by k8s, supports more arches + + - in this case, armv6 + - still looking for rv32/rv64 + +- `kubectl get nodes` +- `kubectl expose` + - `--type=NodePort` picks an ephermal ingress port + - allows external access? + - seems to create the service? +- `kubectl get`: basic info +- `kubectl describe`: more info +- `kubectl create deployment ribosome --image 'pihole/pihole'` + - does idek + - seems to pull and run the image +- deployment + - `spec.repilicas`: how many instances of the container? +- `minikube docker-env` does fuckery to let you use docker with k8s +- `kube-vip` is used for failover? +- Helm is package manager for k8s + - `helm repo add` for adding repos + - `helm repo update` + +--- + +# Keepalived + +- don't ever use use_vmac, it's fucky + +--- + +# Seaweedfs + +- mount: `weed mount -filer=localhost:8888 -dir=/weed -filer.path=/` +- master: `weed server -master.port=9333 -volume.port=8081 -dir="/mnt" -filer=true` diff --git a/src/content/blog/btrfs.md b/src/content/blog/images/btrfs.md similarity index 100% rename from src/content/blog/btrfs.md rename to src/content/blog/images/btrfs.md diff --git a/src/content/blog/images/image-7.png b/src/content/blog/images/image-7.png new file mode 100644 index 0000000000000000000000000000000000000000..ccbd91be7442a55cc7f8dd3aab1f86d0da1c1f20 GIT binary patch literal 122983 zcmb?@WmH^SwRxK>f#Vw3YXyS6onHc1Sddn3k4Jo!Cito!HS@TySvjx z?)^spc;j`y9;446PHj$YtF`x9d(OE|n2M4N#%to&NJvN+a>D*;A8&F?==(HI^{{qoGQdzWg&e*maaa4%8PAb$o6-xgBh`7vk63un6 zUSw`csW$uZSk=s)+J2|E`Tj~ub);M@E_YW0NlJCo<|CoSlJC3V^kPI&0I``)s}he- zO9fxkQ^lXk$yITY)%X$5J(L&iG(5tQ0^gwoI^o!=024MnGdCSgFpL~!cb=Y|X2nxu zu(@i4IJ*D!^cjgAg&Oqq_mf6&?whBZui;-O|NKksZJgj!!QYJHYRFGFvQq!lfmDbh zNA^_k4v(_%`O{4<)qknvckz4-gg(TWFr=Yu>ggGz`PUl21jK092lrfoav2c%oUwu_ z8&t}02)gp0E+ExWheNDVHF0UkV`}(wDCoV>y4}RpKsRj%Eg^|-K$&%8UmFK zRB`|9?J~_E=U^qS6hl6 zumWPmetP`fy8dXck}7e=%*R1vkaRc%rNKl2@K{(4`)Ce=nss&d-iK4`w{iYs8^1tl zx1S;0Ub~hY84uzd_w$risZ)Af=ZWa4QyBiApDILR*b_XTWQZCu`LX$fxDy!Z(LkDN zakk+mF3Y(iX8Fg09LT2g@<*)ByliQU$Nc+~ML$8TGiLI51nE<+Ph|es*3}2X2SmRj z7vsvtQeIhnB*o_*-Wq1rv~7l}a{p<^NTd^RBV}4`jSiE)g>x&CpuZ|Tc+J(`S2;w( zFIMmI9W7^UcWAqkn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