Establishes version control for the personal Logseq DB fork before starting the server-client architecture migration and domain features described in docs/agent-guide and the approved implementation plan. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2 lines
125 KiB
JavaScript
2 lines
125 KiB
JavaScript
/*! For license information please see lsplugin.core.js.LICENSE.txt */
|
||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.LSPlugin=t():e.LSPlugin=t()}(self,()=>(()=>{var e={221(e,t,r){var n=r(558);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))}),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=r(156)(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},156(e,t,r){e.exports=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r}),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(s(e,r))return!1;for(const r of t.names)if(s(e,r))return!0;return!1},t.humanize=r(49),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},314(e){"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===r}(e)}(e)},r="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((r=e,Array.isArray(r)?[]:{}),e,t):e;var r}function s(e,t,r){return e.concat(t).map(function(e){return n(e,r)})}function i(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,r,l){(l=l||{}).arrayMerge=l.arrayMerge||s,l.isMergeableObject=l.isMergeableObject||t,l.cloneUnlessOtherwiseSpecified=n;var c=Array.isArray(r);return c===Array.isArray(e)?c?l.arrayMerge(e,r,l):function(e,t,r){var s={};return r.isMergeableObject(e)&&i(e).forEach(function(t){s[t]=n(e[t],r)}),i(t).forEach(function(i){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,i)||(o(e,i)&&r.isMergeableObject(t[i])?s[i]=function(e,t){if(!t.customMerge)return a;var r=t.customMerge(e);return"function"==typeof r?r:a}(i,r)(e[i],t[i],r):s[i]=n(t[i],r))}),s}(e,r,l):n(r,l)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return a(e,r,t)},{})};var l=a;e.exports=l},138(e){"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var l,c,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(c=1,l=new Array(h-1);c<h;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var d,p=u.length;for(c=0;c<p;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),h){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,s);break;default:if(!l)for(d=1,l=new Array(h-1);d<h;d++)l[d-1]=arguments[d];u[c].fn.apply(u[c].context,l)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var l=0,c=[],u=a.length;l<u;l++)(a[l].fn!==t||s&&!a[l].once||n&&a[l].context!==n)&&c.push(a[l]);c.length?this._events[i]=1===c.length?c[0]:c:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},543(e){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},49(e){var t=1e3,r=60*t,n=60*r,s=24*n,i=7*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var l,c,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(l=e,(c=Math.abs(l))>=s?o(l,c,s,"day"):c>=n?o(l,c,n,"hour"):c>=r?o(l,c,r,"minute"):c>=t?o(l,c,t,"second"):l+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},528(e,t,r){"use strict";var n=r(558),s="win32"===n.platform,i=r(496);function o(e,t){for(var r=[],n=0;n<e.length;n++){var s=e[n];s&&"."!==s&&(".."===s?r.length&&".."!==r[r.length-1]?r.pop():t&&r.push(".."):r.push(s))}return r}function a(e){for(var t=e.length-1,r=0;r<=t&&!e[r];r++);for(var n=t;n>=0&&!e[n];n--);return 0===r&&n===t?e:r>n?[]:e.slice(r,n+1)}var l=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,c=/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/,u={};function h(e){var t=l.exec(e),r=(t[1]||"")+(t[2]||""),n=t[3]||"",s=c.exec(n);return[r,s[1],s[2],s[3]]}function d(e){var t=l.exec(e),r=t[1]||"",n=!!r&&":"!==r[1];return{device:r,isUnc:n,isAbsolute:n||!!t[2],tail:t[3]}}function p(e){return"\\\\"+e.replace(/^[\\\/]+/,"").replace(/[\\\/]+/g,"\\")}u.resolve=function(){for(var e="",t="",r=!1,s=arguments.length-1;s>=-1;s--){var a;if(s>=0?a=arguments[s]:e?(a=n.env["="+e])&&a.substr(0,3).toLowerCase()===e.toLowerCase()+"\\"||(a=e+"\\"):a=n.cwd(),!i.isString(a))throw new TypeError("Arguments to path.resolve must be strings");if(a){var l=d(a),c=l.device,u=l.isUnc,h=l.isAbsolute,f=l.tail;if((!c||!e||c.toLowerCase()===e.toLowerCase())&&(e||(e=c),r||(t=f+"\\"+t,r=h),e&&r))break}}return u&&(e=p(e)),e+(r?"\\":"")+(t=o(t.split(/[\\\/]+/),!r).join("\\"))||"."},u.normalize=function(e){var t=d(e),r=t.device,n=t.isUnc,s=t.isAbsolute,i=t.tail,a=/[\\\/]$/.test(i);return(i=o(i.split(/[\\\/]+/),!s).join("\\"))||s||(i="."),i&&a&&(i+="\\"),n&&(r=p(r)),r+(s?"\\":"")+i},u.isAbsolute=function(e){return d(e).isAbsolute},u.join=function(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(!i.isString(r))throw new TypeError("Arguments to path.join must be strings");r&&e.push(r)}var n=e.join("\\");return/^[\\\/]{2}[^\\\/]/.test(e[0])||(n=n.replace(/^[\\\/]{2,}/,"\\")),u.normalize(n)},u.relative=function(e,t){e=u.resolve(e),t=u.resolve(t);for(var r=e.toLowerCase(),n=t.toLowerCase(),s=a(t.split("\\")),i=a(r.split("\\")),o=a(n.split("\\")),l=Math.min(i.length,o.length),c=l,h=0;h<l;h++)if(i[h]!==o[h]){c=h;break}if(0==c)return t;var d=[];for(h=c;h<i.length;h++)d.push("..");return(d=d.concat(s.slice(c))).join("\\")},u._makeLong=function(e){if(!i.isString(e))return e;if(!e)return"";var t=u.resolve(e);return/^[a-zA-Z]\:\\/.test(t)?"\\\\?\\"+t:/^\\\\[^?.]/.test(t)?"\\\\?\\UNC\\"+t.substring(2):e},u.dirname=function(e){var t=h(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},u.basename=function(e,t){var r=h(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},u.extname=function(e){return h(e)[3]},u.format=function(e){if(!i.isObject(e))throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof e);var t=e.root||"";if(!i.isString(t))throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof e.root);var r=e.dir,n=e.base||"";return r?r[r.length-1]===u.sep?r+n:r+u.sep+n:n},u.parse=function(e){if(!i.isString(e))throw new TypeError("Parameter 'pathString' must be a string, not "+typeof e);var t=h(e);if(!t||4!==t.length)throw new TypeError("Invalid path '"+e+"'");return{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},u.sep="\\",u.delimiter=";";var f=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,g={};function m(e){return f.exec(e).slice(1)}g.resolve=function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var s=r>=0?arguments[r]:n.cwd();if(!i.isString(s))throw new TypeError("Arguments to path.resolve must be strings");s&&(e=s+"/"+e,t="/"===s[0])}return(t?"/":"")+(e=o(e.split("/"),!t).join("/"))||"."},g.normalize=function(e){var t=g.isAbsolute(e),r=e&&"/"===e[e.length-1];return(e=o(e.split("/"),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},g.isAbsolute=function(e){return"/"===e.charAt(0)},g.join=function(){for(var e="",t=0;t<arguments.length;t++){var r=arguments[t];if(!i.isString(r))throw new TypeError("Arguments to path.join must be strings");r&&(e+=e?"/"+r:r)}return g.normalize(e)},g.relative=function(e,t){e=g.resolve(e).substr(1),t=g.resolve(t).substr(1);for(var r=a(e.split("/")),n=a(t.split("/")),s=Math.min(r.length,n.length),i=s,o=0;o<s;o++)if(r[o]!==n[o]){i=o;break}var l=[];for(o=i;o<r.length;o++)l.push("..");return(l=l.concat(n.slice(i))).join("/")},g._makeLong=function(e){return e},g.dirname=function(e){var t=m(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},g.basename=function(e,t){var r=m(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},g.extname=function(e){return m(e)[3]},g.format=function(e){if(!i.isObject(e))throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof e);var t=e.root||"";if(!i.isString(t))throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof e.root);return(e.dir?e.dir+g.sep:"")+(e.base||"")},g.parse=function(e){if(!i.isString(e))throw new TypeError("Parameter 'pathString' must be a string, not "+typeof e);var t=m(e);if(!t||4!==t.length)throw new TypeError("Invalid path '"+e+"'");return t[1]=t[1]||"",t[2]=t[2]||"",t[3]=t[3]||"",{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},g.sep="/",g.delimiter=":",e.exports=s?u:g,e.exports.posix=g,e.exports.win32=u},558(e){var t,r,n=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function o(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var a,l=[],c=!1,u=-1;function h(){c&&a&&(c=!1,a.length?l=a.concat(l):u=-1,l.length&&d())}function d(){if(!c){var e=o(h);c=!0;for(var t=l.length;t;){for(a=l,l=[];++u<t;)a&&a[u].run();u=-1,t=l.length}a=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function f(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new p(e,t)),1!==l.length||c||o(d)},p.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=f,n.addListener=f,n.once=f,n.off=f,n.removeListener=f,n.removeAllListeners=f,n.emit=f,n.prependListener=f,n.prependOnceListener=f,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},80(e){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},496(e,t,r){var n=r(558),s=/%[sdj%]/g;t.format=function(e){if(!y(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(a(arguments[r]));return t.join(" ")}r=1;for(var n=arguments,i=n.length,o=String(e).replace(s,function(e){if("%%"===e)return"%";if(r>=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),l=n[r];r<i;l=n[++r])g(l)||!v(l)?o+=" "+l:o+=" "+a(l);return o},t.deprecate=function(e,s){if(_(r.g.process))return function(){return t.deprecate(e,s).apply(this,arguments)};if(!0===n.noDeprecation)return e;var i=!1;return function(){if(!i){if(n.throwDeprecation)throw new Error(s);n.traceDeprecation?console.trace(s):console.error(s),i=!0}return e.apply(this,arguments)}};var i,o={};function a(e,r){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),f(r)?n.showHidden=r:r&&t._extend(n,r),_(n.showHidden)&&(n.showHidden=!1),_(n.depth)&&(n.depth=2),_(n.colors)&&(n.colors=!1),_(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=l),u(n,e,n.depth)}function l(e,t){var r=a.styles[t];return r?"["+a.colors[r][0]+"m"+e+"["+a.colors[r][1]+"m":e}function c(e,t){return e}function u(e,r,n){if(e.customInspect&&r&&S(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var s=r.inspect(n,e);return y(s)||(s=u(e,s,n)),s}var i=function(e,t){if(_(t))return e.stylize("undefined","undefined");if(y(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return m(t)?e.stylize(""+t,"number"):f(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,r);if(i)return i;var o=Object.keys(r),a=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(r)),x(r)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return h(r);if(0===o.length){if(S(r)){var l=r.name?": "+r.name:"";return e.stylize("[Function"+l+"]","special")}if(b(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(w(r))return e.stylize(Date.prototype.toString.call(r),"date");if(x(r))return h(r)}var c,v="",E=!1,C=["{","}"];return p(r)&&(E=!0,C=["[","]"]),S(r)&&(v=" [Function"+(r.name?": "+r.name:"")+"]"),b(r)&&(v=" "+RegExp.prototype.toString.call(r)),w(r)&&(v=" "+Date.prototype.toUTCString.call(r)),x(r)&&(v=" "+h(r)),0!==o.length||E&&0!=r.length?n<0?b(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=E?function(e,t,r,n,s){for(var i=[],o=0,a=t.length;o<a;++o)A(t,String(o))?i.push(d(e,t,r,n,String(o),!0)):i.push("");return s.forEach(function(s){s.match(/^\d+$/)||i.push(d(e,t,r,n,s,!0))}),i}(e,r,n,a,o):o.map(function(t){return d(e,r,n,a,t,E)}),e.seen.pop(),function(e,t,r){return e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}(c,v,C)):C[0]+v+C[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,s,i){var o,a,l;if((l=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),A(n,s)||(o="["+s+"]"),a||(e.seen.indexOf(l.value)<0?(a=g(r)?u(e,l.value,null):u(e,l.value,r-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),_(o)){if(i&&s.match(/^\d+$/))return a;(o=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function p(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function y(e){return"string"==typeof e}function _(e){return void 0===e}function b(e){return v(e)&&"[object RegExp]"===E(e)}function v(e){return"object"==typeof e&&null!==e}function w(e){return v(e)&&"[object Date]"===E(e)}function x(e){return v(e)&&("[object Error]"===E(e)||e instanceof Error)}function S(e){return"function"==typeof e}function E(e){return Object.prototype.toString.call(e)}function C(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(_(i)&&(i=n.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var r=n.pid;o[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else o[e]=function(){};return o[e]},t.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=p,t.isBoolean=f,t.isNull=g,t.isNullOrUndefined=function(e){return null==e},t.isNumber=m,t.isString=y,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=_,t.isRegExp=b,t.isObject=v,t.isDate=w,t.isError=x,t.isFunction=S,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(80);var T=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;console.log("%s - %s",(r=[C((e=new Date).getHours()),C(e.getMinutes()),C(e.getSeconds())].join(":"),[e.getDate(),T[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=r(543),t._extend=function(e,t){if(!t||!v(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{"use strict";r.r(n),r.d(n,{PluginLocal:()=>Fs,pluginHelpers:()=>t,setupPluginCore:()=>zs});var e={};r.r(e),r.d(e,{setSDKMetadata:()=>me});var t={};r.r(t),r.d(t,{IS_DEV:()=>_e,PROTOCOL_FILE:()=>be,PROTOCOL_LSP:()=>ve,PluginLogger:()=>je,URL_LSP:()=>we,URL_LSP_EXTERNAL:()=>xe,URL_LSP_HOST:()=>Se,URL_LSP_HOST_EXTERNAL:()=>Ee,cleanInjectedScripts:()=>Ge,cleanInjectedUI:()=>qe,deepMerge:()=>Pe,deferred:()=>$e,genID:()=>Me,getAppPathRoot:()=>Ae,getSDKPathRoot:()=>ke,injectTheme:()=>Ye,invokeHostExportedApi:()=>ze,isObject:()=>Oe,isValidUUID:()=>Re,mergeSettingsWithSchema:()=>Ke,normalizeKeyStr:()=>Ve,path:()=>ye,safeSnakeCase:()=>Te,safetyPathJoin:()=>Ue,safetyPathNormalize:()=>Fe,setupInjectedStyle:()=>He,setupInjectedUI:()=>We,transformableEvent:()=>Je,ucFirst:()=>De,withFileProtocol:()=>Ne});const s=r(138);var i=r(528);const{entries:o,setPrototypeOf:a,isFrozen:l,getPrototypeOf:c,getOwnPropertyDescriptor:u}=Object;let{freeze:h,seal:d,create:p}=Object,{apply:f,construct:g}="undefined"!=typeof Reflect&&Reflect;h||(h=function(e){return e}),d||(d=function(e){return e}),f||(f=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),s=2;s<r;s++)n[s-2]=arguments[s];return e.apply(t,n)}),g||(g=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});const m=L(Array.prototype.forEach),y=L(Array.prototype.lastIndexOf),_=L(Array.prototype.pop),b=L(Array.prototype.push),v=L(Array.prototype.splice),w=L(String.prototype.toLowerCase),x=L(String.prototype.toString),S=L(String.prototype.match),E=L(String.prototype.replace),C=L(String.prototype.indexOf),T=L(String.prototype.trim),A=L(Object.prototype.hasOwnProperty),k=L(RegExp.prototype.test),O=(P=TypeError,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return g(P,t)});var P;function L(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return f(e,t,n)}}function I(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:w;a&&a(e,null);let n=t.length;for(;n--;){let s=t[n];if("string"==typeof s){const e=r(s);e!==s&&(l(t)||(t[n]=e),s=e)}e[s]=!0}return e}function j(e){for(let t=0;t<e.length;t++)A(e,t)||(e[t]=null);return e}function R(e){const t=p(null);for(const[r,n]of o(e))A(e,r)&&(Array.isArray(n)?t[r]=j(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=R(n):t[r]=n);return t}function M(e,t){for(;null!==e;){const r=u(e,t);if(r){if(r.get)return L(r.get);if("function"==typeof r.value)return L(r.value)}e=c(e)}return function(){return null}}const D=h(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),N=h(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),U=h(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),F=h(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),$=h(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),z=h(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),H=h(["#text"]),B=h(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),W=h(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),q=h(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),G=h(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),J=d(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Y=d(/<%[\w\W]*|[\w\W]*%>/gm),K=d(/\$\{[\w\W]*/gm),V=d(/^data-[\-\w.\u00B7-\uFFFF]+$/),X=d(/^aria-[\-\w]+$/),Z=d(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Q=d(/^(?:\w+script|data):/i),ee=d(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),te=d(/^html$/i),re=d(/^[a-z][.\w]*(-[.\w]+)+$/i);var ne=Object.freeze({__proto__:null,ARIA_ATTR:X,ATTR_WHITESPACE:ee,CUSTOM_ELEMENT:re,DATA_ATTR:V,DOCTYPE_NAME:te,ERB_EXPR:Y,IS_ALLOWED_URI:Z,IS_SCRIPT_OR_DATA:Q,MUSTACHE_EXPR:J,TMPLIT_EXPR:K});const se=function(){return"undefined"==typeof window?null:window};var ie=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:se();const r=t=>e(t);if(r.version="3.3.3",r.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return r.isSupported=!1,r;let{document:n}=t;const s=n,i=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:l,Node:c,Element:u,NodeFilter:d,NamedNodeMap:f=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:g,DOMParser:P,trustedTypes:L}=t,j=u.prototype,J=M(j,"cloneNode"),Y=M(j,"remove"),K=M(j,"nextSibling"),V=M(j,"childNodes"),X=M(j,"parentNode");if("function"==typeof l){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let Q,ee="";const{implementation:re,createNodeIterator:ie,createDocumentFragment:oe,getElementsByTagName:ae}=n,{importNode:le}=s;let ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof o&&"function"==typeof X&&re&&void 0!==re.createHTMLDocument;const{MUSTACHE_EXPR:ue,ERB_EXPR:he,TMPLIT_EXPR:de,DATA_ATTR:pe,ARIA_ATTR:fe,IS_SCRIPT_OR_DATA:ge,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:ye}=ne;let{IS_ALLOWED_URI:_e}=ne,be=null;const ve=I({},[...D,...N,...U,...$,...H]);let we=null;const xe=I({},[...B,...W,...q,...G]);let Se=Object.seal(p(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ee=null,Ce=null;const Te=Object.seal(p(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ae=!0,ke=!0,Oe=!1,Pe=!0,Le=!1,Ie=!0,je=!1,Re=!1,Me=!1,De=!1,Ne=!1,Ue=!1,Fe=!0,$e=!1,ze=!0,He=!1,Be={},We=null;const qe=I({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ge=null;const Je=I({},["audio","video","img","source","image","track"]);let Ye=null;const Ke=I({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ve="http://www.w3.org/1998/Math/MathML",Xe="http://www.w3.org/2000/svg",Ze="http://www.w3.org/1999/xhtml";let Qe=Ze,et=!1,tt=null;const rt=I({},[Ve,Xe,Ze],x);let nt=I({},["mi","mo","mn","ms","mtext"]),st=I({},["annotation-xml"]);const it=I({},["title","style","font","a","script"]);let ot=null;const at=["application/xhtml+xml","text/html"];let lt=null,ct=null;const ut=n.createElement("form"),ht=function(e){return e instanceof RegExp||e instanceof Function},dt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!ct||ct!==e){if(e&&"object"==typeof e||(e={}),e=R(e),ot=-1===at.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,lt="application/xhtml+xml"===ot?x:w,be=A(e,"ALLOWED_TAGS")?I({},e.ALLOWED_TAGS,lt):ve,we=A(e,"ALLOWED_ATTR")?I({},e.ALLOWED_ATTR,lt):xe,tt=A(e,"ALLOWED_NAMESPACES")?I({},e.ALLOWED_NAMESPACES,x):rt,Ye=A(e,"ADD_URI_SAFE_ATTR")?I(R(Ke),e.ADD_URI_SAFE_ATTR,lt):Ke,Ge=A(e,"ADD_DATA_URI_TAGS")?I(R(Je),e.ADD_DATA_URI_TAGS,lt):Je,We=A(e,"FORBID_CONTENTS")?I({},e.FORBID_CONTENTS,lt):qe,Ee=A(e,"FORBID_TAGS")?I({},e.FORBID_TAGS,lt):R({}),Ce=A(e,"FORBID_ATTR")?I({},e.FORBID_ATTR,lt):R({}),Be=!!A(e,"USE_PROFILES")&&e.USE_PROFILES,Ae=!1!==e.ALLOW_ARIA_ATTR,ke=!1!==e.ALLOW_DATA_ATTR,Oe=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Pe=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Le=e.SAFE_FOR_TEMPLATES||!1,Ie=!1!==e.SAFE_FOR_XML,je=e.WHOLE_DOCUMENT||!1,De=e.RETURN_DOM||!1,Ne=e.RETURN_DOM_FRAGMENT||!1,Ue=e.RETURN_TRUSTED_TYPE||!1,Me=e.FORCE_BODY||!1,Fe=!1!==e.SANITIZE_DOM,$e=e.SANITIZE_NAMED_PROPS||!1,ze=!1!==e.KEEP_CONTENT,He=e.IN_PLACE||!1,_e=e.ALLOWED_URI_REGEXP||Z,Qe=e.NAMESPACE||Ze,nt=e.MATHML_TEXT_INTEGRATION_POINTS||nt,st=e.HTML_INTEGRATION_POINTS||st,Se=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Se.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Se.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Se.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Le&&(ke=!1),Ne&&(De=!0),Be&&(be=I({},H),we=p(null),!0===Be.html&&(I(be,D),I(we,B)),!0===Be.svg&&(I(be,N),I(we,W),I(we,G)),!0===Be.svgFilters&&(I(be,U),I(we,W),I(we,G)),!0===Be.mathMl&&(I(be,$),I(we,q),I(we,G))),A(e,"ADD_TAGS")||(Te.tagCheck=null),A(e,"ADD_ATTR")||(Te.attributeCheck=null),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?Te.tagCheck=e.ADD_TAGS:(be===ve&&(be=R(be)),I(be,e.ADD_TAGS,lt))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?Te.attributeCheck=e.ADD_ATTR:(we===xe&&(we=R(we)),I(we,e.ADD_ATTR,lt))),e.ADD_URI_SAFE_ATTR&&I(Ye,e.ADD_URI_SAFE_ATTR,lt),e.FORBID_CONTENTS&&(We===qe&&(We=R(We)),I(We,e.FORBID_CONTENTS,lt)),e.ADD_FORBID_CONTENTS&&(We===qe&&(We=R(We)),I(We,e.ADD_FORBID_CONTENTS,lt)),ze&&(be["#text"]=!0),je&&I(be,["html","head","body"]),be.table&&(I(be,["tbody"]),delete Ee.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw O('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw O('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=e.TRUSTED_TYPES_POLICY,ee=Q.createHTML("")}else void 0===Q&&(Q=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(L,i)),null!==Q&&"string"==typeof ee&&(ee=Q.createHTML(""));h&&h(e),ct=e}},pt=I({},[...N,...U,...F]),ft=I({},[...$,...z]),gt=function(e){b(r.removed,{element:e});try{X(e).removeChild(e)}catch(t){Y(e)}},mt=function(e,t){try{b(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){b(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(De||Ne)try{gt(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},yt=function(e){let t=null,r=null;if(Me)e="<remove></remove>"+e;else{const t=S(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===ot&&Qe===Ze&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const s=Q?Q.createHTML(e):e;if(Qe===Ze)try{t=(new P).parseFromString(s,ot)}catch(e){}if(!t||!t.documentElement){t=re.createDocument(Qe,"template",null);try{t.documentElement.innerHTML=et?ee:s}catch(e){}}const i=t.body||t.documentElement;return e&&r&&i.insertBefore(n.createTextNode(r),i.childNodes[0]||null),Qe===Ze?ae.call(t,je?"html":"body")[0]:je?t.documentElement:i},_t=function(e){return ie.call(e.ownerDocument||e,e,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},bt=function(e){return e instanceof g&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof f)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},vt=function(e){return"function"==typeof c&&e instanceof c};function wt(e,t,n){m(e,e=>{e.call(r,t,n,ct)})}const xt=function(e){let t=null;if(wt(ce.beforeSanitizeElements,e,null),bt(e))return gt(e),!0;const n=lt(e.nodeName);if(wt(ce.uponSanitizeElement,e,{tagName:n,allowedTags:be}),Ie&&e.hasChildNodes()&&!vt(e.firstElementChild)&&k(/<[/\w!]/g,e.innerHTML)&&k(/<[/\w!]/g,e.textContent))return gt(e),!0;if(7===e.nodeType)return gt(e),!0;if(Ie&&8===e.nodeType&&k(/<[/\w]/g,e.data))return gt(e),!0;if(!(Te.tagCheck instanceof Function&&Te.tagCheck(n))&&(!be[n]||Ee[n])){if(!Ee[n]&&Et(n)){if(Se.tagNameCheck instanceof RegExp&&k(Se.tagNameCheck,n))return!1;if(Se.tagNameCheck instanceof Function&&Se.tagNameCheck(n))return!1}if(ze&&!We[n]){const t=X(e)||e.parentNode,r=V(e)||e.childNodes;if(r&&t)for(let n=r.length-1;n>=0;--n){const s=J(r[n],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,K(e))}}return gt(e),!0}return e instanceof u&&!function(e){let t=X(e);t&&t.tagName||(t={namespaceURI:Qe,tagName:"template"});const r=w(e.tagName),n=w(t.tagName);return!!tt[e.namespaceURI]&&(e.namespaceURI===Xe?t.namespaceURI===Ze?"svg"===r:t.namespaceURI===Ve?"svg"===r&&("annotation-xml"===n||nt[n]):Boolean(pt[r]):e.namespaceURI===Ve?t.namespaceURI===Ze?"math"===r:t.namespaceURI===Xe?"math"===r&&st[n]:Boolean(ft[r]):e.namespaceURI===Ze?!(t.namespaceURI===Xe&&!st[n])&&!(t.namespaceURI===Ve&&!nt[n])&&!ft[r]&&(it[r]||!pt[r]):!("application/xhtml+xml"!==ot||!tt[e.namespaceURI]))}(e)?(gt(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!k(/<\/no(script|embed|frames)/i,e.innerHTML)?(Le&&3===e.nodeType&&(t=e.textContent,m([ue,he,de],e=>{t=E(t,e," ")}),e.textContent!==t&&(b(r.removed,{element:e.cloneNode()}),e.textContent=t)),wt(ce.afterSanitizeElements,e,null),!1):(gt(e),!0)},St=function(e,t,r){if(Ce[t])return!1;if(Fe&&("id"===t||"name"===t)&&(r in n||r in ut))return!1;if(ke&&!Ce[t]&&k(pe,t));else if(Ae&&k(fe,t));else if(Te.attributeCheck instanceof Function&&Te.attributeCheck(t,e));else if(!we[t]||Ce[t]){if(!(Et(e)&&(Se.tagNameCheck instanceof RegExp&&k(Se.tagNameCheck,e)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(e))&&(Se.attributeNameCheck instanceof RegExp&&k(Se.attributeNameCheck,t)||Se.attributeNameCheck instanceof Function&&Se.attributeNameCheck(t,e))||"is"===t&&Se.allowCustomizedBuiltInElements&&(Se.tagNameCheck instanceof RegExp&&k(Se.tagNameCheck,r)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(r))))return!1}else if(Ye[t]);else if(k(_e,E(r,me,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==C(r,"data:")||!Ge[e])if(Oe&&!k(ge,E(r,me,"")));else if(r)return!1;return!0},Et=function(e){return"annotation-xml"!==e&&S(e,ye)},Ct=function(e){wt(ce.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||bt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we,forceKeepAttr:void 0};let s=t.length;for(;s--;){const i=t[s],{name:o,namespaceURI:a,value:l}=i,c=lt(o),u=l;let h="value"===o?u:T(u);if(n.attrName=c,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,wt(ce.uponSanitizeAttribute,e,n),h=n.attrValue,!$e||"id"!==c&&"name"!==c||(mt(o,e),h="user-content-"+h),Ie&&k(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,h)){mt(o,e);continue}if("attributename"===c&&S(h,"href")){mt(o,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){mt(o,e);continue}if(!Pe&&k(/\/>/i,h)){mt(o,e);continue}Le&&m([ue,he,de],e=>{h=E(h,e," ")});const d=lt(e.nodeName);if(St(d,c,h)){if(Q&&"object"==typeof L&&"function"==typeof L.getAttributeType)if(a);else switch(L.getAttributeType(d,c)){case"TrustedHTML":h=Q.createHTML(h);break;case"TrustedScriptURL":h=Q.createScriptURL(h)}if(h!==u)try{a?e.setAttributeNS(a,o,h):e.setAttribute(o,h),bt(e)?gt(e):_(r.removed)}catch(t){mt(o,e)}}else mt(o,e)}wt(ce.afterSanitizeAttributes,e,null)},Tt=function e(t){let r=null;const n=_t(t);for(wt(ce.beforeSanitizeShadowDOM,t,null);r=n.nextNode();)wt(ce.uponSanitizeShadowNode,r,null),xt(r),Ct(r),r.content instanceof a&&e(r.content);wt(ce.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,o=null,l=null;if(et=!e,et&&(e="\x3c!--\x3e"),"string"!=typeof e&&!vt(e)){if("function"!=typeof e.toString)throw O("toString is not a function");if("string"!=typeof(e=e.toString()))throw O("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Re||dt(t),r.removed=[],"string"==typeof e&&(He=!1),He){if(e.nodeName){const t=lt(e.nodeName);if(!be[t]||Ee[t])throw O("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)n=yt("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),1===i.nodeType&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!De&&!Le&&!je&&-1===e.indexOf("<"))return Q&&Ue?Q.createHTML(e):e;if(n=yt(e),!n)return De?null:Ue?ee:""}n&&Me&>(n.firstChild);const u=_t(He?e:n);for(;o=u.nextNode();)xt(o),Ct(o),o.content instanceof a&&Tt(o.content);if(He)return e;if(De){if(Ne)for(l=oe.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(we.shadowroot||we.shadowrootmode)&&(l=le.call(s,l,!0)),l}let h=je?n.outerHTML:n.innerHTML;return je&&be["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&k(te,n.ownerDocument.doctype.name)&&(h="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+h),Le&&m([ue,he,de],e=>{h=E(h,e," ")}),Q&&Ue?Q.createHTML(h):h},r.setConfig=function(){dt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Re=!0},r.clearConfig=function(){ct=null,Re=!1},r.isValidAttribute=function(e,t,r){ct||dt({});const n=lt(e),s=lt(t);return St(n,s,r)},r.addHook=function(e,t){"function"==typeof t&&b(ce[e],t)},r.removeHook=function(e,t){if(void 0!==t){const r=y(ce[e],t);return-1===r?void 0:v(ce[e],r,1)[0]}return _(ce[e])},r.removeHooks=function(e){ce[e]=[]},r.removeAllHooks=function(){ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}(),oe=r(314),ae=r.n(oe);const le=/([\p{Ll}\d])(\p{Lu})/gu,ce=/(\p{Lu})([\p{Lu}][\p{Ll}])/gu,ue=/(\d)\p{Ll}|(\p{L})\d/u,he=/[^\p{L}\d]+/giu,de="$1\0$2";function pe(e){let t=e.trim();t=t.replace(le,de).replace(ce,de),t=t.replace(he,"\0");let r=0,n=t.length;for(;"\0"===t.charAt(r);)r++;if(r===n)return[];for(;"\0"===t.charAt(n-1);)n--;return t.slice(r,n).split(/\0/g)}function fe(e){const t=pe(e);for(let e=0;e<t.length;e++){const r=t[e],n=ue.exec(r);if(n){const s=n.index+(n[1]??n[2]).length;t.splice(e,1,r.slice(0,s),r.slice(s))}}return t}function ge(e,t){const[r,n,s]=function(e,t={}){const r=t.split??(t.separateNumbers?fe:pe),n=t.prefixCharacters??"",s=t.suffixCharacters??"";let i=0,o=e.length;for(;i<e.length;){const t=e.charAt(i);if(!n.includes(t))break;i++}for(;o>i;){const t=o-1,r=e.charAt(t);if(!s.includes(r))break;o=t}return[e.slice(0,i),r(e.slice(i,o)),e.slice(o)]}(e,t);return r+n.map((i=t?.locale,!1===i?e=>e.toLowerCase():e=>e.toLocaleLowerCase(i))).join(t?.delimiter??" ")+s;var i}function me(e){this?.sdk&&e&&(this.sdk=Object.assign({},this.sdk,e))}const ye="win32"===navigator.platform.toLowerCase()?i.win32:i.posix,_e=!1,be="file://",ve="lsp://",we=ve+"logseq.io/plugins/",xe=ve+"logseq.io/external/",Se=ve+"logseq.com/plugins/",Ee=ve+"logseq.com/external/";let Ce;const Te=function(e,t){return ge(e,{delimiter:"_",...t})};async function Ae(){return Ce||(Ce=await ze("_callApplication","getAppPath"))}async function ke(){return _e?localStorage.getItem("LSP_DEV_SDK_ROOT")||"http://localhost:8080":Ue(await Ae(),"js")}function Oe(e){return e===Object(e)&&!Array.isArray(e)}function Pe(e,t){return ae()(e,t,{arrayMerge:(e,t)=>t})}const Le={DEBUG:10,INFO:20,WARN:30,ERROR:40};function Ie(e){if(null==e)return String(e);if(e instanceof Error)return`${e.message}${e.stack?"\n"+e.stack:""}`;if("string"==typeof e)return e;if("object"==typeof e)try{const t=new WeakSet;return JSON.stringify(e,(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r})}catch(t){try{return String(e)}catch(e){return"[Unserializable]"}}try{return String(e)}catch(e){return"[Unserializable]"}}class je extends s{_tag;_opts;_logs=[];_maxSize;_level;constructor(e,t){super(),this._tag=e,this._opts=t,this._maxSize=Math.max(50,t?.maxSize??500),this._level=t?.level??"DEBUG"}write(e,t,r){Array.isArray(t)&&t.length&&!0===t[t.length-1]&&(r=!0,t=t.slice(0,-1));const n="string"==typeof e?e.toUpperCase():e,s=n in Le?n:"INFO";if(Le[s]<Le[this._level])return;const i=(t||[]).map(Ie).join(" "),o={ts:Date.now(),level:s,tag:this._tag||"",message:i};if(this._logs.push(o),this._logs.length>this._maxSize&&this._logs.splice(0,this._logs.length-this._maxSize),r||this._opts?.console){const e="ERROR"===s?"error":"WARN"===s?"warn":"DEBUG"===s?"debug":"info";try{console[e](`[${o.tag}][${new Date(o.ts).toLocaleTimeString()}] ${s}: ${i}`)}catch(e){}}this.emit("append",o),this.emit("change")}clear(){this._logs=[],this.emit("clear"),this.emit("change")}debug(...e){this.write("DEBUG",e)}info(...e){this.write("INFO",e)}warn(...e){this.write("WARN",e)}error(...e){this.write("ERROR",e)}setTag(e){this._tag=e}getTag(){return this._tag}setLevel(e){e in Le&&(this._level=e)}getLevel(){return this._level}setMaxSize(e){this._maxSize=Math.max(50,0|e),this._logs.length>this._maxSize&&(this._logs.splice(0,this._logs.length-this._maxSize),this.emit("change"))}getEntries(){return this._logs.slice()}toJSON(){return this._logs.map(e=>[e.level,`[${e.tag}][${new Date(e.ts).toLocaleTimeString()}] ${e.message}`])}}function Re(e){return"string"==typeof e&&36===e.length&&/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi.test(e)}function Me(){return"_"+Math.random().toString(36).substr(2,9)}function De(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ne(e){return e?(/^(http|file|lsp)/.test(e)||(e=be+e),e):""}function Ue(e,...t){try{const r=new URL(e);if(!r.origin)throw new Error(null);const n=ye.join(e.substr(r.origin.length),...t);return r.origin+n}catch(r){return ye.join(e,...t)}}function Fe(e){return e?.match(/^(http?|lsp|assets):/)||(e=ye.normalize(e)),e}function $e(e,t){let r,n,s=!1;const i=t=>r=>{e&&clearTimeout(e),t(r),s=!0},o=new Promise((s,o)=>{r=i(s),n=i(o),e&&(e=setTimeout(()=>n(new Error(`[deferred timeout] ${t}`)),e))});return{created:Date.now(),setTag:e=>t=e,resolve:r,reject:n,promise:o,get settled(){return s}}}function ze(t,...r){t=t?.startsWith("_call")?t:t?.replace(/^[_$]+/,"");let n=Te(t);const s=window.logseq?.sdk,i=s&&Object.keys(s);let o={};const a=n?.split("_")?.[0];a&&i.includes(a)&&(n=n.replace(new RegExp(`^${a}_`),""),o=s?.[a]);const l=Object.assign({},window.logseq?.api,o,e),c=l[n]||window.apis[n]||l[t]||window.apis[t];if(!c)throw new Error(`Not existed method #${t}`);return"function"!=typeof c?c:c.apply(this,r)}function He(e,t){const r=t["data-injected-style"];let n=r&&document.querySelector(`[data-injected-style=${r}]`);if(!n)return n=document.createElement("style"),n.textContent=e,t&&Object.entries(t).forEach(([e,t])=>{n.setAttribute(e,t)}),document.head.append(n),()=>{document.head.removeChild(n)};n.textContent=e}const Be=new Map;function We(e,t,r){let n,s,i="";const o=this;"slot"in e?(i=e.slot,n=`#${i}`):"path"in e?n=e.path:s=!0;const a=`${o.id}--${e.key||Me()}`,l=a,c=s?document.body:n&&document.querySelector(n);if(!c)return console.error(`${this.debugTag} can not resolve selector target ${n}`),!1;if(!e.template)return void Be.get(a)?.call(null);e.template=ie.sanitize(e.template,{ADD_TAGS:["iframe"],ALLOW_UNKNOWN_PROTOCOLS:!0,ADD_ATTR:["allow","src","allowfullscreen","frameborder","scrolling","target"]});let u,h,d=document.querySelector(`#${a}`),p=s?d?.querySelector(".ls-ui-float-content"):d;if(p){p.innerHTML=e.template,t&&Object.entries(t).forEach(([e,t])=>{d.setAttribute(e,t)});let r=null!=d.dataset.dx;return void(e.style&&Object.entries(e.style).forEach(([e,t])=>{r&&["left","top","bottom","right","width","height"].includes(e)||(d.style[e]=t)}))}if(d=document.createElement("div"),d.id=a,d.dataset.injectedUi=l||"",s?(p=document.createElement("div"),p.classList.add("ls-ui-float-content"),d.appendChild(p)):p=d,p.innerHTML=e.template,t&&Object.entries(t).forEach(([e,t])=>{d.setAttribute(e,t)}),e.style&&Object.entries(e.style).forEach(([e,t])=>{d.style[e]=t}),s&&(d.setAttribute("draggable","true"),d.setAttribute("resizable","true"),e.close&&(d.dataset.close=e.close),d.classList.add("lsp-ui-float-container","visible"),o._setupResizableContainer(d,l),h=o._setupDraggableContainer(d,{key:l,close:()=>u(),title:t?.title})),i&&e.reset){const e=Array.from(c.querySelectorAll("[data-injected-ui]")).map(e=>e.id);e?.forEach(e=>{Be.get(e)?.call(null)})}return c.appendChild(d),["click","focus","focusin","focusout","blur","dblclick","keyup","keypress","keydown","change","input","contextmenu"].forEach(e=>{d.addEventListener(e,t=>{const r=t.target.closest(`[data-on-${e}]`);if(!r)return;const{preventDefault:n}=r.dataset,s=r.dataset[`on${De(e)}`];s&&o.caller?.callUserModel(s,Je(r,t)),"true"===n?.toLowerCase()&&t.preventDefault()},!1)}),r?.({el:d,float:s}),u=()=>{h?.(),Be.delete(a),c.removeChild(d)},Be.set(a,u),u}function qe(e){if(!Be.has(e))return;const t=Be.get(e);try{t()}catch(t){console.warn("[CLEAN Injected UI] ",e,t)}}function Ge(){const e=document.head.querySelectorAll(`script[data-ref=${this.id}]`);e?.forEach(e=>e.remove())}function Je(e,t){const r={};if(e){r.type=t.type;const n=e.dataset,s="rect";["value","id","className","dataset",s].forEach(t=>{let i;if(t===s){if(!n.hasOwnProperty(s))return;i=e.getBoundingClientRect().toJSON()}else i=e[t];"object"==typeof i&&(i={...i}),r[t]=i})}return r}function Ye(e){const t=document.createElement("link");return t.rel="stylesheet",t.href=e,document.head.appendChild(t),()=>{try{document.head.removeChild(t)}catch(e){console.error(e)}}}function Ke(e,t){const r=(t||[]).reduce((e,t)=>("default"in t&&(e[t.key]=t.default),e),{});return Object.assign(r,e)}function Ve(e){if("string"==typeof e)return e.trim().replace(/\s/g,"_").toLowerCase()}window.__injectedUIEffects=Be;var Xe=r(221),Ze=r.n(Xe);const Qe="application/x-postmate-v1+json";let et=0;const tt={handshake:1,"handshake-reply":1,call:1,emit:1,reply:1,request:1},rt=(e,t)=>!("string"==typeof t&&"*"!==t&&e.origin!==t||!e.data||"object"==typeof e.data&&!("postmate"in e.data)||e.data.type!==Qe||!tt[e.data.postmate]);class nt{parent;frame;child;events={};childOrigin;listener;messagePort;addTransportListener(e){this.messagePort?(console.debug("[DEBUG] Using MessagePort for communication:",this.frame.src),this.messagePort.addEventListener("message",e),this.messagePort.start?.()):(console.debug("[DEBUG] Using postMessage for communication:",this.frame.src),this.parent.addEventListener("message",e,!1))}removeTransportListener(e){this.messagePort?this.messagePort.removeEventListener("message",e):this.parent.removeEventListener("message",e,!1)}postToChild(e){this.messagePort?this.messagePort.postMessage(e):this.child.postMessage(e,this.childOrigin)}constructor(e){this.parent=e.parent,this.frame=e.frame,this.child=e.child,this.childOrigin=e.childOrigin,this.messagePort=e.messagePort,this.listener=e=>{if(this.messagePort){if(!e?.data)return!1;if("object"==typeof e.data&&!("postmate"in e.data))return!1;if(e.data.type!==Qe)return!1;if(!tt[e.data.postmate])return!1}else if(!rt(e,this.childOrigin))return!1;const{data:t,name:r}=((e||{}).data||{}).value||{};"emit"===e.data.postmate&&r in this.events&&this.events[r].forEach(e=>{e.call(this,t)})},this.addTransportListener(this.listener)}get(e,...t){return new Promise((r,n)=>{const s=++et,i="number"==typeof it.requestTimeout?it.requestTimeout:1e4;let o;const a=e=>{e?.data?.uid===s&&"reply"===e.data.postmate&&(this.removeTransportListener(a),o&&clearTimeout(o),e.data.error?n(e.data.error):r(e.data.value))};this.addTransportListener(a),i>0&&(o=setTimeout(()=>{this.removeTransportListener(a),n(new Error(`Postmate: request timeout (${i}ms)`))},i)),this.postToChild({postmate:"request",type:Qe,property:e,args:t,uid:s})})}call(e,t){this.postToChild({postmate:"call",type:Qe,property:e,data:t})}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}destroy(){this.removeTransportListener(this.listener);try{this.messagePort?.close()}catch(e){}this.frame.parentNode.removeChild(this.frame)}}class st{model;parent;parentOrigin;child;messagePort;listener;addTransportListener(e){this.messagePort?(this.messagePort.addEventListener("message",e),this.messagePort.start?.()):this.child.addEventListener("message",e,!1)}postToParent(e,t){if(this.messagePort)this.messagePort.postMessage(e);else if(t?.source){const r="null"===t.origin?"*":t.origin;t.source.postMessage(e,r)}else this.parent.postMessage(e,this.parentOrigin)}constructor(e){if(this.model=e.model,this.parent=e.parent,this.parentOrigin=e.parentOrigin,this.child=e.child,this.messagePort=e.messagePort,this.listener=e=>{if(this.messagePort){if(!e?.data)return;if("object"==typeof e.data&&!("postmate"in e.data))return;if(e.data.type!==Qe)return;if(!tt[e.data.postmate])return}else if(!rt(e,this.parentOrigin))return;const{property:t,uid:r,data:n,args:s}=e.data;"call"!==e.data.postmate?((e,t,r)=>{const n="function"==typeof e[t]?e[t].apply(null,r):e[t];return Promise.resolve(n)})(this.model,t,s).then(n=>{this.postToParent({property:t,postmate:"reply",type:Qe,uid:r,value:n},e)}).catch(n=>{this.postToParent({property:t,postmate:"reply",type:Qe,uid:r,error:n},e)}):t in this.model&&"function"==typeof this.model[t]&&this.model[t](n)},this.addTransportListener(this.listener),!this.messagePort){const e=t=>{const r=t.detail?.port;r&&(this.child.removeEventListener("message",this.listener,!1),this.messagePort=r,this.messagePort.addEventListener("message",this.listener),this.messagePort.start?.(),this.child.removeEventListener("postmate:channel-ready",e))};this.child.addEventListener("postmate:channel-ready",e)}}emit(e,t){this.postToParent({postmate:"emit",type:Qe,value:{name:e,data:t}})}}class it{static debug=!1;static requestTimeout=1e4;container;parent;frame;child;childOrigin;url;model;static Model;messagePort;enableMessageChannel;constructor(e){this.container=e.container,this.url=e.url,this.parent=window,this.frame=document.createElement("iframe"),e.id&&(this.frame.id=e.id),e.name&&(this.frame.name=e.name),e.allow&&(this.frame.allow=e.allow),this.frame.classList.add.apply(this.frame.classList,e.classListArray||[]),this.container.appendChild(this.frame),this.child=this.frame.contentWindow,this.model=e.model||{},this.enableMessageChannel=!!e.enableMessageChannel}sendHandshake(e){const t=(e=>{const t=document.createElement("a");if(t.href=e,"file:"===t.protocol)return"*";const r=t.protocol.length>4?t.protocol:window.location.protocol,n=t.host.length?"80"===t.port||"443"===t.port?t.hostname:t.host:window.location.host;return t.origin||`${r}//${n}`})(e=e||this.url);let r,n=0;return new Promise((s,i)=>{const o="undefined"!=typeof MessageChannel&&"function"==typeof MessageChannel,a=this.enableMessageChannel&&o,l=e=>{if(!rt(e,t))return!1;if("handshake-reply"===e.data.postmate){if(clearInterval(r),this.parent.removeEventListener("message",l,!1),this.childOrigin=e.origin,a)if(e?.ports?.length){const t=e.ports[0];t&&(this.messagePort=t,this.messagePort.start?.())}else if(e.data.acceptsMessageChannel){const e=new MessageChannel;this.messagePort=e.port1,this.messagePort.start?.(),this.child.postMessage({postmate:"setup-channel",type:Qe},t,[e.port2])}return s(new nt(this))}return i("Failed handshake")};this.parent.addEventListener("message",l,!1);const c=()=>{n++;const e={postmate:"handshake",type:Qe,model:this.model,enableMessageChannel:a?1:0};this.child.postMessage(e,t),5===n&&clearInterval(r)};this.frame.addEventListener("load",()=>{c(),r=setInterval(c,500)}),this.frame.src=e})}destroy(){try{this.messagePort?.close()}catch(e){}this.frame.parentNode.removeChild(this.frame)}}class ot{child;model;parent;parentOrigin;messagePort;enableMessageChannel;constructor(e){this.child=window,this.model=e,this.parent=this.child.parent,this.enableMessageChannel=!1}sendHandshakeReply(){return new Promise((e,t)=>{const r=n=>{if(n.data.postmate){if("handshake"===n.data.postmate){this.child.removeEventListener("message",r,!1),this.enableMessageChannel=!!n.data?.enableMessageChannel,this.parentOrigin=n.origin;const t="undefined"!=typeof MessageChannel&&"function"==typeof MessageChannel;n.source.postMessage({postmate:"handshake-reply",type:Qe,acceptsMessageChannel:this.enableMessageChannel&&t?1:0},"null"===n.origin?"*":n.origin);const s=n.data.model;if(s&&Object.keys(s).forEach(e=>{this.model[e]=s[e]}),this.enableMessageChannel&&t){const e=t=>{if("setup-channel"===t.data?.postmate&&t.data?.type===Qe&&t.origin===this.parentOrigin){const r=t?.ports?.[0];r&&(this.messagePort=r,this.messagePort.start?.(),this.child.dispatchEvent(new CustomEvent("postmate:channel-ready",{detail:{port:this.messagePort}}))),this.child.removeEventListener("message",e,!1)}};this.child.addEventListener("message",e,!1)}return e(new st(this))}return t("Handshake Reply Failed")}};this.child.addEventListener("message",r,!1)})}}class at{ctx;opts;constructor(e,t){this.ctx=e,this.opts=t}get ctxId(){return this.ctx.baseInfo.id}setItem(e,t){return this.ctx.caller.callAsync("api:call",{method:"write-plugin-storage-file",args:[this.ctxId,e,t,this.opts?.assets]})}getItem(e){return this.ctx.caller.callAsync("api:call",{method:"read-plugin-storage-file",args:[this.ctxId,e,this.opts?.assets]})}removeItem(e){return this.ctx.caller.callAsync("api:call",{method:"unlink-plugin-storage-file",args:[this.ctxId,e,this.opts?.assets]})}allKeys(){return this.ctx.caller.callAsync("api:call",{method:"list-plugin-storage-files",args:[this.ctxId,this.opts?.assets]})}clear(){return this.ctx.caller.callAsync("api:call",{method:"clear-plugin-storage-files",args:[this.ctxId,this.opts?.assets]})}hasItem(e){return this.ctx.caller.callAsync("api:call",{method:"exist-plugin-storage-file",args:[this.ctxId,e,this.opts?.assets]})}}class lt{ctx;constructor(e){this.ctx=e}get React(){return this.ensureHostScope().React}get ReactDOM(){return this.ensureHostScope().ReactDOM}get Components(){return{Editor:this.ensureHostScope().logseq.sdk.experiments.cp_page_editor}}get Utils(){const e=this.ensureHostScope().logseq.sdk.utils,t=t=>e[Te(t)];return{toClj:t("toClj"),jsxToClj:t("jsxToClj"),toJs:t("toJs"),toKeyword:t("toKeyword"),toSymbol:t("toSymbol")}}get pluginLocal(){return this.ensureHostScope().LSPluginCore.ensurePlugin(this.ctx.baseInfo.id)}invokeExperMethod(e,...t){const r=this.ensureHostScope();e=Te(e)?.toLowerCase();const n=r.logseq.api["exper_"+e]||r.logseq.sdk.experiments[e];return n?.apply(r,t)}async loadScripts(...e){(e=e.map(e=>e?.startsWith("http")?e:this.ctx.resolveResourceFullUrl(e))).unshift(this.ctx.baseInfo.id),await this.invokeExperMethod("loadScripts",...e)}registerFencedCodeRenderer(e,t){return this.invokeExperMethod("registerFencedCodeRenderer",this.ctx.baseInfo.id,e,t)}registerDaemonRenderer(e,t){return this.invokeExperMethod("registerDaemonRenderer",this.ctx.baseInfo.id,e,t)}registerHostedRenderer(e,t){return this.invokeExperMethod("registerHostedRenderer",this.ctx.baseInfo.id,e,t)}registerSidebarRenderer(e,t){return e=`_sidebar.${e}`,t.type="sidebar",this.registerHostedRenderer(e,t)}registerRouteRenderer(e,t){return this.invokeExperMethod("registerRouteRenderer",this.ctx.baseInfo.id,e,t)}registerBlockPropertiesRenderer(e,t){return this.invokeExperMethod("registerBlockPropertiesRenderer",this.ctx.baseInfo.id,e,t)}registerBlockRenderer(e,t){return this.invokeExperMethod("registerBlockRenderer",this.ctx.baseInfo.id,e,t)}registerExtensionsEnhancer(e,t){const r=this.ensureHostScope();return"katex"===e&&r.katex&&t(r.katex).catch(console.error),this.invokeExperMethod("registerExtensionsEnhancer",this.ctx.baseInfo.id,e,t)}ensureHostScope(){try{window.top}catch(e){console.error("Can not access host scope!")}return window.top}}const ct=e=>`task_callback_${e}`;function ut(){const e=new Error("The request was aborted");return e.name="AbortError",e}function ht(e){return new Promise(t=>setTimeout(t,e))}function dt(e){return(new TextDecoder).decode(e)}function pt(e){const t={};return e.forEach((e,r)=>{t[r]=e}),t}function ft(e){if(null!=e)return"string"==typeof e||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e:JSON.stringify(e)}class gt{_payload;_responseType;constructor(e,t){this._payload=e,this._responseType=t}get status(){return this._payload.status}get statusText(){return this._payload.statusText}get ok(){return this._payload.ok}get url(){return this._payload.url}get headers(){return this._payload.headers}get body(){return this._payload.body}async json(){const{body:e}=this._payload;return"json"===this._responseType?e:"string"==typeof e?JSON.parse(e):e instanceof ArrayBuffer?JSON.parse(dt(e)):e}async text(){const{body:e}=this._payload;return"string"==typeof e?e:e instanceof ArrayBuffer?dt(e):JSON.stringify(e)}async arrayBuffer(){const{body:e}=this._payload;return e instanceof ArrayBuffer?e:"base64"===this._responseType&&"string"==typeof e?function(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}(e):(t="string"==typeof e?e:JSON.stringify(e),(new TextEncoder).encode(t).buffer);var t}clone(){return new gt({status:(e=this).status,statusText:e.statusText,ok:e.ok,url:e.url,headers:{...e.headers},body:e.body},this._responseType);var e}}class mt extends Error{response;constructor(e){super(`HTTP request failed with status ${e.status} ${e.statusText}`.trim()),this.response=e,this.name="LSPluginNetError"}get status(){return this.response.status}get statusText(){return this.response.statusText}get url(){return this.response.url}get headers(){return this.response.headers}get body(){return this.response.body}}function yt(e){if(e.status>=200&&e.status<300)return e.body;throw new mt(e)}class _t{_ctx;_cache=new Map;_events=new EventTarget;constructor(e){this._ctx=e,this._ctx.caller.on("#lsp#request#callback",e=>{const t=e?.requestId;t&&this._events.dispatchEvent(new CustomEvent(ct(t),{detail:e?.payload}))})}async request(e){const t=(e.method||"GET").toUpperCase(),r="arrayBuffer"===(n=e.responseType)?"arraybuffer":n||"json";var n;const s=this.normalizeRetry(e.retry),i=this.getCacheKey(e,t,r);if(i){const e=this._cache.get(i);if(e&&e.expires>Date.now())return this._cache.delete(i),this._cache.set(i,e),e.response.clone();e&&this._cache.delete(i)}let o=0;for(;;)try{const n=await this.performRequest(e,t,r);if(o<s.retries&&this.shouldRetry(s,n)){await ht(s.delay*Math.pow(s.factor,o++));continue}return i&&(this.pruneCache(this.getCacheMaxEntries(e.cache)),this._cache.set(i,{expires:Date.now()+this.getCacheTTL(e.cache),response:n.clone()})),n}catch(t){if(e.signal?.aborted||o>=s.retries||!this.shouldRetry(s,t))throw t;await ht(s.delay*Math.pow(s.factor,o++))}}get(e,t){return this.requestWithMethod("GET",e,t)}head(e,t){return this.requestWithMethod("HEAD",e,t)}post(e,t,r){return this.requestWithBody("POST",e,t,r)}put(e,t,r){return this.requestWithBody("PUT",e,t,r)}patch(e,t,r){return this.requestWithBody("PATCH",e,t,r)}delete(e,t){return this.requestWithMethod("DELETE",e,t)}requestWithMethod(e,t,r={}){return this.request({...r,url:t,method:e}).then(yt)}requestWithBody(e,t,r,n={}){const s=void 0===r?n.body:r;return this.request({...n,url:t,method:e,body:s}).then(yt)}async performRequest(e,t,r){if(this.shouldUseFetchFallback())return this.performFetchRequest(e,t,r);try{return await this.performProxyRequest(e,t,r)}catch(n){if(this.shouldFallbackAfterProxyError(n))return this.performFetchRequest(e,t,r);throw n}}async performProxyRequest(e,t,r){if(e.signal?.aborted)throw ut();const n=Boolean(e.abortable||e.signal),s=await this._ctx._execCallableAPIAsync("exper_request",this._ctx.baseInfo.id,{url:e.url,method:t,headers:e.headers,data:e.body??e.data,timeout:e.timeout,returnType:r,abortable:n,includeResponse:!0});if(!s)throw new Error("Host HTTP request proxy is not available");const i=ct(s),o=new Promise((e,t)=>{const r=n=>{const s=n.detail;this._events.removeEventListener(i,r),s&&s instanceof Error?t(s):e(s)};this._events.addEventListener(i,r,{once:!0})}),a=()=>this.abortProxyRequest(s,n);e.signal?.addEventListener("abort",a,{once:!0});try{const e=await o;return new gt(e,r)}finally{e.signal?.removeEventListener("abort",a)}}abortProxyRequest(e,t){t&&this._ctx._execCallableAPI("http_request_abort",e)}async performFetchRequest(e,t,r){if("function"!=typeof fetch)throw new Error("Browser fetch is not available");if(e.signal?.aborted)throw ut();const n="number"==typeof e.timeout&&e.timeout>0?e.timeout:void 0,s=n||e.signal?new AbortController:null,i=()=>s?.abort(),o=n?setTimeout(i,n):null;e.signal?.addEventListener("abort",i,{once:!0});try{const n=await fetch(e.url,{method:t,headers:e.headers,body:["GET","HEAD"].includes(t)?void 0:ft(e.body??e.data),signal:s?.signal||e.signal}),i=await this.readFetchBody(n,t,r);return new gt({status:n.status,statusText:n.statusText,ok:n.ok,url:n.url,headers:pt(n.headers),body:i},r)}finally{o&&clearTimeout(o),e.signal?.removeEventListener("abort",i)}}async readFetchBody(e,t,r){if("HEAD"===t||204===e.status||205===e.status)return null;switch(r){case"json":return await e.json();case"text":return await e.text();case"arraybuffer":return await e.arrayBuffer();case"base64":return function(e){const t=new Uint8Array(e);let r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}(await e.arrayBuffer())}}shouldUseFetchFallback(){return Boolean(this._ctx.baseInfo?.webMode)}shouldFallbackAfterProxyError(e){return null==e&&"function"==typeof fetch}normalizeRetry(e){return"number"==typeof e?{retries:Math.max(0,e),delay:300,factor:2}:{retries:Math.max(0,e?.retries||0),delay:e?.delay||300,factor:e?.factor||2,retryOn:e?.retryOn}}shouldRetry(e,t){const{retryOn:r}=e;return"function"==typeof r?r(t):!(t instanceof gt)||(Array.isArray(r)?r.includes(t.status):429===t.status||t.status>=500)}getCacheKey(e,t,r){return e.cache&&["GET","HEAD"].includes(t)?"object"==typeof e.cache&&e.cache.key?e.cache.key:JSON.stringify({method:t,url:e.url,headers:e.headers||{},responseType:r}):null}getCacheTTL(e){return"object"==typeof e&&"number"==typeof e.ttl?Math.max(0,e.ttl):3e5}getCacheMaxEntries(e){return"object"==typeof e&&"number"==typeof e.maxEntries?Math.max(1,e.maxEntries):100}pruneCache(e){for(;this._cache.size>=e;){const e=this._cache.keys().next().value;if(!e)return;this._cache.delete(e)}}get ctx(){return this._ctx}}const bt=Array.isArray,vt="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g;var wt="object"==typeof self&&self&&self.Object===Object&&self;const xt=vt||wt||Function("return this")(),St=xt.Symbol;var Et=Object.prototype,Ct=Et.hasOwnProperty,Tt=Et.toString,At=St?St.toStringTag:void 0;var kt=Object.prototype.toString;var Ot=St?St.toStringTag:void 0;const Pt=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Ot&&Ot in Object(e)?function(e){var t=Ct.call(e,At),r=e[At];try{e[At]=void 0;var n=!0}catch(e){}var s=Tt.call(e);return n&&(t?e[At]=r:delete e[At]),s}(e):function(e){return kt.call(e)}(e)},Lt=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},It=function(e){if(!Lt(e))return!1;var t=Pt(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},jt=xt["__core-js_shared__"];var Rt,Mt=(Rt=/[^.]+$/.exec(jt&&jt.keys&&jt.keys.IE_PROTO||""))?"Symbol(src)_1."+Rt:"";var Dt=Function.prototype.toString;const Nt=function(e){if(null!=e){try{return Dt.call(e)}catch(e){}try{return e+""}catch(e){}}return""};var Ut=/^\[object .+?Constructor\]$/,Ft=Function.prototype,$t=Object.prototype,zt=Ft.toString,Ht=$t.hasOwnProperty,Bt=RegExp("^"+zt.call(Ht).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");const Wt=function(e){return!(!Lt(e)||(t=e,Mt&&Mt in t))&&(It(e)?Bt:Ut).test(Nt(e));var t},qt=function(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Wt(r)?r:void 0},Gt=function(){try{var e=qt(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),Jt=function(e,t,r){for(var n=-1,s=Object(e),i=r(e),o=i.length;o--;){var a=i[++n];if(!1===t(s[a],a,s))break}return e},Yt=function(e){return null!=e&&"object"==typeof e},Kt=function(e){return Yt(e)&&"[object Arguments]"==Pt(e)};var Vt=Object.prototype,Xt=Vt.hasOwnProperty,Zt=Vt.propertyIsEnumerable;const Qt=Kt(function(){return arguments}())?Kt:function(e){return Yt(e)&&Xt.call(e,"callee")&&!Zt.call(e,"callee")};var er="object"==typeof exports&&exports&&!exports.nodeType&&exports,tr=er&&"object"==typeof module&&module&&!module.nodeType&&module,rr=tr&&tr.exports===er?xt.Buffer:void 0;const nr=(rr?rr.isBuffer:void 0)||function(){return!1};var sr=/^(?:0|[1-9]\d*)$/;const ir=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&sr.test(e))&&e>-1&&e%1==0&&e<t},or=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991};var ar={};ar["[object Float32Array]"]=ar["[object Float64Array]"]=ar["[object Int8Array]"]=ar["[object Int16Array]"]=ar["[object Int32Array]"]=ar["[object Uint8Array]"]=ar["[object Uint8ClampedArray]"]=ar["[object Uint16Array]"]=ar["[object Uint32Array]"]=!0,ar["[object Arguments]"]=ar["[object Array]"]=ar["[object ArrayBuffer]"]=ar["[object Boolean]"]=ar["[object DataView]"]=ar["[object Date]"]=ar["[object Error]"]=ar["[object Function]"]=ar["[object Map]"]=ar["[object Number]"]=ar["[object Object]"]=ar["[object RegExp]"]=ar["[object Set]"]=ar["[object String]"]=ar["[object WeakMap]"]=!1;var lr="object"==typeof exports&&exports&&!exports.nodeType&&exports,cr=lr&&"object"==typeof module&&module&&!module.nodeType&&module,ur=cr&&cr.exports===lr&&vt.process,hr=function(){try{return cr&&cr.require&&cr.require("util").types||ur&&ur.binding&&ur.binding("util")}catch(e){}}(),dr=hr&&hr.isTypedArray;const pr=dr?(fr=dr,function(e){return fr(e)}):function(e){return Yt(e)&&or(e.length)&&!!ar[Pt(e)]};var fr,gr=Object.prototype.hasOwnProperty;const mr=function(e,t){var r=bt(e),n=!r&&Qt(e),s=!r&&!n&&nr(e),i=!r&&!n&&!s&&pr(e),o=r||n||s||i,a=o?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],l=a.length;for(var c in e)!t&&!gr.call(e,c)||o&&("length"==c||s&&("offset"==c||"parent"==c)||i&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||ir(c,l))||a.push(c);return a};var yr=Object.prototype;const _r=function(e,t){return function(r){return e(t(r))}}(Object.keys,Object);var br=Object.prototype.hasOwnProperty;const vr=function(e){if(r=(t=e)&&t.constructor,t!==("function"==typeof r&&r.prototype||yr))return _r(e);var t,r,n=[];for(var s in Object(e))br.call(e,s)&&"constructor"!=s&&n.push(s);return n},wr=function(e){return null!=(t=e)&&or(t.length)&&!It(t)?mr(e):vr(e);var t},xr=function(e,t){return e===t||e!=e&&t!=t},Sr=function(e,t){for(var r=e.length;r--;)if(xr(e[r][0],t))return r;return-1};var Er=Array.prototype.splice;function Cr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Cr.prototype.clear=function(){this.__data__=[],this.size=0},Cr.prototype.delete=function(e){var t=this.__data__,r=Sr(t,e);return!(r<0||(r==t.length-1?t.pop():Er.call(t,r,1),--this.size,0))},Cr.prototype.get=function(e){var t=this.__data__,r=Sr(t,e);return r<0?void 0:t[r][1]},Cr.prototype.has=function(e){return Sr(this.__data__,e)>-1},Cr.prototype.set=function(e,t){var r=this.__data__,n=Sr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};const Tr=Cr,Ar=qt(xt,"Map"),kr=qt(Object,"create");var Or=Object.prototype.hasOwnProperty;var Pr=Object.prototype.hasOwnProperty;function Lr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Lr.prototype.clear=function(){this.__data__=kr?kr(null):{},this.size=0},Lr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Lr.prototype.get=function(e){var t=this.__data__;if(kr){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return Or.call(t,e)?t[e]:void 0},Lr.prototype.has=function(e){var t=this.__data__;return kr?void 0!==t[e]:Pr.call(t,e)},Lr.prototype.set=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=kr&&void 0===t?"__lodash_hash_undefined__":t,this};const Ir=Lr,jr=function(e,t){var r,n,s=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?s["string"==typeof t?"string":"hash"]:s.map};function Rr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Rr.prototype.clear=function(){this.size=0,this.__data__={hash:new Ir,map:new(Ar||Tr),string:new Ir}},Rr.prototype.delete=function(e){var t=jr(this,e).delete(e);return this.size-=t?1:0,t},Rr.prototype.get=function(e){return jr(this,e).get(e)},Rr.prototype.has=function(e){return jr(this,e).has(e)},Rr.prototype.set=function(e,t){var r=jr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this};const Mr=Rr;function Dr(e){var t=this.__data__=new Tr(e);this.size=t.size}Dr.prototype.clear=function(){this.__data__=new Tr,this.size=0},Dr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Dr.prototype.get=function(e){return this.__data__.get(e)},Dr.prototype.has=function(e){return this.__data__.has(e)},Dr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Tr){var n=r.__data__;if(!Ar||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Mr(n)}return r.set(e,t),this.size=r.size,this};const Nr=Dr;function Ur(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Mr;++t<r;)this.add(e[t])}Ur.prototype.add=Ur.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},Ur.prototype.has=function(e){return this.__data__.has(e)};const Fr=Ur,$r=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1},zr=function(e,t,r,n,s,i){var o=1&r,a=e.length,l=t.length;if(a!=l&&!(o&&l>a))return!1;var c=i.get(e),u=i.get(t);if(c&&u)return c==t&&u==e;var h=-1,d=!0,p=2&r?new Fr:void 0;for(i.set(e,t),i.set(t,e);++h<a;){var f=e[h],g=t[h];if(n)var m=o?n(g,f,h,t,e,i):n(f,g,h,e,t,i);if(void 0!==m){if(m)continue;d=!1;break}if(p){if(!$r(t,function(e,t){if(o=t,!p.has(o)&&(f===e||s(f,e,r,n,i)))return p.push(t);var o})){d=!1;break}}else if(f!==g&&!s(f,g,r,n,i)){d=!1;break}}return i.delete(e),i.delete(t),d},Hr=xt.Uint8Array,Br=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r},Wr=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r};var qr=St?St.prototype:void 0,Gr=qr?qr.valueOf:void 0;var Jr=Object.prototype.propertyIsEnumerable,Yr=Object.getOwnPropertySymbols;const Kr=Yr?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var r=-1,n=null==e?0:e.length,s=0,i=[];++r<n;){var o=e[r];t(o,r,e)&&(i[s++]=o)}return i}(Yr(e),function(t){return Jr.call(e,t)}))}:function(){return[]},Vr=function(e){return function(e,t,r){var n=t(e);return bt(e)?n:function(e,t){for(var r=-1,n=t.length,s=e.length;++r<n;)e[s+r]=t[r];return e}(n,r(e))}(e,wr,Kr)};var Xr=Object.prototype.hasOwnProperty;const Zr=qt(xt,"DataView"),Qr=qt(xt,"Promise"),en=qt(xt,"Set"),tn=qt(xt,"WeakMap");var rn="[object Map]",nn="[object Promise]",sn="[object Set]",on="[object WeakMap]",an="[object DataView]",ln=Nt(Zr),cn=Nt(Ar),un=Nt(Qr),hn=Nt(en),dn=Nt(tn),pn=Pt;(Zr&&pn(new Zr(new ArrayBuffer(1)))!=an||Ar&&pn(new Ar)!=rn||Qr&&pn(Qr.resolve())!=nn||en&&pn(new en)!=sn||tn&&pn(new tn)!=on)&&(pn=function(e){var t=Pt(e),r="[object Object]"==t?e.constructor:void 0,n=r?Nt(r):"";if(n)switch(n){case ln:return an;case cn:return rn;case un:return nn;case hn:return sn;case dn:return on}return t});const fn=pn;var gn="[object Arguments]",mn="[object Array]",yn="[object Object]",_n=Object.prototype.hasOwnProperty;const bn=function(e,t,r,n,s,i){var o=bt(e),a=bt(t),l=o?mn:fn(e),c=a?mn:fn(t),u=(l=l==gn?yn:l)==yn,h=(c=c==gn?yn:c)==yn,d=l==c;if(d&&nr(e)){if(!nr(t))return!1;o=!0,u=!1}if(d&&!u)return i||(i=new Nr),o||pr(e)?zr(e,t,r,n,s,i):function(e,t,r,n,s,i,o){switch(r){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!i(new Hr(e),new Hr(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return xr(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var a=Br;case"[object Set]":var l=1&n;if(a||(a=Wr),e.size!=t.size&&!l)return!1;var c=o.get(e);if(c)return c==t;n|=2,o.set(e,t);var u=zr(a(e),a(t),n,s,i,o);return o.delete(e),u;case"[object Symbol]":if(Gr)return Gr.call(e)==Gr.call(t)}return!1}(e,t,l,r,n,s,i);if(!(1&r)){var p=u&&_n.call(e,"__wrapped__"),f=h&&_n.call(t,"__wrapped__");if(p||f){var g=p?e.value():e,m=f?t.value():t;return i||(i=new Nr),s(g,m,r,n,i)}}return!!d&&(i||(i=new Nr),function(e,t,r,n,s,i){var o=1&r,a=Vr(e),l=a.length;if(l!=Vr(t).length&&!o)return!1;for(var c=l;c--;){var u=a[c];if(!(o?u in t:Xr.call(t,u)))return!1}var h=i.get(e),d=i.get(t);if(h&&d)return h==t&&d==e;var p=!0;i.set(e,t),i.set(t,e);for(var f=o;++c<l;){var g=e[u=a[c]],m=t[u];if(n)var y=o?n(m,g,u,t,e,i):n(g,m,u,e,t,i);if(!(void 0===y?g===m||s(g,m,r,n,i):y)){p=!1;break}f||(f="constructor"==u)}if(p&&!f){var _=e.constructor,b=t.constructor;_==b||!("constructor"in e)||!("constructor"in t)||"function"==typeof _&&_ instanceof _&&"function"==typeof b&&b instanceof b||(p=!1)}return i.delete(e),i.delete(t),p}(e,t,r,n,s,i))},vn=function e(t,r,n,s,i){return t===r||(null==t||null==r||!Yt(t)&&!Yt(r)?t!=t&&r!=r:bn(t,r,n,s,e,i))},wn=function(e){return e==e&&!Lt(e)},xn=function(e,t){return function(r){return null!=r&&r[e]===t&&(void 0!==t||e in Object(r))}},Sn=function(e){var t=function(e){for(var t=wr(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,wn(s)]}return t}(e);return 1==t.length&&t[0][2]?xn(t[0][0],t[0][1]):function(r){return r===e||function(e,t,r,n){var s=r.length,i=s,o=!n;if(null==e)return!i;for(e=Object(e);s--;){var a=r[s];if(o&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++s<i;){var l=(a=r[s])[0],c=e[l],u=a[1];if(o&&a[2]){if(void 0===c&&!(l in e))return!1}else{var h=new Nr;if(n)var d=n(c,u,l,e,t,h);if(!(void 0===d?vn(u,c,3,n,h):d))return!1}}return!0}(r,e,t)}},En=function(e){return"symbol"==typeof e||Yt(e)&&"[object Symbol]"==Pt(e)};var Cn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Tn=/^\w*$/;const An=function(e,t){if(bt(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!En(e))||Tn.test(e)||!Cn.test(e)||null!=t&&e in Object(t)};function kn(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],i=r.cache;if(i.has(s))return i.get(s);var o=e.apply(this,n);return r.cache=i.set(s,o)||i,o};return r.cache=new(kn.Cache||Mr),r}kn.Cache=Mr;var On=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Pn=/\\(\\)?/g;const Ln=(In=kn(function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(On,function(e,r,n,s){t.push(n?s.replace(Pn,"$1"):r||e)}),t},function(e){return 500===jn.size&&jn.clear(),e}),jn=In.cache,In);var In,jn;var Rn=St?St.prototype:void 0,Mn=Rn?Rn.toString:void 0;const Dn=function e(t){if("string"==typeof t)return t;if(bt(t))return function(e,t){for(var r=-1,n=null==e?0:e.length,s=Array(n);++r<n;)s[r]=t(e[r],r,e);return s}(t,e)+"";if(En(t))return Mn?Mn.call(t):"";var r=t+"";return"0"==r&&1/t==-1/0?"-0":r},Nn=function(e,t){return bt(e)?e:An(e,t)?[e]:Ln(function(e){return null==e?"":Dn(e)}(e))},Un=function(e){if("string"==typeof e||En(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t},Fn=function(e,t){for(var r=0,n=(t=Nn(t,e)).length;null!=e&&r<n;)e=e[Un(t[r++])];return r&&r==n?e:void 0},$n=function(e,t){return null!=e&&t in Object(e)},zn=function(e,t){return null!=e&&function(e,t,r){for(var n=-1,s=(t=Nn(t,e)).length,i=!1;++n<s;){var o=Un(t[n]);if(!(i=null!=e&&r(e,o)))break;e=e[o]}return i||++n!=s?i:!!(s=null==e?0:e.length)&&or(s)&&ir(o,s)&&(bt(e)||Qt(e))}(e,t,$n)},Hn=function(e,t){return An(e)&&wn(t)?xn(Un(e),t):function(r){var n=function(e,t,r){var n=null==e?void 0:Fn(e,t);return void 0===n?r:n}(r,e);return void 0===n&&n===t?zn(r,e):vn(t,n,3)}},Bn=function(e){return e},Wn=function(e){return An(e)?(t=Un(e),function(e){return null==e?void 0:e[t]}):function(e){return function(t){return Fn(t,e)}}(e);var t},qn=function(e,t){var r,n={};return t="function"==typeof(r=t)?r:null==r?Bn:"object"==typeof r?bt(r)?Hn(r[0],r[1]):Sn(r):Wn(r),function(e,t){e&&Jt(e,t,wr)}(e,function(e,r,s){!function(e,t,r){"__proto__"==t&&Gt?Gt(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}(n,t(e,r,s),e)}),n};class Gn{ctx;serviceHooks;constructor(e,t){this.ctx=e,this.serviceHooks=t,e._execCallableAPI("register-search-service",e.baseInfo.id,t.name,t.options),Object.entries({query:{f:"onQuery",args:["graph","q",!0],reply:!0,transformOutput:e=>(bt(e?.blocks)&&(e.blocks=e.blocks.map(e=>e&&qn(e,(e,t)=>`block/${t}`))),e)},rebuildBlocksIndice:{f:"onIndiceInit",args:["graph","blocks"]},transactBlocks:{f:"onBlocksChanged",args:["graph","data"]},truncateBlocks:{f:"onIndiceReset",args:["graph"]},removeDb:{f:"onGraph",args:["graph"]}}).forEach(([r,n])=>{const s=(e=>`service:search:${e}:${t.name}`)(r);e.caller.on(s,async r=>{if(It(t?.[n.f])){let i=null;try{i=await t[n.f].apply(t,(n.args||[]).map(e=>{if(r){if(!0===e)return r;if(r.hasOwnProperty(e)){const t=r[e];return delete r[e],t}}})),n.transformOutput&&(i=n.transformOutput(i))}catch(e){console.error("[SearchService] ",e),i=e}finally{n.reply&&e.caller.call(`${s}:reply`,i)}}})})}}const Jn=Symbol.for("proxy-continue"),Yn=Ze()("LSPlugin:user"),Kn=new je("",{console:!0});function Vn(e){let t=!1;return()=>{t||(t=!0,e())}}function Xn(e,t,r){const{key:n,label:s,desc:i,palette:o,keybinding:a,extras:l}=t;if("function"!=typeof r)return this.logger.error(`${n||s}: command action should be function.`),!1;const c=Ve(n);if(!c)return this.logger.error(`${s}: command key is required.`),!1;const u=`SimpleCommandHook${c}${++as}`;return this.Editor["on"+u](r),this.caller?.call("api:call",{method:"register-plugin-simple-command",args:[this.baseInfo.id,[{key:c,label:s,type:e,desc:i,keybinding:a,extras:l},["editor/hook",u]],o]}),Vn(()=>{this.Editor["off"+u](r),this._execCallableAPI("unregister_plugin_simple_command",this.baseInfo.id,c)})}function Zn(e){return"string"==typeof e?{mode:"global",binding:e}:e}function Qn(e,t){Yn("Register slash command #",this.baseInfo.id,e,t);const r=[];return"function"==typeof t&&(t=[["editor/clear-current-slash",!1],["editor/restore-saved-cursor"],["editor/hook",t]]),t=t.map(e=>{const[t,...n]=e;if("editor/hook"===t){let s=n[0],i=()=>{this.caller?.callUserModel(s)};"function"==typeof s&&(i=s);const o=`SlashCommandHook${t}${++as}`;e[1]=o,r.push(this.Editor["on"+o](i))}return e}),this.caller?.call("api:call",{method:"register-plugin-slash-command",args:[this.baseInfo.id,[e,t]]}),Vn(()=>{r.forEach(e=>e()),this._execCallableAPI("unregister_plugin_slash_command",this.baseInfo.id,e)})}function es(e,t={},r){if(!(r=r||t.handler))return this.logger.error(`${e}: command handler is required.`),!1;const n=t.key||e,s=t.label||t.title||e,i=Zn(t.keybinding),o=function(e){return void 0===e.when?e.extras:{...e.extras||{},when:e.when}}(t),a=function(e){return Array.isArray(e.placements)&&e.placements.length?e.placements:e.placement?[e.placement]:e.palette?["palette"]:e.keybinding?["shortcut"]:["simple"]}(t).map(e=>{switch(e){case"palette":return Xn.call(this,"$palette$",{key:n,label:s,desc:t.desc,palette:!0,keybinding:i,extras:o},r);case"shortcut":{const e="$shortcut$",a=n||e+Te(i?.binding?.toString());return Xn.call(this,e,{key:a,label:s,desc:t.desc,palette:!1,keybinding:i,extras:o},r)}case"slash":return Qn.call(this,s,r);case"block-context-menu":return Xn.call(this,"block-context-menu-item",{key:n,label:s,desc:t.desc,extras:o},r);case"highlight-context-menu":return Xn.call(this,"highlight-context-menu-item",{key:n,label:s,desc:t.desc,extras:o},r);case"page-menu":return Xn.call(this,"page-menu-item",{key:n,label:s,desc:t.desc,extras:o},r);default:return Xn.call(this,t.type||"$commands$",{key:n,label:s,desc:t.desc,palette:t.palette,keybinding:i,extras:o},r)}});return Vn(()=>{a.forEach(e=>{"function"==typeof e&&e()})})}function ts(e){return Ve(e)?.replace(/:/g,"-").replace(/^([0-9])/,"_$1")}function rs(e){return!!Re(e)||(Kn.error(`#${e} is not a valid UUID string.`),!1)}let ns=null,ss=new Map;const is={async getInfo(e){return ns||(ns=await this._execCallableAPIAsync("get-app-info")),"string"==typeof e?ns[e]:ns},registerCommand(e,t,r){return es.call(this,t.key,{...t,type:e,placement:"simple"},r)},registerSearchService(e){if(ss.has(e.name))throw new Error(`SearchService: #${e.name} has registered!`);ss.set(e.name,new Gn(this,e))},registerCommandPalette(e,t){return es.call(this,e.key,{...e,placement:"palette"},t)},registerCommandShortcut(e,t,r={}){e=Zn(e);const{binding:n}=e,s=r.key||"$shortcut$"+Te(n?.toString());return es.call(this,s,{...r,key:s,placement:"shortcut",keybinding:e},t)},registerUIItem(e,t){const r=this.baseInfo.id;this.caller?.call("api:call",{method:"register-plugin-ui-item",args:[r,e,t]})},registerPageMenuItem(e,t){if("function"!=typeof t)return!1;const r=e+"_"+this.baseInfo.id,n=e;es.call(this,r,{key:r,label:n,placement:"page-menu"},t)},onBlockRendererSlotted(e,t){if(!rs(e))return;const r=this.baseInfo.id,n=`hook:editor:${Te(`slot:${e}`)}`;return this.caller.on(n,t),this.App._installPluginHook(r,n),()=>{this.caller.off(n,t),this.App._uninstallPluginHook(r,n)}},invokeExternalPlugin(e,...t){if(e=e?.trim(),!e)return;let[r,n]=e.split(".");if(!["models","commands"].includes(n?.toLowerCase()))throw new Error("Type only support '.models' or '.commands' currently.");const s=e.replace(`${r}.${n}.`,"");if(!r||!n||!s)throw new Error(`Illegal type of #${e} to invoke external plugin.`);return this._execCallableAPIAsync("invoke_external_plugin_cmd",r,n.toLowerCase(),s,t)},setFullScreen(e){const t=(...e)=>this._callWin("setFullScreen",...e);"toggle"===e?this._callWin("isFullScreen").then(e=>{e?t():t(!0)}):e?t(!0):t()}},os={register:es,execute:function(e,...t){if(e=e?.trim(),!e)return;if(e.startsWith("logseq."))return this.App.invokeExternalCommand(e,...t);const r=e.match(/^([^.]+)\.commands\.(.+)$/);if(r){const[,e,n]=r,s=ts(n);return this._execCallableAPIAsync("invoke_external_plugin_cmd",e,"commands",s,t)}const n=e.indexOf("/");return n>0?this._execCallableAPIAsync("invoke_external_plugin_cmd",e.slice(0,n),"commands",ts(e.slice(n+1)),t):this._execCallableAPIAsync("invoke_external_plugin_cmd",this.baseInfo.id,"commands",ts(e),t)}};let as=0;const ls={newBlockUUID(){return this._execCallableAPIAsync("new_block_uuid")},isPageBlock:e=>e.uuid&&e.hasOwnProperty("name"),registerSlashCommand(e,t){return es.call(this,e,{title:e,placement:"slash"},t)},registerBlockContextMenuItem(e,t){if("function"!=typeof t)return!1;const r=e+"_"+this.baseInfo.id;es.call(this,r,{key:r,label:e,placement:"block-context-menu"},t)},registerHighlightContextMenuItem(e,t,r){if("function"!=typeof t)return!1;const n=e+"_"+this.baseInfo.id;es.call(this,n,{key:n,label:e,placement:"highlight-context-menu",extras:r},t)},scrollToBlockInPage(e,t,r){const n="block-content-"+t;r?.replaceState?this.App.replaceState("page",{name:e},{anchor:n}):this.App.pushState("page",{name:e},{anchor:n})}},cs={onBlockChanged(e,t){if(!rs(e))return;const r=this.baseInfo.id,n=`hook:db:${Te(`block:${e}`)}`,s=({block:r,txData:n,txMeta:s})=>{r.uuid===e&&t(r,n,s)};return this.caller.on(n,s),this.App._installPluginHook(r,n),()=>{this.caller.off(n,s),this.App._uninstallPluginHook(r,n)}},datascriptQuery(e,...t){return t.pop(),t?.some(e=>"function"==typeof e)?this.Experiments.ensureHostScope().logseq.api.datascript_query(e,...t):this._execCallableAPIAsync("datascript_query",e,...t)}},us={},hs={},ds={},ps={makeSandboxStorage(){return new at(this,{assets:!0})}};class fs extends s{_baseInfo;_caller;_version=LIB_VERSION;_debugTag="";_settingsSchema;_connected=!1;_ui=new Map;_mFileStorage;_mNet;_mExperiments;_beforeunloadCallback;constructor(e,t){super(),this._baseInfo=e,this._caller=t,t.on("sys:ui:visible",e=>{e?.toggle&&this.toggleMainUI()}),t.on("settings:changed",e=>{const t={...this.settings||{}},r={...e||{}};this._baseInfo={...this._baseInfo,settings:r},this.emit("settings:changed",r,t)}),t.on("beforeunload",async e=>{const{actor:t,...r}=e,n=this._beforeunloadCallback;try{n&&await n(r),t?.resolve(null)}catch(e){this.logger.error("[beforeunload] ",e),t?.reject(e)}})}async ready(e,t){if(!this._connected)try{"function"==typeof e&&(t=e,e={});let r=await this._caller.connectToParent(e);const n=r?.settings;this._connected=!0,r=Pe(this._baseInfo,r),void 0!==n&&(r.settings=n),this._baseInfo=r,r?.id&&(this._debugTag=this._caller.debugTag=`#${r.id} [${r.name}]`,this.logger.setTag(this._debugTag)),this._settingsSchema&&(r.settings=Ke(r.settings,this._settingsSchema),await this.useSettingsSchema(this._settingsSchema));try{await this._execCallableAPIAsync("setSDKMetadata",{version:this._version,runtime:"js"})}catch(e){console.warn(e)}t&&t.call(this,r)}catch(e){console.error(`${this._debugTag} [Ready Error]`,e)}}ensureConnected(){if(!this._connected)throw new Error("not connected")}beforeunload(e){"function"==typeof e&&(this._beforeunloadCallback=e)}provideModel(e){return this.caller._extendUserModel(e),this}provideTheme(e){return this.caller.call("provider:theme",e),this}provideStyle(e){return this.caller.call("provider:style",e),this}provideUI(e){return this.caller.call("provider:ui",e),this}useSettingsSchema(e){return this.connected&&this.caller.call("settings:schema",{schema:e,isSync:!0}),this._settingsSchema=e,this}updateSettings(e){this.caller.call("settings:update",e)}onSettingsChanged(e){const t="settings:changed";return this.on(t,e),()=>this.off(t,e)}showSettingsUI(){this.caller.call("settings:visible:changed",{visible:!0})}hideSettingsUI(){this.caller.call("settings:visible:changed",{visible:!1})}setMainUIAttrs(e){this.caller.call("main-ui:attrs",e)}setMainUIInlineStyle(e){this.caller.call("main-ui:style",e)}hideMainUI(e){const t={key:0,visible:!1,cursor:e?.restoreEditingCursor};this.caller.call("main-ui:visible",t),this.emit("ui:visible:changed",t),this._ui.set(t.key,t)}showMainUI(e){const t={key:0,visible:!0,autoFocus:e?.autoFocus};this.caller.call("main-ui:visible",t),this.emit("ui:visible:changed",t),this._ui.set(t.key,t)}toggleMainUI(){const e=this._ui.get(0);e&&e.visible?this.hideMainUI():this.showMainUI()}get version(){return this._version}get isMainUIVisible(){const e=this._ui.get(0);return Boolean(e&&e.visible)}get connected(){return this._connected}get baseInfo(){return this._baseInfo}get effect(){return this&&(this.baseInfo?.effect||!this.baseInfo?.iir)}get logger(){return Kn}get settings(){return this.baseInfo?.settings}get caller(){return this._caller}resolveResourceFullUrl(e){if(this.ensureConnected(),e)return e=e.replace(/^[.\\/]+/,""),Ue(this._baseInfo.lsr,e)}_makeUserProxy(e,t){const r=this,n=this.caller;return new Proxy(e,{get(e,s,i){const o=e[s];return function(...e){if(o){0!==e?.length&&e.push(t);const n=o.apply(r,e);if(n!==Jn)return n}if(t){const i=s.toString().match(/^(once|off|on)/i);if(null!=i){const s=i[0].toLowerCase(),o=i.input,a="off"===s,l=r.baseInfo.id;let c=o.slice(s.length),u=e[0],h=e[1];"string"==typeof u&&"function"==typeof h&&(u=u.replace(/^logseq./,":"),c=`${c}${u}`,u=h,h=e[2]),c=`hook:${t}:${Te(c)}`,n[s](c,u);const d=()=>{n.off(c,u),n.listenerCount(c)||r.App._uninstallPluginHook(l,c)};return a?void d():(r.App._installPluginHook(l,c,h),d)}}let i=s;return["git","ui","assets","utils"].includes(t)&&(i=t+"_"+i),n.callAsync("api:call",{tag:t,method:i,args:e})}}})}_execCallableAPIAsync(e,...t){return this._caller.callAsync("api:call",{method:e,args:t})}_execCallableAPI(e,...t){this._caller.call("api:call",{method:e,args:t})}_callWin(...e){return this._execCallableAPIAsync("_callMainWin",...e)}#e;#t;#r;#n;#s;#i;get App(){return this.#e?this.#e:this.#e=this._makeUserProxy(is,"app")}get Commands(){return this.#t?this.#t:this.#t=this._makeUserProxy(os,"commands")}get Editor(){return this.#r?this.#r:this.#r=this._makeUserProxy(ls,"editor")}get DB(){return this.#n?this.#n:this.#n=this._makeUserProxy(cs,"db")}get UI(){return this.#s?this.#s:this.#s=this._makeUserProxy(hs,"ui")}get Utils(){return this.#i?this.#i:this.#i=this._makeUserProxy(ds,"utils")}get Git(){return this._makeUserProxy(us,"git")}get Assets(){return this._makeUserProxy(ps,"assets")}get FileStorage(){let e=this._mFileStorage;return e||(e=this._mFileStorage=new at(this)),e}get Net(){let e=this._mNet;return e||(e=this._mNet=new _t(this)),e}get Experiments(){let e=this._mExperiments;return e||(e=this._mExperiments=new lt(this)),e}}if(null==window.__LSP__HOST__){const e=new Os(null);window.logseq=new fs({},e)}const{importHTML:gs,createSandboxContainer:ms}=window.QSandbox||{};function ys(e,t){return e.startsWith("http")?fetch(e,t):(e=e.replace("file://",""),new Promise(async(t,r)=>{try{const r=await window.apis.doAction(["readFile",e]);t({text:()=>r})}catch(e){console.error(e),r(e)}}))}class _s extends s{_pluginLocal;_frame;_root;_loaded=!1;_unmountFns=[];constructor(e){super(),this._pluginLocal=e,e._dispose(()=>{this._unmount()})}async load(){const{name:e,entry:t}=this._pluginLocal.options;if(this.loaded||!t)return;const{template:r,execScripts:n}=await gs(t,{fetch:ys});this._mount(r,document.body);const s=ms(e,{elementGetter:()=>this._root?.firstChild}).instance.proxy;s.__shadow_mode__=!0,s.LSPluginLocal=this._pluginLocal,s.LSPluginShadow=this,s.LSPluginUser=s.logseq=new fs(this._pluginLocal.toJSON(),this._pluginLocal.caller);const i=await n(s,!0);this._unmountFns.push(i.unmount),this._loaded=!0}_mount(e,t){const r=this._frame=document.createElement("div");r.classList.add("lsp-shadow-sandbox"),r.id=this._pluginLocal.id,this._root=r.attachShadow({mode:"open"}),this._root.innerHTML=`<div>${e}</div>`,t.appendChild(r),this.emit("mounted")}_unmount(){for(const e of this._unmountFns)e&&e.call(null)}destroy(){this.frame?.parentNode?.removeChild(this.frame)}get loaded(){return this._loaded}get document(){return this._root?.firstChild}get frame(){return this._frame}}const bs=Ze()("LSPlugin:caller"),vs="#await#response#",ws="#lspmsg#",xs="#lspmsg#error#",Ss="#lspmsg#settings#",Es="#lspmsg#beforeunload#",Cs="#lspmsg#reply#",Ts="#lspmsg#ready#",As=e=>`${ws}${e}`,ks=e=>`${vs}${e}`;class Os extends s{_pluginLocal;_connected=!1;_parent;_child;_shadow;_status;_userModel={};_syncGCTimer=null;_call;_callUserModel;_debugTag="";constructor(e){super(),this._pluginLocal=e,e&&(this._debugTag=e.debugTag)}async connectToChild(){if(this._connected)return;const{shadow:e}=this._pluginLocal;e?await this._setupShadowSandbox():await this._setupIframeSandbox()}async connectToParent(e={}){if(this._connected)return;const t=this,r=null!=this._pluginLocal;let n=0;const s=new Map,i=$e(6e4),o=this._extendUserModel({[Ts]:async e=>{o[As(e?.pid)]=({type:e,payload:r})=>{bs(`[host (_call) -> *user] ${this._debugTag}`,e,r),t.emit(e,r)},await i.resolve()},[Es]:async e=>{const r=$e(1e4);t.emit("beforeunload",Object.assign({actor:r},e)),await r.promise},[Ss]:async({payload:e})=>{t.emit("settings:changed",e)},[ws]:async({ns:e,type:r,payload:n})=>{bs(`[host (async) -> *user] ${this._debugTag} ns=${e} type=${r}`,n),e&&e.startsWith("hook")?t.emit(`${e}:${r}`,n):t.emit(r,n)},[Cs]:({_sync:e,result:t})=>{if(bs(`[sync host -> *user] #${e}`,t),s.has(e)){const r=s.get(e);r&&(t?.hasOwnProperty(xs)?r.reject(t[xs]):r.resolve(t),s.delete(e))}},...e});if(r)return await i.promise,JSON.parse(JSON.stringify(this._pluginLocal?.toJSON()));const a=new ot(o).sendHandshakeReply();return this._status="pending",await a.then(e=>{this._child=e,this._connected=!0,this._call=async(t,r={},i)=>{if(i){const e=++n;s.set(e,i),r._sync=e,i.setTag(`async call #${e}`),bs(`async call #${e}`)}return e.emit(As(o.baseInfo.id),{type:t,payload:r}),i?.promise},this._callUserModel=async(e,t)=>{try{o[e](t)}catch(t){bs(`call user model(${e}) not exist. #${this._debugTag}`)}},this._syncGCTimer=setInterval(()=>{if(s.size>100)for(const[e,t]of s)t.settled&&s.delete(e)},18e5)}).finally(()=>{this._status=void 0}),await i.promise,o.baseInfo}async call(e,t={}){return this._call?.call(this,e,t)}async callAsync(e,t={}){const r=$e(1e4);return this._call?.call(this,e,t,r)}async callUserModel(e,...t){return this._callUserModel?.apply(this,[e,...t])}async callUserModelAsync(e,...t){return e=ks(e),this._callUserModel?.apply(this,[e,...t])}_calcLayoutPosition(e,t,r=0){const n=Math.max(e,r);return"number"==typeof t?`${Math.min(100*n/t,99)}%`:`${n}px`}async _applyContainerLayout(e){const t=(await(this._pluginLocal?._loadLayoutsData()))?.$$0;if(!t)return;const{width:r,height:n,left:s,top:i,vw:o,vh:a}=t;e.dataset.inited_layout="true",Object.assign(e.style,{width:`${r}px`,height:`${n}px`,left:this._calcLayoutPosition(s,o),top:this._calcLayoutPosition(i,a,45)})}async _setupIframeSandbox(){const e=this._pluginLocal,t=e.id,r=`${t}_lsp_main`,n=new URL(e.options.entry);n.searchParams.set("__v__",_e?Date.now().toString():e.options.version),document.querySelector(`#${r}`)?.remove();const s=document.createElement("div");s.classList.add("lsp-iframe-sandbox-container"),s.id=r,s.dataset.pid=t;try{await this._applyContainerLayout(s)}catch(e){console.error("[Restore Layout Error]",e)}document.body.appendChild(s);const i=new it({id:t+"_iframe",container:s,url:n.href,classListArray:["lsp-iframe-sandbox"],model:{baseInfo:JSON.parse(JSON.stringify(e.toJSON()))},allow:e.options.allow,enableMessageChannel:!0});let o;this._status="pending";const a=new Promise((e,t)=>{o=setTimeout(()=>{i.destroy(),t(new Error("handshake Timeout"))},8e3)});try{const t=await Promise.race([i.sendHandshake(),a]);this._parent=t,this._connected=!0,this.emit("connected"),t.on(As(e.id),({type:e,payload:t})=>{bs("[user -> *host] ",e,t),this._pluginLocal?.emit(e,t||{}),this._pluginLocal?.caller.emit(e,t||{})}),this._call=async(...r)=>{t.call(As(e.id),{type:r[0],payload:Object.assign(r[1]||{},{$$pid:e.id})})},this._callUserModel=async(e,...r)=>{if(e.startsWith(vs))return await t.get(e.replace(vs,""),...r);t.call(e,r?.[0])}}catch(e){throw bs("[iframe sandbox] error",e),e}finally{clearTimeout(o),this._status=void 0}}async _setupShadowSandbox(){const e=this._pluginLocal,t=this._shadow=new _s(e);try{this._status="pending",await t.load(),this._connected=!0,this.emit("connected"),this._call=async(t,r={},n)=>(n&&(r.actor=n),this._pluginLocal?.emit(t,Object.assign(r,{$$pid:e.id})),n?.promise),this._callUserModel=async(...e)=>{let t=e[0];t?.startsWith(vs)&&(t=t.replace(vs,""));const r=e[1]||{},n=this._userModel[t];"function"==typeof n&&await n.call(null,r)}}catch(e){throw bs("[shadow sandbox] error",e),e}finally{this._status=void 0}}_extendUserModel(e){return Object.assign(this._userModel,e)}_getSandboxIframeContainer(){return this._parent?.frame.parentNode}_getSandboxShadowContainer(){return this._shadow?.frame}_getSandboxIframeRoot(){return this._parent?.frame}_getSandboxShadowRoot(){return this._shadow?.frame}set debugTag(e){this._debugTag=e}async destroy(){let e=null;this._parent&&(e=this._getSandboxIframeContainer(),this._parent.destroy()),this._shadow&&(e=this._getSandboxShadowContainer(),this._shadow.destroy()),e?.parentNode?.removeChild(e),this._syncGCTimer&&(clearInterval(this._syncGCTimer),this._syncGCTimer=null),this._connected=!1,this._parent=void 0,this._child=void 0,this._shadow=void 0,this._call=void 0,this._callUserModel=void 0,this._status=void 0}}const Ps=Ze()("LSPlugin:core"),Ls="plugins";class Is extends s{_userPluginSettings;_schema;_settings={disabled:!1};constructor(e,t){super(),this._userPluginSettings=e,this._schema=t,Object.assign(this._settings,e)}get(e){return this._settings[e]}set(e,t){const r=Pe({},this._settings);this._settings[e]!==t&&(this._settings={...this._settings,[e]:t},this.emit("change",{...this._settings},r))}patch(e){if(!Oe(e))return;const t=Pe({},this._settings);this._settings=Pe(this._settings,e),this.emit("change",{...this._settings},t)}replace(e){const t=Pe({},this._settings);this._settings={disabled:!1,...e||{}},this.emit("change",{...this._settings},t)}set settings(e){this.replace(e)}get settings(){return this._settings}setSchema(e,t){this._schema=e,t&&this.replace(Ke(this._settings,e))}reset(){const e=this.settings,t={};this._schema,this.replace(t),this.emit("reset",t,e)}toJSON(){return this._settings}}var js;function Rs(e,t,r=we){return t&&e.startsWith(be+t)&&(e=Ue(r,e.substr(be.length+t.length))),e}function Ms(e){return e?Se:we}function Ds(e,t,r){return Rs(e,t,function(e,t){return Ue(!1===t?xe:Ee,encodeURIComponent(e))}(t,r))}!function(e){e.LOADING="loading",e.UNLOADING="unloading",e.LOADED="loaded",e.UNLOADED="unload",e.ERROR="error"}(js||(js={}));class Ns extends Error{url;packageJsonPath;constructor(e,t={}){super(e),this.name="IllegalPluginPackageError",Object.assign(this,t)}}class Us extends Error{constructor(e){super(e),this.name="ExistedImportedPluginPackageError"}}class Fs extends s{_options;_themeMgr;_ctx;_sdk={};_runtimeDisposes=[];_registrationDisposes=[];_id;_status=js.UNLOADED;_loadErr;_localRoot;_dotSettingsFile;_caller;_logger=new je("PluginLocal");_disposeSettingsObserver;constructor(e,t,r){var n;super(),this._options=e,this._themeMgr=t,this._ctx=r,this._id=e.key||Me(),this._disposeRegistration(async()=>{this._disposeSettingsObserver?.(),this._disposeSettingsObserver=void 0}),function(e){const t=e=>`settings:${e}`;e.on(t("schema"),({schema:t,isSync:r})=>{e.settingsSchema=t,e.settings?.setSchema(t,r)}),e.on(t("update"),t=>{t&&e.settings?.patch(t)}),e.on(t("visible:changed"),t=>{const r=t?.visible;ze("set_focused_settings",r?e.id:null)})}(this),function(e){const t=e=>`main-ui:${e}`;e.on(t("visible"),({visible:t,toggle:r,cursor:n,autoFocus:s})=>{const i=e.getMainUIContainer();i?.classList[r?"toggle":t?"add":"remove"]("visible"),t?!e.shadow&&i&&!1!==s&&i.querySelector("iframe")?.contentWindow?.focus():i.ownerDocument.activeElement.blur(),n&&ze("restore_editing_cursor")}),e.on(t("attrs"),t=>{const r=e.getMainUIContainer();Object.entries(t).forEach(([t,n])=>{r?.setAttribute(t,String(n)),"draggable"===t&&n&&e._dispose(e._setupDraggableContainer(r,{title:e.options.name,close:()=>{e.caller.call("sys:ui:visible",{toggle:!0})}})),"resizable"===t&&n&&e._dispose(e._setupResizableContainer(r))})}),e.on(t("style"),t=>{const r=e.getMainUIContainer(),n=!!r.dataset.inited_layout;Object.entries(t).forEach(([e,t])=>{n&&["left","top","bottom","right","width","height"].includes(e)||(r.style[e]=t)})})}(this),function(e){const t=e=>`provider:${e}`;let r=!1;e.on(t("theme"),t=>{e.themeMgr.registerTheme(e.id,t),r||(e._dispose(()=>{e.themeMgr.unregisterTheme(e.id)}),r=!0)}),e.on(t("style"),t=>{let r;"string"!=typeof t&&(r=t.key,t=t.style),t&&t.trim()&&e._dispose(He(t,{"data-injected-style":r?`${r}-${e.id}`:"","data-ref":e.id}))}),e.on(t("ui"),t=>{e._onHostMounted(()=>{const r=We.call(e,t,Object.assign({"data-ref":e.id},t.attrs||{}),({el:t,float:r})=>{if(!r)return;const n=t.dataset.identity;e.layoutCore.move_container_to_top(n)});"function"==typeof r&&e._dispose(r)})})}(this),(n=this).on("api:call",async e=>{let t;try{window.$$callerPluginID=n.id,t=await ze.apply(n,[e.method,...e.args])}catch(e){t={[xs]:e}}finally{window.$$callerPluginID=void 0}if(n.shadow)return void(e.actor&&(t?.hasOwnProperty(xs)?e.actor.reject(t[xs]):e.actor.resolve(t)));const{_sync:r}=e;if(null!=r){const e=e=>{n.caller?.callUserModel(Cs,{result:e,_sync:r})};Promise.resolve(t).then(e,e)}})}async _setupUserSettings(e){const{_options:t}=this;this._logger||(this._logger=new je("Loader"));const r=this._logger;if(!t.settings||e||!this._disposeSettingsObserver)try{const n=()=>ze("load_plugin_user_settings",this.id),[s,i]=await n();this._dotSettingsFile=s;let o=t.settings;o||(o=t.settings=new Is(i)),this._disposeSettingsObserver?.(),this._disposeSettingsObserver=void 0,e&&o.replace(i);const a=async(e,t)=>{const n=function(e,t){e=e||{},t=t||{};const r=new Set([...Object.keys(e),...Object.keys(t)]),n=[],s=e=>{if(void 0===e)return"undefined";try{const t=JSON.stringify(e);return t&&t.length>80?t.slice(0,77)+"...":t}catch(t){return String(e)}};for(const i of r){const r=e[i],o=t[i];if(r!==o)if(i in e)if(i in t){try{if(JSON.stringify(r)===JSON.stringify(o))continue}catch(e){}n.push(`${i}: ${s(r)} -> ${s(o)}`)}else n.push(`-${i}`);else n.push(`+${i}: ${s(o)}`)}return n.length?n.join(", "):null}(t,e);n&&r.debug("settings changed",n),e&&ze("save_plugin_user_settings",this.id,e)};o.on("change",a);const l=()=>{o.off("change",a),this._disposeSettingsObserver===l&&(this._disposeSettingsObserver=void 0)};this._disposeSettingsObserver=l}catch(e){Ps("[load plugin user settings Error]",e),r?.error("load user settings failed",e)}}getMainUIContainer(){return this.shadow?this.caller?._getSandboxShadowContainer():this.caller?._getSandboxIframeContainer()}_resolveResourceFullUrl(e,t){if(!e?.trim())return;if(t=t||this._localRoot,this.isWebPlugin)return this.installedFromUserWebUrl?`${this.installedFromUserWebUrl}/${e}`:`https://pub-80f42b85b62c40219354a834fcf2bbfa.r2.dev/${ye.join(t,e)}`;const r=/^(http|file)/;if(!r.test(e)){const n=ye.join(t,e);e=r.test(n)?n:be+n}return this.isInstalledInLocalDotRoot?Rs(e,this.dotPluginsRoot,Ms(this.options.effect)):Ds(e,t,this.options.effect)}async _preparePackageConfigs(){const{url:e,webPkg:t}=this._options;let r=t;if(!r){let t;if(e){Ps("prepare package root",e),this._logger?.debug("prepare package root",e);try{r=await ze("load_plugin_config",e),r?(r=JSON.parse(r),r||(t=`Parse package config error #${e}/package.json`)):t=`Parse package config error #${e}/package.json`}catch(e){t=e?.message||String(e)}}else t="Can not resolve package config location";if(t)throw new Ns(t,{url:e,packageJsonPath:e?ye.join(e,"package.json"):void 0})}["name","author","repository","version","description","repo","title","effect","sponsors"].concat(this.isInstalledInLocalDotRoot?[]:["devEntry"]).forEach(e=>{this._options[e]=r[e]});const{repo:n,version:s}=this._options,i=this._localRoot=this.isWebPlugin?`${n||e}/${s}`:Fe(e),o=r.logseq||{},a=o.entry||o.main||r.main;o.devEntry?(this._options.devEntry=o.devEntry,this._options.entry=this._resolveResourceFullUrl(o.devEntry,i)):this._options.entry=this._resolveResourceFullUrl(a,i),o.mode&&(this._options.mode=o.mode);const l=o.title||r.title,c=o.icon||r.icon;if(this._options.title=l,this._options.icon=c&&this._resolveResourceFullUrl(c),this._options.theme=Boolean(o.theme||!!o.themes),this.isInstalledInLocalDotRoot)this._id=ye.basename(i);else if(!this.isWebPlugin)if(o.id)this._id=o.id;else{o.id=this.id;try{await ze("save_plugin_package_json",e,{...r,logseq:o})}catch(e){Ps("[save plugin ID Error] ",e),this._logger?.warn("save plugin id failed",e)}}const{registeredPlugins:u,isRegistering:h}=this._ctx;if(h&&u.has(this.id))throw new Us(this.id);return async()=>{try{const e=o.themes;e&&await this._loadConfigThemes(Array.isArray(e)?e:[e])}catch(e){Ps("[prepare package effect Error]",e),this._logger?.error("prepare package effect failed",e)}}}async _tryToNormalizeEntry(){let{entry:e,settings:t,devEntry:r}=this.options;if(r=r||t?.get("_devEntry"),r)return void(this._options.entry=this._resolveResourceFullUrl(r,this._localRoot));if(!e.endsWith(".js"))return;let n=null,s="write_user_tmp_file";this.isInstalledInLocalDotRoot&&(s="write_dotdir_file",n=this._localRoot.replace(this.dotPluginsRoot,""),n=ye.join(Ls,n));const i=(new Date).getDay(),o=await ke(),a=await ze(s,`${this._id}_index.html`,`<!doctype html>\n<html lang="en">\n <head>\n <meta charset="UTF-8">\n <title>logseq plugin entry</title>\n ${this.isWebPlugin?`<script src="https://cdn.jsdelivr.net/npm/@logseq/libs/dist/lsplugin.user.min.js?v=${i}"><\/script>`:`<script src="/external/${o}/lsplugin.user.js?v=${i}"><\/script>`}\n\n </head>\n <body>\n <div id="app"></div>\n <script src="${e}"><\/script>\n </body>\n</html>`,n);e=Ne(ye.normalize(a)),e=this.isInstalledInLocalDotRoot?Rs(e,this.dotPluginsRoot,Ms(this.options.effect)):Ds(e,ye.dirname(a),this.options.effect),this._options.entry=e}async _loadConfigThemes(e){e.forEach(e=>{e.url&&(!e.url.startsWith("http")&&this._localRoot&&(e.url=this._resolveResourceFullUrl(e.url,this._localRoot),this.isWebPlugin||e.url.startsWith("file:")||e.url.startsWith("lsp:")||(e.url="assets://"+e.url)),this.emit("provider:theme",e))})}async _loadLayoutsData(){const e=this.id+"_layouts",[,t]=await ze("load_plugin_user_settings",e);return t||{}}async _saveLayoutsData(e){const t=this.id+"_layouts";await ze("save_plugin_user_settings",t,e)}async _persistMainUILayoutData(e){const t=await this._loadLayoutsData();t.$$0=e,await this._saveLayoutsData(t)}_setupDraggableContainer(e,t={}){const r=e.dataset;if(r.inited_draggable)return;r.identity||(r.identity="dd-"+Me());const n=!!t.key,s=document.createElement("div");s.classList.add("draggable-handle"),s.innerHTML=`\n <div class="th">\n <div class="l"><h3>${t.title||""}</h3></div>\n <div class="r">\n <a class="button x"><i class="ti ti-x"></i></a>\n </div>\n </div>\n `,s.querySelector(".x").addEventListener("click",e=>{t?.close?.(),e.stopPropagation()},!1),s.addEventListener("mousedown",e=>{const t=e.target;t?.closest(".r")&&(e.stopPropagation(),e.preventDefault())},!1),e.prepend(s),e.addEventListener("mousedown",e=>{this.layoutCore.move_container_to_top(r.identity)},!0);const i=this.layoutCore.setup_draggable_container_BANG_(e,n?()=>{}:this._persistMainUILayoutData.bind(this));var o;r.inited_draggable="true",t.title&&(o=t.title,s.querySelector("h3").textContent=o);let a=null;if("outside"===r.close){const r=r=>{const n=r.target;e.contains(n)||t.close()};document.addEventListener("click",r,!1),a=()=>{document.removeEventListener("click",r)}}return()=>{i(),a?.()}}_setupResizableContainer(e,t){const r=e.dataset;if(r.inited_resizable)return;r.identity||(r.identity="dd-"+Me());const n=document.createElement("div");n.classList.add("resizable-handle"),e.prepend(n);const s=window.frontend.modules.layout.core.setup_resizable_container_BANG_(e,t?()=>{}:this._persistMainUILayoutData.bind(this));return r.inited_resizable="true",s}async load(e){if(this.pending||this.loaded)return void this._logger?.debug("load skipped",this.pending?"(pending)":"(already loaded)");const t=performance.now();this._logger?.info("load:start",e?.reload?"(reload)":""),this._transitionStatus(js.LOADING,[js.UNLOADED,js.ERROR]),this._loadErr=void 0;try{const r=await this._preparePackageConfigs();if(await this._setupUserSettings(e?.reload),this.disabled||await r.call(null),this.disabled)return void this._logger?.info("load:skip (disabled)");if(!this.options.entry)return void this._logger?.info("load:skip (no entry - theme-only package)");this._ctx.emit("beforeload",this),await this._tryToNormalizeEntry(),this._logger?.debug("entry normalized",this.options.entry),this._caller=new Os(this),await this._caller.connectToChild(),this._logger?.debug("sandbox connected");const n=()=>{this._caller?.callUserModel(Ts,{pid:this.id})};e?.indicator?e.indicator.promise.then(n):n(),this._dispose(async()=>{await(this._caller?.destroy())}),this._dispose(Ge.bind(this)),this._ctx.emit("loadeded",this),this._logger?.info(`load:done in ${(performance.now()-t).toFixed(1)}ms`)}catch(e){this.logger.error("load:failed",e,!0),this.disposeRuntime().catch(null),this._status=js.ERROR,this._loadErr=e}finally{this._loadErr||this._transitionStatus(this.disabled?js.UNLOADED:js.LOADED,[js.LOADING])}}async reload(){this.pending?this._logger?.debug("reload skipped (pending)"):(this._logger?.info("reload:start"),this._ctx.emit("beforereload",this),this.loaded&&await this.unload(),await this.load({reload:!0}),this._ctx.emit("reloaded",this),this._logger?.info("reload:done"))}async unload(e=!1){if(this.pending)this._logger?.debug("unload skipped (pending)");else if(e||this.loaded){if(e)return this._logger?.info("unregister:start"),await this.unload(),await this.disposeRegistration(),(this.isWebPlugin||this.isInstalledInLocalDotRoot)&&this._ctx.emit("unlink-plugin",this.id),void this._logger?.info("unregister:done");this._logger?.info("unload:start");try{const t={unregister:e};if(this.loaded){this._transitionStatus(js.UNLOADING,[js.LOADED]);try{await(this._caller?.callUserModel(ks(Es),t)),this.emit("beforeunload",t)}catch(e){this.logger.error("beforeunload hook failed",e)}await this.disposeRuntime()}this.emit("unloaded"),this._logger?.info("unload:done")}catch(e){this.logger.error("unload failed",e)}finally{this._status=js.UNLOADED}}else this._status=js.UNLOADED}async _runDisposers(e){for(const t of e)try{t&&await t()}catch(e){this._logger?.error("dispose failed",e)}}async disposeRuntime(){await this._runDisposers(this._runtimeDisposes),this._runtimeDisposes=[]}async disposeRegistration(){await this._runDisposers(this._registrationDisposes),this._registrationDisposes=[]}_dispose(e){e&&this._runtimeDisposes.push(e)}_disposeRegistration(e){e&&this._registrationDisposes.push(e)}_transitionStatus(e,t){if(t&&!t.includes(this._status))throw new Error(`Invalid plugin status transition: ${this._status} -> ${e}`);this._status=e}_onHostMounted(e){const t=this._ctx.hostMountedActor;!t||t.settled?e():t?.promise.then(e)}get isWebPlugin(){return this._ctx.isWebPlatform||!!this.options.webPkg}get installedFromUserWebUrl(){return this.isWebPlugin&&this.options.webPkg?.installedFromUserWebUrl}get layoutCore(){return window.frontend.modules.layout.core}get isInstalledInLocalDotRoot(){if(this.isWebPlugin)return!1;const e=this.dotConfigRoot,t=this.localRoot;return e&&t&&t.startsWith(e)}get loaded(){return this._status===js.LOADED}get pending(){return[js.LOADING,js.UNLOADING].includes(this._status)}get status(){return this._status}get settings(){return this.options.settings}set settingsSchema(e){this._options.settingsSchema=e}get settingsSchema(){return this.options.settingsSchema}get logger(){return this._logger}get disabled(){return this.settings?.get("disabled")}get theme(){return this.options.theme}get caller(){return this._caller}get id(){return this._id}get shadow(){return"shadow"===this.options.mode}get options(){return this._options}get themeMgr(){return this._themeMgr}get debugTag(){const e=this._options?.name;return`#${this._id} - ${e??""}`}get localRoot(){return this._localRoot||this._options.url}get loadErr(){return this._loadErr}get dotConfigRoot(){return ye.normalize(this._ctx.options.dotConfigRoot)}get dotSettingsFile(){return this._dotSettingsFile}get dotPluginsRoot(){return ye.join(this.dotConfigRoot,Ls)}get sdk(){return this._sdk}set sdk(e){this._sdk=e}toJSON(e=!0){const t={...this.options};return t.id=this.id,t.err=this.loadErr,t.usf=this.dotSettingsFile,t.iir=this.isInstalledInLocalDotRoot,t.webMode=!!this.isWebPlugin&&(this.installedFromUserWebUrl?"user":"github"),t.lsr=this._resolveResourceFullUrl("/"),!1===e?delete t.settings:t.settings=t.settings?.toJSON(),t}}class $s extends s{_options;_isRegistering=!1;_readyIndicator;_hostMountedActor=$e();_userPreferences={theme:null,themes:{mode:"light",light:null,dark:null},externals:[]};_registeredThemes=new Map;_registeredPlugins=new Map;_currentTheme;constructor(e){super(),this._options=e}async loadUserPreferences(){try{const e=await ze("load_user_preferences");e&&Object.assign(this._userPreferences,e)}catch(e){Ps("[load user preferences Error]",e)}}async saveUserPreferences(e){try{e&&Object.assign(this._userPreferences,e),await ze("save_user_preferences",this._userPreferences)}catch(e){Ps("[save user preferences Error]",e)}}async activateUserPreferences(){const{theme:e,themes:t}=this._userPreferences,r=t[t.mode];r?await this.selectTheme(r,{effect:!1,emit:!1}):e&&await this.selectTheme(e,{effect:!1,emit:!1})}async register(e,t=!1){if(!Array.isArray(e))return void await this.register([e]);const r=new Map,n=()=>{const e=Array.from(r.values()).reduce((e,t)=>{const{id:r,options:n,status:s,disabled:i}=t.o;return!0===i||!n.entry&&(n.name||n.entry)||(e[r]={name:n.name,entry:n.entry,status:s,enabled:"boolean"==typeof i?i?"⚫️":"🟢":"🔴",perf:t.e?`${(t.e-t.s).toFixed(2)}ms`:t.o.loadErr}),e},{});console.table(e)};window.__debugPluginsPerfInfo=n;const s=this._readyIndicator=$e();try{this._isRegistering=!0,await this.loadUserPreferences();let n=new Set(this._userPreferences.externals);if(n?.size)try{const e=await ze("validate_external_plugins",[...n]);n=new Set([...Object.entries(e)].reduce((e,[t,r])=>(r&&e.push(t),e),[]))}catch(e){console.error("[validatedExternals Error]",e)}t&&(e=e.concat([...n].filter(t=>!e.length||e.every(e=>!e.entry&&e.url!==t)).map(e=>({url:e}))));for(const t of e){const{url:e}=t,i=new Fs(t,this,this),o={o:i,s:performance.now(),e:0};r.set(e,o),await i.load({indicator:s}),o.e=performance.now();const{loadErr:a}=i;if(a&&(Ps("[Failed LOAD Plugin] #",t),i.logger?.error("register: load failed",a,!0),this.emit("error",a),a instanceof Ns||a instanceof Us))continue;const l=e=>{this.emit("settings-changed",i.id,e),i.caller?.callUserModel(Ss,{payload:e})};i.settings?.on("change",l),i._disposeRegistration(()=>{i.settings?.off("change",l)}),this._registeredPlugins.set(i.id,i),this.emit("registered",i),i.isWebPlugin||i.isInstalledInLocalDotRoot||n.add(e)}await this.saveUserPreferences({externals:Array.from(n)}),await this.activateUserPreferences(),s.resolve("ready")}catch(e){console.error(e)}finally{s.settled||s.resolve("ready"),this._isRegistering=!1,this.emit("ready",r),n()}}async reload(e){if(Array.isArray(e))for(const t of e)try{const e=this.ensurePlugin(t);await e.reload()}catch(e){try{this.getPluginLogger(t)?.error("reload failed",e)}catch(e){}Ps(e)}else await this.reload([e])}async unregister(e){if(!Array.isArray(e))return void await this.unregister([e]);const t=[];for(const r of e){const e=this.ensurePlugin(r);e.isWebPlugin||e.isInstalledInLocalDotRoot||t.push(e.options.url),await e.unload(!0),this._registeredPlugins.delete(r),this.emit("unregistered",r)}const r=this._userPreferences.externals;r.length&&t.length&&await this.saveUserPreferences({externals:r.filter(e=>!t.includes(e))})}async enable(e){const t=this.ensurePlugin(e);t.pending||!t.disabled&&t.loaded||(t.logger?.info("enable:start"),this.emit("beforeenable"),t.settings?.set("disabled",!1),await t.load(),this.emit("enabled",t.id),t.logger?.info("enable:done"))}async disable(e){const t=this.ensurePlugin(e);t.pending||t.disabled&&!t.loaded||(t.logger?.info("disable:start"),this.emit("beforedisable"),t.settings?.set("disabled",!0),await t.unload(),this.emit("disabled",t.id),t.logger?.info("disable:done"))}async _hook(e,t,r,n){const s=`${e}:${Te(t)}`,i="hook:db:changed"===s,o=s.startsWith("hook:db:block"),a=n=>{Ps(`[call hook][#${n.id}]`,e,t),n.caller?.callUserModel(ws,{ns:e,type:Te(t),payload:r})},l=n&&this._registeredPlugins.get(n);if(l&&!l.disabled&&l.options.entry)a(l);else for(const[e,t]of this._registeredPlugins)if(t.options.entry&&!t.disabled)if(n){if(n===t.id){a(t);break}}else{const e=t.sdk?.version;if(!e){if(i||o)continue;a(t)}e&&ze("should_exec_plugin_hook",t.id,s)&&a(t)}}async hookApp(e,t,r){return await this._hook("hook:app",e,t,r)}async hookEditor(e,t,r){return await this._hook("hook:editor",e,t,r)}async hookDb(e,t,r){return await this._hook("hook:db",e,t,r)}ensurePlugin(e){if(e instanceof Fs)return e;const t=this._registeredPlugins.get(e);if(!t)throw new Error(`plugin #${e} not existed.`);return t}getPluginLogger(e){try{return this.ensurePlugin(e)?.logger}catch(e){return}}getPluginLogs(e){return this.getPluginLogger(e)?.getEntries()||[]}clearPluginLogs(e){this.getPluginLogger(e)?.clear()}hostMounted(){this._hostMountedActor.resolve()}_forceCleanInjectedUI(e){if(e)return qe(e)}get isWebPlatform(){return this.options.dotConfigRoot?.startsWith("LSPUserDotRoot")}get registeredPlugins(){return this._registeredPlugins}get options(){return this._options}get readyIndicator(){return this._readyIndicator}get hostMountedActor(){return this._hostMountedActor}get isRegistering(){return this._isRegistering}get themes(){return this._registeredThemes}get enabledPlugins(){return[...this.registeredPlugins.entries()].reduce((e,t)=>{let r=t?.[1];return!0!==r?.disabled&&e.set(t?.[0],r),e},new Map)}async registerTheme(e,t){if(Ps("Register theme #",e,t),!e)return;let r=this._registeredThemes.get(e);r||this._registeredThemes.set(e,r=[]),r.push(t),this.emit("themes-changed",this.themes,{id:e,...t}),this.getPluginLogger(e)?.debug("theme registered",t?.name||t?.url||"")}async selectTheme(e,t={}){const{effect:r,emit:n}=Object.assign({effect:!0,emit:!0},t);if(this._currentTheme&&this._currentTheme.eject(),e.url){const t=Ye(e.url);this._currentTheme={pid:e.pid,opt:e,eject:t}}else this._currentTheme=null;r&&await this.saveUserPreferences(e.mode?{themes:{...this._userPreferences.themes,mode:e.mode,[e.mode]:e}}:{theme:e}),n&&this.emit("theme-selected",e,t)}async unregisterTheme(e,t=!0){if(Ps("Unregister theme #",e),this._registeredThemes.has(e)&&(this._registeredThemes.delete(e),this.emit("themes-changed",this.themes,{id:e}),t&&this._currentTheme?.pid===e)){this._currentTheme.eject(),this._currentTheme=null;const{theme:t,themes:r}=this._userPreferences;await this.saveUserPreferences({theme:t?.pid===e?null:t,themes:{...r,light:r.light?.pid===e?null:r.light,dark:r.dark?.pid===e?null:r.dark}}),this.emit("reset-custom-theme",this._userPreferences.themes)}}}function zs(e){const t=new $s(e);Ps("=== 🔗 Setup Logseq Plugin System 🔗 ==="),window.LSPluginCore=t,window.DOMPurify=ie}})(),n})()); |