(() => {
var OMNIVORE_DASHBOARD_NOTE_TITLE_DEFAULT = "Omnivore Library Dashboard", OMNIVORE_DASHBOARD_ORDER_SETTING_DEFAULT = "updatedAt-desc", NOTE_HIGHLIGHT_ORDER_SETTING_DEFAULT = "updatedAt-desc", BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING_DEFAULT = "omnivore", OMNIVORE_DASHBOARD_COLUMNS_SETTING_DEFAULT = "Author, UpdatedAt", SYNC_ARTICLE_CONTENT_SETTING_DEFAULT = "false", OMNIVORE_DASHBOARD_NOTE_TITLE_SETTING = `Omnivore dashboard note title (default: "${OMNIVORE_DASHBOARD_NOTE_TITLE_DEFAULT}")`, OMNIVORE_DASHBOARD_ORDER_SETTING = `Omnivore dashboard order ("updatedAt-asc" or "updatedAt-desc" or "savedAt-asc" or "savedAt-desc"). Default: "${OMNIVORE_DASHBOARD_ORDER_SETTING_DEFAULT}")`, OMNIVORE_DASHBOARD_COLUMNS_SETTING = `Omnivore dashboard columns (comma separated list of: "Author", "Description", "UpdatedAt", "SavedAt", "PageType", "ReadingProgressPercent") (default: "${OMNIVORE_DASHBOARD_COLUMNS_SETTING_DEFAULT}")`, BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING = `Base tag for highlight note (default: "${BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING_DEFAULT}")`, NOTE_HIGHLIGHT_ORDER_SETTING = `Highlight order ("updatedAt-asc" or "updatedAt-desc". Default: "${NOTE_HIGHLIGHT_ORDER_SETTING_DEFAULT}")`, SYNC_ARTICLE_CONTENT_SETTING = `Sync article content (true or false). Default: "${SYNC_ARTICLE_CONTENT_SETTING_DEFAULT}"`, OMNIVORE_API_KEY_SETTING = "Omnivore API Key", AMPLENOTE_INSERT_CONTENT_LIMIT = 9e4, OMNIVORE_SYNC_BATCH_SIZE = 30;
var OMINOVRE_API_ENDPOINT = "https://api-prod.omnivore.app/api/graphql", OMNIVORE_APP_URL = "https://omnivore.app";
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"date-fns": "^3.6.0",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
"@omnivore-app/api": "^1.0.4",
"markdown-it": "^14.1.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
unified: "11.0.0",
"unist-util-visit": "^5.0.0",
"unist-util-visit-parents": "6.0.1",
"d3-svg-to-png": "^0.3.1",
"chart.js": "^4.4.3",
fparser: "^3.1.0",
nanoid: "^5.0.7",
zod: "^3.23.8"
},
devDependencies: {
"@types/jest": "^29.5.0",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.23.1",
"esbuild-jest2": "0.6.7",
"esbuild-plugins-node-modules-polyfill": "1.6.6",
express: "^4.19.2",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
playwright: "^1.47.2",
"core-js": "^3.38.1"
},
scripts: {
test: "jest --testPathPattern=src-omnivore",
"test:watch": "jest --testPathPattern=src-omnivore --watch",
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-omnivore",
"build:dev": "node esbuild.js $(pwd)/src-omnivore --watch --server"
}
};
var dynamicImportESM = async (pkg, pkgVersion = null) => {
if (0) {
try {
} catch (e) {
}
try {
} catch (e) {
}
}
let cdnList = ["https://esm.sh/", "https://esm.run/"], resolvedVersion = resolvePackageVersion(pkg, pkgVersion), importCompleted = !1, importPromises = cdnList.map(async (cdn) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (cdn !== "https://esm.sh/" && await new Promise((resolve) => setTimeout(resolve, 600)), importCompleted)
throw new Error(`Terminating as ${pkg} has already been imported`);
return import(url).then((module2) => ({ module: module2, url })).catch((e) => {
throw console.warn(`Failed to import ${pkg} from ${cdn}: ${e.message}`), e;
});
});
try {
let result = await Promise.any(importPromises);
return importCompleted = !0, console.log(`Imported ${pkg}@${resolvedVersion} from ${result.url}`), result.module;
} catch {
throw new Error(`Failed to import ${pkg} from all available CDNs`);
}
throw new Error(`Failed to import ${pkg} from all available CDNs`);
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return `${scope}/${name}`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function buildCDNUrl(cdn, pkg, version) {
let folders = [];
pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/");
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? `@${version}` : "", folderString = folders && folders.length > 0 ? `/${folders.join("/")}` : "", url = `${cdn}${basePkg}${versionString}${folderString}`;
return ["https://esm.sh/"].includes(cdn) ? url + "?bundle-deps" : url;
}
var dynamic_import_esm_default = dynamicImportESM;
var baseUrl = (endpoint) => endpoint.replace(/\/api\/graphql$/, ""), getContent = async (endpoint, apiKey, libraryItemIds) => {
let response = await fetch(`${baseUrl(endpoint)}/api/content`, {
method: "POST",
headers: {
"content-type": "application/json",
Authorization: apiKey
},
body: JSON.stringify({ libraryItemIds, format: "highlightedMarkdown" })
});
if (!response.ok)
throw console.error("Failed to fetch content", response.statusText), new Error("Failed to fetch content");
return await response.json();
}, downloadFromUrl = async (url) => {
let response = await fetch(url);
if (!response.ok) {
if (response.status === 404)
return await new Promise((resolve) => setTimeout(resolve, 1e3)), downloadFromUrl(url);
throw console.error("Failed to download content", response.statusText), new Error("Failed to download content");
}
return await response.text();
}, fetchContentForItems = async (endpoint, apiKey, items) => {
let content = await getContent(
endpoint,
apiKey,
items.map((a) => a.id)
);
await Promise.allSettled(
content.data.map(async (c) => {
if (c.error) {
console.error("Error fetching content", c.error);
return;
}
let item = items.find((i) => i.id === c.libraryItemId);
if (!item) {
console.error("Item not found", c.libraryItemId);
return;
}
item.content = await Promise.race([
downloadFromUrl(c.downloadUrl),
new Promise((_, reject) => setTimeout(() => reject("Timeout"), 6e4))
]);
})
);
}, getOmnivoreItems = async (apiKey, after = 0, first = 10, updatedAt = "", query = "", includeContent = !1, format = "html", endpoint) => {
let { Omnivore } = await dynamic_import_esm_default("@omnivore-app/api"), result = await new Omnivore({
apiKey,
baseUrl: baseUrl(endpoint),
timeoutMs: 1e4
}).items.search({
after,
first,
query: `${updatedAt ? "updated:" + updatedAt : ""} sort:saved-asc ${query}`,
includeContent: !1,
format
}), items = result.edges.map((e) => e.node);
if (includeContent && items.length > 0)
try {
await fetchContentForItems(endpoint, apiKey, items);
} catch (error) {
console.error("Error fetching content", error);
}
return [items, result.pageInfo.hasNextPage];
}, getDeletedOmnivoreItems = async (apiKey, after = 0, first = 10, updatedAt = "", endpoint) => {
let { Omnivore } = await dynamic_import_esm_default("@omnivore-app/api"), result = await new Omnivore({
apiKey,
baseUrl: baseUrl(endpoint),
timeoutMs: 1e4
}).items.updates({
after,
first,
since: updatedAt || "2021-01-01"
});
return [result.edges.filter((edge) => edge.updateReason === "DELETED" && edge.node).map((edge) => edge.node), result.pageInfo.hasNextPage];
};
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root = freeGlobal_default || freeSelf || Function("return this")(), root_default = root;
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
var isArray = Array.isArray, isArray_default = isArray;
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value))
return !1;
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;
var coreJsData = root_default["__core-js_shared__"], coreJsData_default = coreJsData;
var maskSrcKey = function() {
var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
var isMasked_default = isMasked;
var funcProto = Function.prototype, funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch {
}
try {
return func + "";
} catch {
}
}
return "";
}
var toSource_default = toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reIsHostCtor = /^\[object .+?Constructor\]$/, funcProto2 = Function.prototype, objectProto3 = Object.prototype, funcToString2 = funcProto2.toString, hasOwnProperty2 = objectProto3.hasOwnProperty, reIsNative = RegExp(
"^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject_default(value) || isMasked_default(value))
return !1;
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource_default(value));
}
var baseIsNative_default = baseIsNative;
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
var getValue_default = getValue;
function getNative(object, key) {
var value = getValue_default(object, key);
return baseIsNative_default(value) ? value : void 0;
}
var getNative_default = getNative;
var WeakMap = getNative_default(root_default, "WeakMap"), WeakMap_default = WeakMap;
var objectCreate = Object.create, baseCreate = function() {
function object() {
}
return function(proto) {
if (!isObject_default(proto))
return {};
if (objectCreate)
return objectCreate(proto);
object.prototype = proto;
var result = new object();
return object.prototype = void 0, result;
};
}(), baseCreate_default = baseCreate;
function copyArray(source, array) {
var index = -1, length = source.length;
for (array || (array = Array(length)); ++index < length; )
array[index] = source[index];
return array;
}
var copyArray_default = copyArray;
var defineProperty = function() {
try {
var func = getNative_default(Object, "defineProperty");
return func({}, "", {}), func;
} catch {
}
}(), defineProperty_default = defineProperty;
function arrayEach(array, iteratee) {
for (var index = -1, length = array == null ? 0 : array.length; ++index < length && iteratee(array[index], index, array) !== !1; )
;
return array;
}
var arrayEach_default = arrayEach;
var MAX_SAFE_INTEGER = 9007199254740991, reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
var type = typeof value;
return length = length == null ? MAX_SAFE_INTEGER : length, !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var isIndex_default = isIndex;
function baseAssignValue(object, key, value) {
key == "__proto__" && defineProperty_default ? defineProperty_default(object, key, {
configurable: !0,
enumerable: !0,
value,
writable: !0
}) : object[key] = value;
}
var baseAssignValue_default = baseAssignValue;
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var eq_default = eq;
var objectProto4 = Object.prototype, hasOwnProperty3 = objectProto4.hasOwnProperty;
function assignValue(object, key, value) {
var objValue = object[key];
(!(hasOwnProperty3.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) && baseAssignValue_default(object, key, value);
}
var assignValue_default = assignValue;
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for (var index = -1, length = props.length; ++index < length; ) {
var key = props[index], newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
newValue === void 0 && (newValue = source[key]), isNew ? baseAssignValue_default(object, key, newValue) : assignValue_default(object, key, newValue);
}
return object;
}
var copyObject_default = copyObject;
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;
var objectProto5 = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5;
return value === proto;
}
var isPrototype_default = isPrototype;
function baseTimes(n, iteratee) {
for (var index = -1, result = Array(n); ++index < n; )
result[index] = iteratee(index);
return result;
}
var baseTimes_default = baseTimes;
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
var baseIsArguments_default = baseIsArguments;
var objectProto6 = Object.prototype, hasOwnProperty4 = objectProto6.hasOwnProperty, propertyIsEnumerable = objectProto6.propertyIsEnumerable, isArguments = baseIsArguments_default( function() {
return arguments;
}()) ? baseIsArguments_default : function(value) {
return isObjectLike_default(value) && hasOwnProperty4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
}, isArguments_default = isArguments;
function stubFalse() {
return !1;
}
var stubFalse_default = stubFalse;
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, Buffer2 = moduleExports ? root_default.Buffer : void 0, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, isBuffer = nativeIsBuffer || stubFalse_default, isBuffer_default = isBuffer;
var argsTag2 = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag2 = "[object Function]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", weakMapTag = "[object WeakMap]", arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]", typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = !0;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = !1;
function baseIsTypedArray(value) {
return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
var baseIsTypedArray_default = baseIsTypedArray;
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var baseUnary_default = baseUnary;
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module, moduleExports2 = freeModule2 && freeModule2.exports === freeExports2, freeProcess = moduleExports2 && freeGlobal_default.process, nodeUtil = function() {
try {
var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch {
}
}(), nodeUtil_default = nodeUtil;
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray, isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default, isTypedArray_default = isTypedArray;
var objectProto7 = Object.prototype, hasOwnProperty5 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
for (var key in value)
(inherited || hasOwnProperty5.call(value, key)) && !(skipIndexes &&
(key == "length" ||
isBuff && (key == "offset" || key == "parent") ||
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") ||
isIndex_default(key, length))) && result.push(key);
return result;
}
var arrayLikeKeys_default = arrayLikeKeys;
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var overArg_default = overArg;
var nativeKeys = overArg_default(Object.keys, Object), nativeKeys_default = nativeKeys;
var objectProto8 = Object.prototype, hasOwnProperty6 = objectProto8.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype_default(object))
return nativeKeys_default(object);
var result = [];
for (var key in Object(object))
hasOwnProperty6.call(object, key) && key != "constructor" && result.push(key);
return result;
}
var baseKeys_default = baseKeys;
function keys(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
var keys_default = keys;
function nativeKeysIn(object) {
var result = [];
if (object != null)
for (var key in Object(object))
result.push(key);
return result;
}
var nativeKeysIn_default = nativeKeysIn;
var objectProto9 = Object.prototype, hasOwnProperty7 = objectProto9.hasOwnProperty;
function baseKeysIn(object) {
if (!isObject_default(object))
return nativeKeysIn_default(object);
var isProto = isPrototype_default(object), result = [];
for (var key in object)
key == "constructor" && (isProto || !hasOwnProperty7.call(object, key)) || result.push(key);
return result;
}
var baseKeysIn_default = baseKeysIn;
function keysIn(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object, !0) : baseKeysIn_default(object);
}
var keysIn_default = keysIn;
var nativeCreate = getNative_default(Object, "create"), nativeCreate_default = nativeCreate;
function hashClear() {
this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {}, this.size = 0;
}
var hashClear_default = hashClear;
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= result ? 1 : 0, result;
}
var hashDelete_default = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__", objectProto10 = Object.prototype, hasOwnProperty8 = objectProto10.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate_default) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty8.call(data, key) ? data[key] : void 0;
}
var hashGet_default = hashGet;
var objectProto11 = Object.prototype, hasOwnProperty9 = objectProto11.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty9.call(data, key);
}
var hashHas_default = hashHas;
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
return this.size += this.has(key) ? 0 : 1, data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value, this;
}
var hashSet_default = hashSet;
function Hash(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
Hash.prototype.clear = hashClear_default;
Hash.prototype.delete = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;
function listCacheClear() {
this.__data__ = [], this.size = 0;
}
var listCacheClear_default = listCacheClear;
function assocIndexOf(array, key) {
for (var length = array.length; length--; )
if (eq_default(array[length][0], key))
return length;
return -1;
}
var assocIndexOf_default = assocIndexOf;
var arrayProto = Array.prototype, splice = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
if (index < 0)
return !1;
var lastIndex = data.length - 1;
return index == lastIndex ? data.pop() : splice.call(data, index, 1), --this.size, !0;
}
var listCacheDelete_default = listCacheDelete;
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? void 0 : data[index][1];
}
var listCacheGet_default = listCacheGet;
function listCacheHas(key) {
return assocIndexOf_default(this.__data__, key) > -1;
}
var listCacheHas_default = listCacheHas;
function listCacheSet(key, value) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? (++this.size, data.push([key, value])) : data[index][1] = value, this;
}
var listCacheSet_default = listCacheSet;
function ListCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype.delete = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;
var Map = getNative_default(root_default, "Map"), Map_default = Map;
function mapCacheClear() {
this.size = 0, this.__data__ = {
hash: new Hash_default(),
map: new (Map_default || ListCache_default)(),
string: new Hash_default()
};
}
var mapCacheClear_default = mapCacheClear;
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var isKeyable_default = isKeyable;
function getMapData(map, key) {
var data = map.__data__;
return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var getMapData_default = getMapData;
function mapCacheDelete(key) {
var result = getMapData_default(this, key).delete(key);
return this.size -= result ? 1 : 0, result;
}
var mapCacheDelete_default = mapCacheDelete;
function mapCacheGet(key) {
return getMapData_default(this, key).get(key);
}
var mapCacheGet_default = mapCacheGet;
function mapCacheHas(key) {
return getMapData_default(this, key).has(key);
}
var mapCacheHas_default = mapCacheHas;
function mapCacheSet(key, value) {
var data = getMapData_default(this, key), size2 = data.size;
return data.set(key, value), this.size += data.size == size2 ? 0 : 1, this;
}
var mapCacheSet_default = mapCacheSet;
function MapCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype.delete = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;
function arrayPush(array, values) {
for (var index = -1, length = values.length, offset = array.length; ++index < length; )
array[offset + index] = values[index];
return array;
}
var arrayPush_default = arrayPush;
var getPrototype = overArg_default(Object.getPrototypeOf, Object), getPrototype_default = getPrototype;
function stackClear() {
this.__data__ = new ListCache_default(), this.size = 0;
}
var stackClear_default = stackClear;
function stackDelete(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
}
var stackDelete_default = stackDelete;
function stackGet(key) {
return this.__data__.get(key);
}
var stackGet_default = stackGet;
function stackHas(key) {
return this.__data__.has(key);
}
var stackHas_default = stackHas;
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default) {
var pairs = data.__data__;
if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1)
return pairs.push([key, value]), this.size = ++data.size, this;
data = this.__data__ = new MapCache_default(pairs);
}
return data.set(key, value), this.size = data.size, this;
}
var stackSet_default = stackSet;
function Stack(entries) {
var data = this.__data__ = new ListCache_default(entries);
this.size = data.size;
}
Stack.prototype.clear = stackClear_default;
Stack.prototype.delete = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;
function baseAssign(object, source) {
return object && copyObject_default(source, keys_default(source), object);
}
var baseAssign_default = baseAssign;
function baseAssignIn(object, source) {
return object && copyObject_default(source, keysIn_default(source), object);
}
var baseAssignIn_default = baseAssignIn;
var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module, moduleExports3 = freeModule3 && freeModule3.exports === freeExports3, Buffer3 = moduleExports3 ? root_default.Buffer : void 0, allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : void 0;
function cloneBuffer(buffer, isDeep) {
if (isDeep)
return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
}
var cloneBuffer_default = cloneBuffer;
function arrayFilter(array, predicate) {
for (var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; ++index < length; ) {
var value = array[index];
predicate(value, index, array) && (result[resIndex++] = value);
}
return result;
}
var arrayFilter_default = arrayFilter;
function stubArray() {
return [];
}
var stubArray_default = stubArray;
var objectProto12 = Object.prototype, propertyIsEnumerable2 = objectProto12.propertyIsEnumerable, nativeGetSymbols = Object.getOwnPropertySymbols, getSymbols = nativeGetSymbols ? function(object) {
return object == null ? [] : (object = Object(object), arrayFilter_default(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable2.call(object, symbol);
}));
} : stubArray_default, getSymbols_default = getSymbols;
function copySymbols(source, object) {
return copyObject_default(source, getSymbols_default(source), object);
}
var copySymbols_default = copySymbols;
var nativeGetSymbols2 = Object.getOwnPropertySymbols, getSymbolsIn = nativeGetSymbols2 ? function(object) {
for (var result = []; object; )
arrayPush_default(result, getSymbols_default(object)), object = getPrototype_default(object);
return result;
} : stubArray_default, getSymbolsIn_default = getSymbolsIn;
function copySymbolsIn(source, object) {
return copyObject_default(source, getSymbolsIn_default(source), object);
}
var copySymbolsIn_default = copySymbolsIn;
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
var baseGetAllKeys_default = baseGetAllKeys;
function getAllKeys(object) {
return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
var getAllKeys_default = getAllKeys;
function getAllKeysIn(object) {
return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default);
}
var getAllKeysIn_default = getAllKeysIn;
var DataView = getNative_default(root_default, "DataView"), DataView_default = DataView;
var Promise2 = getNative_default(root_default, "Promise"), Promise_default = Promise2;
var Set = getNative_default(root_default, "Set"), Set_default = Set;
var mapTag2 = "[object Map]", objectTag2 = "[object Object]", promiseTag = "[object Promise]", setTag2 = "[object Set]", weakMapTag2 = "[object WeakMap]", dataViewTag2 = "[object DataView]", dataViewCtorString = toSource_default(DataView_default), mapCtorString = toSource_default(Map_default), promiseCtorString = toSource_default(Promise_default), setCtorString = toSource_default(Set_default), weakMapCtorString = toSource_default(WeakMap_default), getTag = baseGetTag_default;
(DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) && (getTag = function(value) {
var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
if (ctorString)
switch (ctorString) {
case dataViewCtorString:
return dataViewTag2;
case mapCtorString:
return mapTag2;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag2;
case weakMapCtorString:
return weakMapTag2;
}
return result;
});
var getTag_default = getTag;
var objectProto13 = Object.prototype, hasOwnProperty10 = objectProto13.hasOwnProperty;
function initCloneArray(array) {
var length = array.length, result = new array.constructor(length);
return length && typeof array[0] == "string" && hasOwnProperty10.call(array, "index") && (result.index = array.index, result.input = array.input), result;
}
var initCloneArray_default = initCloneArray;
var Uint8Array2 = root_default.Uint8Array, Uint8Array_default = Uint8Array2;
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer)), result;
}
var cloneArrayBuffer_default = cloneArrayBuffer;
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var cloneDataView_default = cloneDataView;
var reFlags = /\w*$/;
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
return result.lastIndex = regexp.lastIndex, result;
}
var cloneRegExp_default = cloneRegExp;
var symbolProto = Symbol_default ? Symbol_default.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var cloneSymbol_default = cloneSymbol;
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var cloneTypedArray_default = cloneTypedArray;
var boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", mapTag3 = "[object Map]", numberTag2 = "[object Number]", regexpTag2 = "[object RegExp]", setTag3 = "[object Set]", stringTag2 = "[object String]", symbolTag = "[object Symbol]", arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag2:
return cloneArrayBuffer_default(object);
case boolTag2:
case dateTag2:
return new Ctor(+object);
case dataViewTag3:
return cloneDataView_default(object, isDeep);
case float32Tag2:
case float64Tag2:
case int8Tag2:
case int16Tag2:
case int32Tag2:
case uint8Tag2:
case uint8ClampedTag2:
case uint16Tag2:
case uint32Tag2:
return cloneTypedArray_default(object, isDeep);
case mapTag3:
return new Ctor();
case numberTag2:
case stringTag2:
return new Ctor(object);
case regexpTag2:
return cloneRegExp_default(object);
case setTag3:
return new Ctor();
case symbolTag:
return cloneSymbol_default(object);
}
}
var initCloneByTag_default = initCloneByTag;
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {};
}
var initCloneObject_default = initCloneObject;
var mapTag4 = "[object Map]";
function baseIsMap(value) {
return isObjectLike_default(value) && getTag_default(value) == mapTag4;
}
var baseIsMap_default = baseIsMap;
var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap, isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default, isMap_default = isMap;
var setTag4 = "[object Set]";
function baseIsSet(value) {
return isObjectLike_default(value) && getTag_default(value) == setTag4;
}
var baseIsSet_default = baseIsSet;
var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet, isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default, isSet_default = isSet;
var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4, argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", errorTag2 = "[object Error]", funcTag3 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag5 = "[object Map]", numberTag3 = "[object Number]", objectTag3 = "[object Object]", regexpTag3 = "[object RegExp]", setTag5 = "[object Set]", stringTag3 = "[object String]", symbolTag2 = "[object Symbol]", weakMapTag3 = "[object WeakMap]", arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]", cloneableTags = {};
cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag3] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag2] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = !0;
cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = !1;
function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer && (result = object ? customizer(value, key, object, stack) : customizer(value)), result !== void 0)
return result;
if (!isObject_default(value))
return value;
var isArr = isArray_default(value);
if (isArr) {
if (result = initCloneArray_default(value), !isDeep)
return copyArray_default(value, result);
} else {
var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
if (isBuffer_default(value))
return cloneBuffer_default(value, isDeep);
if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
if (result = isFlat || isFunc ? {} : initCloneObject_default(value), !isDeep)
return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value));
} else {
if (!cloneableTags[tag])
return object ? value : {};
result = initCloneByTag_default(value, tag, isDeep);
}
}
stack || (stack = new Stack_default());
var stacked = stack.get(value);
if (stacked)
return stacked;
stack.set(value, result), isSet_default(value) ? value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
}) : isMap_default(value) && value.forEach(function(subValue, key2) {
result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default, props = isArr ? void 0 : keysFunc(value);
return arrayEach_default(props || value, function(subValue, key2) {
props && (key2 = subValue, subValue = value[key2]), assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
}), result;
}
var baseClone_default = baseClone;
var CLONE_DEEP_FLAG2 = 1, CLONE_SYMBOLS_FLAG2 = 4;
function cloneDeep(value) {
return baseClone_default(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
}
var cloneDeep_default = cloneDeep;
function sortOmnivoreItems(omnivoreItems, sortKeyOrder) {
let [sortKey, sortOrder] = sortKeyOrder.trim().split("-"), validKeys = ["updatedAt", "savedAt"];
if (validKeys.map((k) => k.toLowerCase()).includes(sortKey.toLowerCase()))
sortKey = validKeys[validKeys.map((k) => k.toLowerCase()).indexOf(sortKey.toLowerCase())];
else
throw new Error(`Invalid omnivore items sort key: ${sortKey}`);
if (!["asc", "desc"].includes(sortOrder))
throw new Error(`Invalid sort order: ${sortOrder}`);
return cloneDeep_default(omnivoreItems).sort((a, b) => {
let aValue = a[sortKey] || "", bValue = b[sortKey] || "", comparison = aValue.toString().localeCompare(bValue.toString());
return sortOrder === "asc" ? comparison : -comparison;
});
}
function sortOmnivoreItemHighlights(omnivoreItemHighlights, sortKeyOrder) {
let [sortKey, sortOrder] = sortKeyOrder.trim().split("-"), validKeys = ["updatedAt"];
if (validKeys.map((k) => k.toLowerCase()).includes(sortKey.toLowerCase()))
sortKey = validKeys[validKeys.map((k) => k.toLowerCase()).indexOf(sortKey.toLowerCase())];
else
throw new Error(`Invalid highlights sort key: ${sortKey}`);
if (!["asc", "desc"].includes(sortOrder))
throw new Error(`Invalid sort order: ${sortOrder}`);
return cloneDeep_default(omnivoreItemHighlights).sort((a, b) => {
let aValue = a[sortKey] || "", bValue = b[sortKey] || "", comparison = aValue.toString().localeCompare(bValue.toString());
return sortOrder === "asc" ? comparison : -comparison;
});
}
function markdownEscape(string, extra = []) {
return [
[/\\/g, "\\\\"],
[/\*/g, "\\*"],
[/^-/g, "\\-"],
[/^\+ /g, "\\+ "],
[/^(=+)/g, "\\$1"],
[/^(#{1,6}) /g, "\\$1 "],
[/`/g, "\\`"],
[/^~~~/g, "\\~~~"],
[/\[/g, "\\["],
[/\]/g, "\\]"],
[/^>/g, "\\>"],
[/_/g, "\\_"],
[/^(\d+)\. /g, "$1\\. "],
[/\(/g, "\\("],
[/\)/g, "\\)"],
...extra
].reduce(function(accumulator, escape) {
return accumulator.replace(escape[0], escape[1]);
}, string);
}
function telegramMarkdownEscape(string) {
return string = markdownEscape(string, [
[/-/g, "\\-"],
[/\./g, "\\."],
[/\+/g, "\\+"],
[/\|/g, "\\|"],
[/=/g, "\\="],
[/>/g, "\\>"],
[/#/g, "\\#"]
]), string;
}
async function generateDashboardTable(omnivoreItemsState, appSettings, getNoteUrlFromTitle) {
let optionalColumns = (appSettings[OMNIVORE_DASHBOARD_COLUMNS_SETTING] || "").split(",").map((c) => c.trim()) || [];
optionalColumns = optionalColumns.filter((c) => ["Author", "Description", "UpdatedAt", "SavedAt", "PageType", "ReadingProgressPercent"].includes(c));
let headers = `|**Cover**|**Title**${optionalColumns.includes("Author") ? "|**Author**" : ""}${optionalColumns.includes("Description") ? "|**Description**" : ""}${optionalColumns.includes("UpdatedAt") ? "|**Updated At**" : ""}${optionalColumns.includes("SavedAt") ? "|**Saved At**" : ""}${optionalColumns.includes("PageType") ? "|**Page Type**" : ""}${optionalColumns.includes("ReadingProgressPercent") ? "|**Reading Progress Percent**" : ""}|**Omnivore Link**|`, separator = `|---|---${optionalColumns.map(() => "|---").join("")}|---|`, omnivoreItemsStateSorted = sortOmnivoreItems(omnivoreItemsState, appSettings[OMNIVORE_DASHBOARD_ORDER_SETTING] || OMNIVORE_DASHBOARD_ORDER_SETTING_DEFAULT), rows = await Promise.all(omnivoreItemsStateSorted.map(async (note) => `|![\\|180](${note.image})|${note.url ? `[${telegramMarkdownEscape(note.title || "")}](${await getNoteUrlFromTitle(note.title)})` : telegramMarkdownEscape(note.title || "")}${optionalColumns.includes("Author") ? `|${telegramMarkdownEscape(note.author || "")}` : ""}${optionalColumns.includes("Description") ? `|${telegramMarkdownEscape(note.description || "")}` : ""}${optionalColumns.includes("UpdatedAt") ? `|${new Date(note.updatedAt).toLocaleString()}` : ""}${optionalColumns.includes("SavedAt") ? `|${new Date(note.savedAt).toLocaleString()}` : ""}${optionalColumns.includes("PageType") ? `|${note.pageType}` : ""}${optionalColumns.includes("ReadingProgressPercent") ? `|${note.readingProgressPercent}%` : ""}|[Omnivore Link](${OMNIVORE_APP_URL}/me/${note.slug})|`)), result = [`# Omnivore Dashboard
`], currentChunk = "", currentChunkLength = 0, pageIndex = 1;
return rows.forEach((row) => {
let rowLength = [headers, separator, row].join(`
`).length;
currentChunkLength + rowLength > AMPLENOTE_INSERT_CONTENT_LIMIT && (result.push(`### Page ${pageIndex}
` + [headers, separator, currentChunk].join(`
`) + `
`), currentChunk = "", currentChunkLength = 0, pageIndex += 1), row.length < AMPLENOTE_INSERT_CONTENT_LIMIT && (currentChunk += row + `
`, currentChunkLength += rowLength);
}), currentChunk && result.push(`### Page ${pageIndex}
` + [headers, separator, currentChunk].join(`
`) + `
`), result;
}
function generateNoteHighlightSectionMarkdown(omnivoreItemsState, appSettings) {
let highlights = omnivoreItemsState.highlights || [], properHighlights = sortOmnivoreItemHighlights(highlights, appSettings[NOTE_HIGHLIGHT_ORDER_SETTING] || NOTE_HIGHLIGHT_ORDER_SETTING_DEFAULT).map((highlight) => highlight.quote ? `**Highlight [\u2197\uFE0F](${OMNIVORE_APP_URL}/me/${omnivoreItemsState.slug}#${highlight.id}):**
> ${getHighlightUnicodeIcon(highlight.color)} ${highlight.quote.split(`
`).join(" ").replace(/>/g, "\\>").replace(/\|/g, "\\|").replace(/^(#{1,6}) /g, "\\$1 ")}
` + (highlight.annotation != null && highlight.annotation !== "" ? `> > \u{1F4DD} ${highlight.annotation.split(`
`).join(" ").replace(/>/g, "\\>").replace(/\|/g, "\\|").replace(/^(#{1,6}) /g, "\\$1 ")}
` : "") : null).filter((h) => h);
return properHighlights.length === 0 ? `(No highlights - [create one](${OMNIVORE_APP_URL}/me/${omnivoreItemsState.slug}))` : properHighlights.join(`
`);
}
function generateNoteSummarySectionMarkdown(omnivoreItemsState, appSettings) {
return `![\\|180](${omnivoreItemsState.image})
- **Author:** ${(omnivoreItemsState.author || "").replace(/>/g, "\\>").replace(/\|/g, "\\|").replace(/^(#{1,6}) /g, "\\$1 ")}
- **Description:** ${(omnivoreItemsState.description || "").replace(/>/g, "\\>").replace(/\|/g, "\\|").replace(/^(#{1,6}) /g, "\\$1 ")}
- **Page Type:** ${omnivoreItemsState.pageType}
- **Updated At:** ${new Date(omnivoreItemsState.updatedAt).toLocaleString()}
- **Saved At:** ${new Date(omnivoreItemsState.savedAt).toLocaleString()}
- **Reading Progress Percent:** ${omnivoreItemsState.readingProgressPercent} / 100
`;
}
function getHighlightUnicodeIcon(color) {
switch (color = (color || "yellow").toLowerCase(), color) {
case "yellow":
return "\u{1F7E1}";
case "red":
return "\u{1F534}";
case "blue":
return "\u{1F535}";
case "green":
return "\u{1F7E2}";
default:
return "\u26AB\uFE0F";
}
}
var plugin = {
appOption: {
"Sync all": async function(app) {
await plugin._syncAll(app);
}
},
noteOption: {
"Sync all": {
run: async function(app, noteUUID) {
await plugin._syncAll(app);
},
check: async function(app, noteUUID) {
let noteTitle = (await app.findNote({ uuid: noteUUID })).name;
return noteTitle === app.settings[OMNIVORE_DASHBOARD_NOTE_TITLE_SETTING] || noteTitle === OMNIVORE_DASHBOARD_NOTE_TITLE_DEFAULT;
}
}
},
_syncAll: async function(app) {
if (app.settings[OMNIVORE_API_KEY_SETTING] === "" || app.settings[OMNIVORE_API_KEY_SETTING] === void 0 || app.settings[OMNIVORE_API_KEY_SETTING] === null) {
app.alert("Please set your Omnivore API Key in the settings.");
return;
}
try {
if (await plugin._checkOmnivoreApiKey(app)) {
let {
omnivoreItemsState,
omnivoreItemsStateDelta,
omnivoreDeletedItems
} = await plugin._syncStateWithOmnivore(app);
console.log(omnivoreItemsState, omnivoreItemsStateDelta, omnivoreDeletedItems);
let suppressedErrorMessages = await plugin._syncHighlightsToNotes(omnivoreItemsState, omnivoreItemsStateDelta, omnivoreDeletedItems, app);
await plugin._syncCatalogToDashboard(omnivoreItemsState, app), app.alert(`Syncing complete. ${suppressedErrorMessages.length > 0 ? "Some errors were encountered: " + suppressedErrorMessages.join(`
`) : ""}`);
} else
app.alert("Failed to connect to omnivore. It is likely Omnivore API Key provided in settings is invalid.");
} catch (e) {
console.error(e), app.alert("Error encountered: " + typeof e == "string" ? e : e.message);
}
},
_syncStateWithOmnivore: async function(app) {
let lastSyncPluginVersion = localStorage.getItem("lastSyncPluginVersion"), lastSyncPluginSettings = localStorage.getItem("lastSyncPluginSettings");
(lastSyncPluginVersion !== "2024-10-16T15:07:42.992Z" || lastSyncPluginSettings !== JSON.stringify(app.settings)) && (await localStorage.setItem("lastSyncTime", ""), await localStorage.setItem("lastOmnivoreItemsState", JSON.stringify([])));
let lastSyncTime = localStorage.getItem("lastSyncTime"), lastOmnivoreItemsState = [];
try {
lastOmnivoreItemsState = JSON.parse(localStorage.getItem("lastOmnivoreItemsState"));
} catch (e) {
console.error("Failed to parse lastOmnivoreItemsState", e);
}
let omnivoreItemsState = cloneDeep_default(lastOmnivoreItemsState), omnivoreItemsStateDelta = [];
for (let after = 0; ; after += OMNIVORE_SYNC_BATCH_SIZE) {
let [items, hasNextPage] = await getOmnivoreItems(
app.settings[OMNIVORE_API_KEY_SETTING],
after,
OMNIVORE_SYNC_BATCH_SIZE,
lastSyncTime,
"",
(app.settings[SYNC_ARTICLE_CONTENT_SETTING] || SYNC_ARTICLE_CONTENT_SETTING_DEFAULT).includes("true"),
"highlightedMarkdown",
OMINOVRE_API_ENDPOINT
);
for (let item of items) {
let note = omnivoreItemsState.find((n) => n.id === item.id);
note ? omnivoreItemsState[omnivoreItemsState.indexOf(note)] = item : omnivoreItemsState.push(item), omnivoreItemsStateDelta.push(item);
}
if (!hasNextPage)
break;
await new Promise((resolve) => setTimeout(resolve, 1200));
}
let omnivoreDeletedItems = [];
if (lastSyncTime !== "" && lastSyncTime != null)
for (let after = 0; ; after += size) {
let [deletedItems, hasNextPage] = await getDeletedOmnivoreItems(
app.settings[OMNIVORE_API_KEY_SETTING],
after,
OMNIVORE_SYNC_BATCH_SIZE,
lastSyncTime,
OMINOVRE_API_ENDPOINT
);
for (let item of deletedItems)
omnivoreDeletedItems.push(item);
if (!hasNextPage)
break;
await new Promise((resolve) => setTimeout(resolve, 1200));
}
omnivoreItemsState = omnivoreItemsState.filter((item) => omnivoreDeletedItems.find((deletedItem) => deletedItem.id === item.id) === void 0);
try {
await localStorage.setItem("lastOmnivoreItemsState", JSON.stringify(omnivoreItemsState)), await localStorage.setItem("lastSyncPluginVersion", "2024-10-16T15:07:42.992Z"), await localStorage.setItem("lastSyncTime", ( new Date()).toISOString()), await localStorage.setItem("lastSyncPluginSettings", JSON.stringify(app.settings));
} catch (e) {
console.error(e);
}
return { omnivoreItemsState, omnivoreItemsStateDelta, omnivoreDeletedItems };
},
_checkOmnivoreApiKey: async function(app) {
try {
let [items, hasNextPage] = await getOmnivoreItems(
app.settings[OMNIVORE_API_KEY_SETTING],
0,
1,
( new Date()).toISOString(),
"",
!1,
"highlightedMarkdown",
OMINOVRE_API_ENDPOINT
);
} catch (e) {
if (e.message && e.message.includes("Unexpected server error"))
return !1;
}
return !0;
},
_syncCatalogToDashboard: async function(omnivoreItemsState, app) {
let dashboardNoteTitle = app.settings[OMNIVORE_DASHBOARD_NOTE_TITLE_SETTING] || OMNIVORE_DASHBOARD_NOTE_TITLE_DEFAULT, dashboardNote = await app.findNote({ name: dashboardNoteTitle });
if (!dashboardNote && (dashboardNote = await app.notes.create(dashboardNoteTitle, []), !dashboardNote || !dashboardNote.uuid))
throw new Error(`Failed to create dashboard note: ${dashboardNoteTitle}`);
dashboardNote = await app.notes.find(dashboardNote.uuid), app.settings[OMNIVORE_DASHBOARD_COLUMNS_SETTING] = app.settings[OMNIVORE_DASHBOARD_COLUMNS_SETTING] || OMNIVORE_DASHBOARD_COLUMNS_SETTING_DEFAULT;
let newDashboardContent = await generateDashboardTable(omnivoreItemsState, app.settings, async (title) => {
let note = await app.findNote({ name: title });
return note ? await app.getNoteURL({ uuid: note.uuid }) : "";
});
if ((await dashboardNote.content()).trim() !== newDashboardContent.join(`
`).trim()) {
await app.replaceNoteContent({ uuid: dashboardNote.uuid }, "");
for (let chunk of newDashboardContent)
await app.insertNoteContent({ uuid: dashboardNote.uuid }, chunk, { atEnd: !0 });
}
},
_syncHighlightsToNotes: async function(omnivoreItemsState, omnivoreItemsStateDelta, omnivoreDeletedItems, app) {
let suppressedErrorMessages = [];
for (let omnivoreItem of omnivoreDeletedItems) {
let highlightNote = await app.findNote({ name: omnivoreItem.title });
if (highlightNote) {
highlightNote = await app.notes.find(highlightNote.uuid);
let content = await highlightNote.content();
content.includes("Summary") || content.includes("Highlights") ? await app.deleteNote({ uuid: highlightNote.uuid }) : suppressedErrorMessages.push(`Failed to delete highlight note: ${omnivoreItem.title}`);
}
}
let omnivoreItemsStateFiltered = [];
for (let omnivoreItem of omnivoreItemsState)
omnivoreItem.title && omnivoreItem.title !== "" && !await app.findNote({ name: omnivoreItem.title }) && omnivoreItemsStateFiltered.push(omnivoreItem);
omnivoreItemsStateFiltered = [...omnivoreItemsStateFiltered, ...omnivoreItemsStateDelta];
for (let omnivoreItem of omnivoreItemsStateFiltered)
try {
let highlightNote = await app.findNote({ name: omnivoreItem.title });
highlightNote || (highlightNote = await app.notes.create(omnivoreItem.title, []), (!highlightNote || !highlightNote.uuid) && (suppressedErrorMessages.push(`Failed to create highlight note: ${omnivoreItem.title}`), console.log(`Failed to create highlight note: ${omnivoreItem.title}`))), highlightNote = await app.notes.find(highlightNote.uuid);
let highlightNoteTag = app.settings[BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING] || BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING_DEFAULT;
highlightNote.tags.includes(highlightNoteTag) || (highlightNoteTag !== BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING_DEFAULT && await highlightNote.removeTag(BASE_TAG_FOR_HIGHLIGHT_NOTE_SETTING_DEFAULT), await highlightNote.addTag(highlightNoteTag));
let summaryContent = generateNoteSummarySectionMarkdown(omnivoreItem, app.settings), highlightsContent = generateNoteHighlightSectionMarkdown(omnivoreItem, app.settings), newNoteContent = `# Summary
${summaryContent}<br/>
# Highlights
${highlightsContent}` + ((app.settings[SYNC_ARTICLE_CONTENT_SETTING] || SYNC_ARTICLE_CONTENT_SETTING_DEFAULT).includes("true") && omnivoreItem.content && omnivoreItem.content !== "" ? `
# Content
${omnivoreItem.content.length > 6e4 ? omnivoreItem.content.substring(0, 6e4) + "..." : omnivoreItem.content}` : "");
(await highlightNote.content()).trim() !== newNoteContent.trim() && await app.replaceNoteContent({ uuid: highlightNote.uuid }, newNoteContent);
} catch (e) {
suppressedErrorMessages.push(`Failed to sync highlight note: ${omnivoreItem.title}. Error:` + typeof e == "string" ? e : e.message), console.error(`Failed to sync highlight note: ${omnivoreItem.title}`, e);
}
return suppressedErrorMessages;
}
}, plugin_default = plugin;
return plugin;
})()