@3sln/trove 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1227 -0
- package/package.json +75 -0
- package/packages/core/src/collections/index.js +249 -0
- package/packages/core/src/errors.js +186 -0
- package/packages/core/src/identity/discovery.js +210 -0
- package/packages/core/src/identity/index.js +188 -0
- package/packages/core/src/identity/jwt.js +199 -0
- package/packages/core/src/index.js +104 -0
- package/packages/core/src/indexers/contribution.js +115 -0
- package/packages/core/src/indexers/registry.js +162 -0
- package/packages/core/src/indexing.js +340 -0
- package/packages/core/src/issues.js +150 -0
- package/packages/core/src/kv.js +0 -0
- package/packages/core/src/links.js +141 -0
- package/packages/core/src/metadata/cursor.js +73 -0
- package/packages/core/src/metadata/interface.js +244 -0
- package/packages/core/src/metadata/memory.js +270 -0
- package/packages/core/src/metadata/sqlite.js +412 -0
- package/packages/core/src/notifications/index.js +139 -0
- package/packages/core/src/notifications/webpush.js +217 -0
- package/packages/core/src/plugins/contributions.js +177 -0
- package/packages/core/src/plugins/identity.js +98 -0
- package/packages/core/src/plugins/index.js +225 -0
- package/packages/core/src/plugins/indexers.js +142 -0
- package/packages/core/src/plugins/installStore.js +134 -0
- package/packages/core/src/plugins/package.js +102 -0
- package/packages/core/src/plugins/packageStore.js +61 -0
- package/packages/core/src/plugins/runtime.js +101 -0
- package/packages/core/src/plugins/sql.js +52 -0
- package/packages/core/src/retry.js +74 -0
- package/packages/core/src/scan.js +302 -0
- package/packages/core/src/search/embeddings.js +128 -0
- package/packages/core/src/search/index.js +200 -0
- package/packages/core/src/search/keywordStore.js +107 -0
- package/packages/core/src/search/sqliteStores.js +455 -0
- package/packages/core/src/search/tagMatch.js +59 -0
- package/packages/core/src/search/transformer.js +195 -0
- package/packages/core/src/search/vectorStore.js +274 -0
- package/packages/core/src/search/vectorize.js +249 -0
- package/packages/core/src/sidecar/document.js +213 -0
- package/packages/core/src/sidecar/index.js +174 -0
- package/packages/core/src/sidecar/manager.js +239 -0
- package/packages/core/src/sidecar/store.js +46 -0
- package/packages/core/src/signedUrls.js +170 -0
- package/packages/core/src/sqlite-d1.js +162 -0
- package/packages/core/src/sqlite-driver.js +42 -0
- package/packages/core/src/sqlite.js +162 -0
- package/packages/core/src/storage/filesystem.js +283 -0
- package/packages/core/src/storage/interface.js +222 -0
- package/packages/core/src/storage/memory.js +113 -0
- package/packages/core/src/storage/prefixed.js +75 -0
- package/packages/core/src/storage/s3.js +316 -0
- package/packages/core/src/storage/s3sigv4.js +185 -0
- package/packages/core/src/tasks.js +228 -0
- package/packages/core/src/uploads.js +386 -0
- package/packages/core/src/util.js +125 -0
- package/packages/core/src/vfs.js +666 -0
- package/packages/plugin-sdk/src/browser.js +316 -0
- package/packages/plugin-sdk/src/index.js +32 -0
- package/packages/plugin-sdk/src/protocol.js +59 -0
- package/packages/plugin-sdk/src/rpc.js +95 -0
- package/packages/server/src/adapters/bun.js +78 -0
- package/packages/server/src/adapters/node.js +115 -0
- package/packages/server/src/adapters/staticAssets.js +123 -0
- package/packages/server/src/adapters/webDist.js +70 -0
- package/packages/server/src/adapters/worker-tasks.js +206 -0
- package/packages/server/src/adapters/worker.js +159 -0
- package/packages/server/src/cachePolicy.js +34 -0
- package/packages/server/src/engine/README.md +88 -0
- package/packages/server/src/engine/actions/scanCollection.js +114 -0
- package/packages/server/src/engine/index.js +95 -0
- package/packages/server/src/engine/lazy.js +25 -0
- package/packages/server/src/engine/providers/access.js +363 -0
- package/packages/server/src/engine/providers/core.js +405 -0
- package/packages/server/src/engine/providers/scan.js +67 -0
- package/packages/server/src/index.js +698 -0
- package/packages/server/src/manifest.js +98 -0
- package/packages/server/src/mcp/auth.js +40 -0
- package/packages/server/src/mcp/index.js +213 -0
- package/packages/server/src/mcp/protocol.js +181 -0
- package/packages/server/src/mcp/tools.js +351 -0
- package/packages/server/src/router.js +229 -0
- package/packages/server/src/routes.js +1066 -0
- package/packages/server/src/scope.js +43 -0
- package/packages/web/dist/assets/chunk-4xqbzebh.js +5 -0
- package/packages/web/dist/assets/chunk-4xqbzebh.js.map +9 -0
- package/packages/web/dist/assets/chunk-h05bxfbs.js +5 -0
- package/packages/web/dist/assets/chunk-h05bxfbs.js.map +10 -0
- package/packages/web/dist/assets/main-4cxs7prw.js +356 -0
- package/packages/web/dist/assets/main-4cxs7prw.js.map +103 -0
- package/packages/web/dist/assets/styles-kcx1x337.css +1 -0
- package/packages/web/dist/icon.svg +11 -0
- package/packages/web/dist/index.html +16 -0
- package/packages/web/dist/sql-wasm.wasm +0 -0
- package/packages/web/dist/sw.js +186 -0
- package/packages/web/src/bl/actions.js +410 -0
- package/packages/web/src/bl/activity.js +306 -0
- package/packages/web/src/bl/commands.js +274 -0
- package/packages/web/src/bl/fileType.js +49 -0
- package/packages/web/src/bl/index.js +70 -0
- package/packages/web/src/bl/links.js +54 -0
- package/packages/web/src/bl/offline.js +268 -0
- package/packages/web/src/bl/openers.js +71 -0
- package/packages/web/src/bl/pluginInstall.js +59 -0
- package/packages/web/src/bl/services.js +143 -0
- package/packages/web/src/bl/social.js +234 -0
- package/packages/web/src/bl/tagQuery.js +44 -0
- package/packages/web/src/main.js +10 -0
- package/packages/web/src/platform/api.js +529 -0
- package/packages/web/src/platform/commands.js +89 -0
- package/packages/web/src/platform/context.js +77 -0
- package/packages/web/src/platform/contributions.js +156 -0
- package/packages/web/src/platform/index.js +150 -0
- package/packages/web/src/platform/keybindings.js +199 -0
- package/packages/web/src/platform/mediaUrls.js +137 -0
- package/packages/web/src/platform/navigation.js +131 -0
- package/packages/web/src/platform/notifications.js +50 -0
- package/packages/web/src/platform/overlay.js +81 -0
- package/packages/web/src/platform/pluginClientDb.js +132 -0
- package/packages/web/src/platform/pluginDock.js +141 -0
- package/packages/web/src/platform/pluginFrames.js +194 -0
- package/packages/web/src/platform/pluginHost.js +648 -0
- package/packages/web/src/platform/pluginMedia.js +62 -0
- package/packages/web/src/platform/pluginModules.js +90 -0
- package/packages/web/src/platform/pluginNet.js +71 -0
- package/packages/web/src/platform/pluginPackage.js +247 -0
- package/packages/web/src/platform/pluginRpc.js +377 -0
- package/packages/web/src/platform/pluginSigning.js +168 -0
- package/packages/web/src/platform/pluginStore.js +67 -0
- package/packages/web/src/platform/settings.js +101 -0
- package/packages/web/src/platform/spatialNav.js +286 -0
- package/packages/web/src/platform/viewport.js +123 -0
- package/packages/web/src/platform/voice.js +133 -0
- package/packages/web/src/platform/voiceSearch.js +155 -0
- package/packages/web/src/platform/whenclause.js +162 -0
- package/packages/web/src/platform/workbench.js +156 -0
- package/packages/web/src/runtime.js +73 -0
- package/packages/web/src/styles.css +1382 -0
- package/packages/web/src/ui/components/activityBar.js +35 -0
- package/packages/web/src/ui/components/activityPanel.js +132 -0
- package/packages/web/src/ui/components/commandPalette.js +154 -0
- package/packages/web/src/ui/components/editorArea.js +75 -0
- package/packages/web/src/ui/components/launcher.js +392 -0
- package/packages/web/src/ui/components/openers/index.js +212 -0
- package/packages/web/src/ui/components/openers/markdown.js +222 -0
- package/packages/web/src/ui/components/overlays.js +255 -0
- package/packages/web/src/ui/components/phoneChrome.js +188 -0
- package/packages/web/src/ui/components/pluginReview.js +151 -0
- package/packages/web/src/ui/components/pluginsView.js +120 -0
- package/packages/web/src/ui/components/settingsView.js +258 -0
- package/packages/web/src/ui/components/social.js +290 -0
- package/packages/web/src/ui/components/statusBar.js +198 -0
- package/packages/web/src/ui/components/views/grid.js +115 -0
- package/packages/web/src/ui/components/views/index.js +155 -0
- package/packages/web/src/ui/components/views/list.js +50 -0
- package/packages/web/src/ui/components/views/parts.js +58 -0
- package/packages/web/src/ui/compositions/workbench.js +125 -0
- package/packages/web/src/ui/format.js +33 -0
- package/packages/web/src/ui/icon.js +81 -0
- package/packages/web/src/ui/media.js +114 -0
- package/packages/web/src/ui/sanitize.js +86 -0
- package/packages/web/src/workbench.js +205 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import{a as W8,c as PY,d as R8}from"./chunk-4xqbzebh.js";var dQ={};PY(dQ,{wbr:()=>kI,video:()=>bI,vdom:()=>YC,ul:()=>YI,u:()=>_I,track:()=>vI,tr:()=>EL,title:()=>wY,time:()=>TI,thead:()=>CL,th:()=>BL,tfoot:()=>QL,textarea:()=>RL,template:()=>NL,td:()=>AL,tbody:()=>eI,table:()=>tI,svg:()=>nI,sup:()=>wI,summary:()=>VL,sub:()=>SI,style:()=>kY,strong:()=>jI,special:()=>OY,span:()=>OI,source:()=>dI,small:()=>zI,slot:()=>PL,settings:()=>SY,select:()=>WL,section:()=>aY,script:()=>xY,schedule:()=>qL,samp:()=>qI,s:()=>NI,reconcile:()=>jY,q:()=>PI,progress:()=>UL,pre:()=>JI,portal:()=>lI,picture:()=>cI,param:()=>pI,p:()=>KI,output:()=>ZL,option:()=>$L,optgroup:()=>HL,ol:()=>EI,object:()=>mI,noscript:()=>gY,nav:()=>oY,meter:()=>XL,meta:()=>TY,math:()=>oI,mark:()=>VI,map:()=>hI,main:()=>nY,link:()=>_Y,li:()=>CI,legend:()=>GL,label:()=>DL,kbd:()=>MI,ins:()=>FI,input:()=>LL,img:()=>yI,iframe:()=>uI,i:()=>RI,html:()=>UB,hr:()=>BI,header:()=>fY,h6:()=>dY,h5:()=>lY,h4:()=>cY,h3:()=>pY,h2:()=>mY,h1:()=>uY,h:()=>qY,form:()=>IL,footer:()=>bY,flush:()=>zL,figure:()=>QI,figcaption:()=>AI,fieldset:()=>YL,embed:()=>fI,em:()=>WI,dt:()=>eY,dodo:()=>DE,dl:()=>tY,div:()=>rY,dialog:()=>ML,dfn:()=>UI,details:()=>FL,del:()=>ZI,dd:()=>iY,datalist:()=>JL,data:()=>$I,colgroup:()=>rI,col:()=>iI,code:()=>HI,clear:()=>OL,cite:()=>XI,caption:()=>sI,canvas:()=>aI,button:()=>KL,br:()=>GI,blockquote:()=>sY,b:()=>DI,audio:()=>gI,aside:()=>vY,article:()=>hY,area:()=>xI,alias:()=>zY,address:()=>yY,abbr:()=>LI,a:()=>II});var LQ=Symbol("ELEMENT_NODE"),ZB=Symbol("ALIAS_NODE"),_Q=Symbol("SPECIAL_NODE"),lQ=Symbol("OPAQUE_NODE"),MA=Symbol("NODE_STATE");var XY=new Set(["__proto__","constructor","prototype"]),YE=(A,Q)=>Object.prototype.hasOwnProperty.call(A,Q);function HY(A,Q){return typeof Q==="string"&&A.toLowerCase()===Q.toLowerCase()}class kQ{constructor(A,Q,B){this.type=A,this.tag=Q,this.args=B}key(A){return this.k=A,this}on(A){return this.hooks=A,this}opaque(){if(this.type!==LQ)throw Error(".opaque() can only be used on element nodes (h).");return this.type=lQ,this}}function $Y(A,Q){if(A===Q)return!1;if(A&&Q&&typeof A==="object"&&typeof Q==="object"){if(A.constructor!==Q.constructor)return!0;if(Array.isArray(A)){if(A.length!==Q.length)return!0;for(let B=0;B<A.length;B++)if(A[B]!==Q[B])return!0;return!1}if(A.constructor===Object){let B=Object.keys(A);if(B.length!==Object.keys(Q).length)return!0;for(let C of B)if(!YE(Q,C)||A[C]!==Q[C])return!0;return!1}}return!0}function ZY(A){return Array.isArray(A)||A!=null&&typeof A[Symbol.iterator]==="function"&&typeof A!=="string"}function UY(A){return(...Q)=>new kQ(ZB,A,Q)}function WY(A){return(...Q)=>new kQ(_Q,A,Q)}function RY(A,Q){if(A.namespaceURI==="http://www.w3.org/1999/xhtml")switch(Q){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML"}return A.namespaceURI??A.host?.namespaceURI??"http://www.w3.org/1999/xhtml"}function IE(A){return{originalProps:Object.create(null),newVdom:A}}function JC(A,Q,B){let C=A.ownerDocument.createElementNS(RY(A,Q),Q);return C[MA]=IE(B),C}var LE=new WeakMap;function FY(A){let Q=[],B=A;while(B)if(Q.push(B),B.parentElement)B=B.parentElement;else B=B.getRootNode()?.host;return Q}function JE(A,Q){for(let B of Q)A.add(B)}function MY(A,Q){let B=Q??A?.defaultView??globalThis;return B.Node?.prototype??B.Element?.prototype}function VY(A){let Q=new Set;return A.addEventListener("focusin",(B)=>{Q.clear(),JE(Q,B.composedPath())}),A.addEventListener("focusout",(B)=>{if(!B.relatedTarget)Q.clear()}),JE(Q,FY(A.activeElement)),LE.set(A,Q),Q}var YC=(A)=>{let Q=A?.shouldUpdate??$Y,B=A?.isMap??((H)=>H?.constructor===Object),C=A?.mapIter??((H)=>Object.entries(H)),E=A?.mapGet??((H,U)=>H[U]),K=A?.mapMerge??((...H)=>Object.assign({},...H)),J=A?.newMap??((H)=>({...H})),Y=A?.mapPut??((H,U,$)=>{return H[U]=$,H}),I=A?.isSeq??ZY,D=A?.seqIter??((H)=>H),L=A?.convertName??((H)=>H),G=A?.convertTagName??L,X=A?.convertPropName??L,Z=A?.convertStyleName??L,R=A?.convertDataName??L,F=A?.convertClassName??L,V=A?.convertHookName??L,g=A?.listenerKey??"listener",b=A?.captureKey??"capture",M=A?.passiveKey??"passive",j=J({});function z(H){if(H==null)return[][Symbol.iterator]();if(typeof H[Symbol.iterator]==="function")return H[Symbol.iterator]();if(typeof H.next==="function")return H;return[H][Symbol.iterator]()}function y(H,U,$,N,O){if(H==null)return;for(let q in H)if(YE(H,q))U(q,H[q],$,N,O)}function p(H,U,$,N,O){if(H==null)return;let q=z(C(H)),m;while(!(m=q.next()).done){let BA=m.value;U(BA[0],BA[1],$,N,O)}}let S=A?.mapEach??(A?.mapIter?p:y);function _(H){return H===null||H===void 0||H===!1}function r(H,U,$){let N=z(D(U)),O;while(!(O=N.next()).done){let q=O.value;if($&&_(q))continue;if(!I(q))H.push(q);else r(H,q,$)}}function t(H,U){let $=[];return r($,H,U),$}let a=A?.flattenSeq??t;function gA(H,U){let $=[];for(let N=U;N<H.length;N++){let O=H[N];if(_(O))continue;if(!I(O))$.push(O);else r($,O,!0)}return $}function IA(H){return _(H)?"":String(H)}function LA(H,U,...$){if(!B(U)){if(U!==null&&U!==void 0)$.unshift(U);U=j}return new kQ(LQ,G(H),[U,...$])}function e(H,U,$){$.setProperty(Z(H),U)}function o(H,U,$,N){if(E(N,H)!==void 0)return;$.removeProperty(Z(H))}function JA(H,U,$){let N=H.style;S($,e,N),S(U,o,N,$)}function AA(H,U,$){$.setAttribute(X(H),U)}function YQ(H,U,$,N){if(E(N,H)!==void 0)return;$.removeAttribute(X(H))}function ZA(H,U,$){S($,AA,H),S(U,YQ,H,$)}function TA(H,U,$){$.dataset[R(H)]=U}function UA(H,U,$,N){if(E(N,H)!==void 0)return;delete $.dataset[R(H)]}function DA(H,U,$){S($,TA,H),S(U,UA,H,$)}function n(H,U,$){let N=new Set;for(let O of a(U,!0)){let q=F(O);if(q)N.add(q)}for(let O of a($,!0)){let q=F(O);if(!q)continue;N.delete(q),H.classList.add(q)}for(let O of N)H.classList.remove(O)}function qA(H,U,$,N){if(XY.has($)){console.error(`Refusing to assign unsafe prop name '${$}' to a DOM node.`);return}let O=U.originalProps;if(!($ in O))O[$]=H[$];H[$]=N===void 0?O[$]:N}function aA(H,U,$){let N=U.originalProps;if($ in N)H[$]=N[$],delete N[$]}function sA(H,U,$,N,O){let q=X(H),m=E(N,H);if(Object.is(U,m))return;switch(q){case"$styling":{if(!B(U))throw Error("invalid value for styling prop");JA($,m??j,U??j);break}case"$classes":{if(!I(U))throw Error("invalid value for classes prop");n($,m??[],U??[]);break}case"$attrs":{if(!B(U))throw Error("invalid value for attrs prop");ZA($,m??j,U??j);break}case"$dataset":{if(!B(U))throw Error("invalid value for dataset prop");DA($,m??j,U??j);break}default:{if(O)qA($,$[MA],q,U);else if(U===void 0)$.removeAttribute(q);else $.setAttribute(q,U);break}}}function jQ(H,U,$,N,O){if(E(N,H)!==void 0)return;let q=X(H);switch(q){case"$styling":JA($,U??j,j);break;case"$classes":n($,U??[],[]);break;case"$attrs":ZA($,U??j,j);break;case"$dataset":DA($,U??j,j);break;default:{if(O)aA($,$[MA],q);else $.removeAttribute(q);break}}}function iA(H,U){let $=H[MA],N=H.namespaceURI==="http://www.w3.org/1999/xhtml",O=$.vdom?.args[0]??j;S(U,sA,H,O,N),S(O,jQ,H,U,N)}function rA(H,U,$){if(typeof $==="function")H.addEventListener(U,$);else if($!=null)H.addEventListener(U,E($,g),{capture:!!E($,b),passive:!!E($,M)})}function tA(H,U,$){if(typeof $==="function")H.removeEventListener(U,$);else if($!=null)H.removeEventListener(U,E($,g),!!E($,b))}function eA(H,U,$){let N=V(H);if(N[0]==="$")return;rA($,N,U)}function pQ(H,U,$,N){let O=V(H);if(O[0]==="$")return;let q=E(N,H);if(U===q)return;tA($,O,q),rA($,O,U)}function CY(H,U,$,N){let O=V(H);if(O[0]==="$"||E(N,H)!==void 0)return;tA($,O,U)}function QE(H,U){let $=H[MA],N=U??j;if(!$.vdom){S(N,eA,H);return}let O=$.vdom.hooks??j;S(N,pQ,H,O),S(O,CY,H,N)}function KC(H){let U=H[MA],$=U.newVdom,N=U.vdom,O=$.args;switch($.type){case LQ:{iA(H,O[0]),cQ(H,gA(O,1));break}case lQ:{iA(H,O[0]);break}case ZB:{let q=$.tag.apply(H,$.args);if(_(q))cQ(H,[]);else if(I(q))cQ(H,a(q,!0));else cQ(H,[q]);break}case _Q:{try{$.tag.update?.(H,$.args,N?.args)}catch(q){console.error(q)}break}}if($.hooks||N?.hooks)QE(H,$.hooks??j);try{$.hooks?.$update?.(H,$,N)}catch(q){console.error(q)}U.vdom=$,delete U.newVdom}function EY(H,U){if(typeof U!=="object"||U===null)return H.ownerDocument.createTextNode(IA(U));let $;switch(U.type){case LQ:case lQ:$=JC(H,U.tag,U);break;case ZB:$=JC(H,"udom-alias",U),$.style.display="contents";break;case _Q:$=JC(H,"udom-special",U),$.style.display="contents";break;default:throw Error("Invalid VDOM node")}return $}function BE(H){if(H.children)for(let U of H.children)$B(U)}function $B(H){let U=H[MA];if(!U)return;let{vdom:$}=U;if(!$){delete H[MA];return}if($.hooks)QE(H,j);if($.type===LQ||$.type===lQ)iA(H,j);if($.type===LQ||$.type===ZB)BE(H);delete H[MA];try{if($.type===_Q)$.tag.detach?.(H);$.hooks?.$detach?.(H)}catch(N){console.error(N)}}function KY(H,U){let $=H[MA];if(Q($.vdom.args,U.args)||Q($.vdom.hooks,U.hooks))$.newVdom=U;return H}function JY(H){let U=new Map,$={nodes:[],cursor:0};for(let N of H.childNodes){if(N.nodeType===3){$.nodes.push(N);continue}let O=N[MA],q=O?.vdom;if(q===void 0){if(O?.newVdom)throw Error("Attempt to reconcile against a target while already working on a reconciliation against that same target, this is not allowed");continue}let m=U.get(q.tag);if(!m)m={nodesForKey:null,nodesWithoutKey:{nodes:[],cursor:0}},U.set(q.tag,m);if(q.k!==void 0){if(!m.nodesForKey)m.nodesForKey=new Map;let BA=m.nodesForKey.get(q.k);if(BA)BA.nodes.push(N);else m.nodesForKey.set(q.k,{nodes:[N],cursor:0})}else m.nodesWithoutKey.nodes.push(N)}return{byTag:U,textNodes:$}}function CE(H){if(!H||H.cursor>=H.nodes.length)return;return H.nodes[H.cursor++]}function YY(H,U,$,N){let O=H.firstChild;for(let q=0;q<U.length;q++){let m=U[q];if(m===O){O=O.nextSibling;continue}(N&&m.isConnected?N:$).call(H,m,O)}}function IY(H,U,$,N){let O=U[N],q=O;for(let BA=N-1;BA>=0;BA--){let mA=U[BA];if(mA!==q.previousSibling)$.call(H,mA,q);q=mA}let m=O.nextSibling;for(let BA=N+1;BA<U.length;BA++){let mA=U[BA];if(mA===m)m=m.nextSibling;else $.call(H,mA,m)}}function LY(H,U){for(let $=0;$<H.length;$++)if(U.has(H[$]))return $;return-1}function DY(H){let U=H[MA];if(!U?.newVdom)return;if(!U.vdom)try{if(U.newVdom.hooks?.$attach?.(H),U.newVdom.type===_Q)U.newVdom.tag.attach?.(H)}catch($){console.error($)}KC(H)}function cQ(H,U){let $=H.firstChild?new Set(H.childNodes):null,{byTag:N,textNodes:O}=JY(H),q=[];for(let GA of U){let IQ;if(GA instanceof kQ){let wQ=N.get(GA.tag),TQ=wQ?CE(GA.k!==void 0?wQ.nodesForKey?.get(GA.k):wQ.nodesWithoutKey):void 0;IQ=TQ?KY(TQ,GA):EY(H,GA)}else{let wQ=CE(O),TQ=IA(GA);if(wQ){if(IQ=wQ,IQ.nodeValue!==TQ)IQ.nodeValue=TQ}else IQ=H.ownerDocument.createTextNode(TQ)}$?.delete(IQ),q.push(IQ)}if($)for(let GA of $)$B(GA),H.removeChild(GA);if(q.length===0)return;let m=H.ownerDocument,BA=MY(m,A?.window),mA=BA.insertBefore,EE=typeof BA.moveBefore==="function"?BA.moveBefore:null,KE=H.isConnected,SQ=-1;if(KE&&!EE){let GA=LE.get(m)??VY(m);if(SQ=LY(q,GA),SQ!==-1&&q[SQ].parentNode!==H)SQ=-1}if(SQ===-1)YY(H,q,mA,KE?EE:null);else IY(H,q,mA,SQ);for(let GA=0;GA<q.length;GA++)DY(q[GA])}function GY(H,U){let $=H[MA];if(U===null||U===void 0){if($)$B(H);else BE(H);H.replaceChildren();return}if(I(U)){cQ(H,a(U,!0));return}if(U instanceof kQ){if($){if($.vdom.type===U.type&&$.vdom.tag===U.tag){if(Q($.vdom.args,U.args)||Q($.vdom.hooks,U.hooks))$.newVdom=U,KC(H);return}$B(H)}switch(U.type){case LQ:case lQ:if(!HY(H.nodeName,G(U.tag)))throw Error("incompatible target for vdom");break}H[MA]=IE(U);try{if(U.hooks?.$attach?.(H),U.type===_Q)U.tag.attach?.(H)}catch(N){console.error(N)}KC(H);return}throw Error("invalid vdom")}return{h:LA,alias:UY,special:WY,reconcile:GY,settings:{shouldUpdate:Q,isMap:B,mapIter:C,mapEach:S,mapGet:E,mapMerge:K,newMap:J,mapPut:Y,isSeq:I,flattenSeq:a,seqIter:D,convertTagName:G,convertPropName:X,convertStyleName:Z,convertDataName:R,convertClassName:F,convertHookName:V,convertName:L,listenerKey:g,captureKey:b,passiveKey:M}}};function UB({h:A}){return{title:(...Q)=>A("title",...Q),meta:(Q)=>A("meta",Q),link:(Q)=>A("link",Q),style:(...Q)=>A("style",...Q),script:(...Q)=>A("script",...Q),noscript:(...Q)=>A("noscript",...Q),address:(...Q)=>A("address",...Q),article:(...Q)=>A("article",...Q),aside:(...Q)=>A("aside",...Q),footer:(...Q)=>A("footer",...Q),header:(...Q)=>A("header",...Q),h1:(...Q)=>A("h1",...Q),h2:(...Q)=>A("h2",...Q),h3:(...Q)=>A("h3",...Q),h4:(...Q)=>A("h4",...Q),h5:(...Q)=>A("h5",...Q),h6:(...Q)=>A("h6",...Q),main:(...Q)=>A("main",...Q),nav:(...Q)=>A("nav",...Q),section:(...Q)=>A("section",...Q),blockquote:(...Q)=>A("blockquote",...Q),dd:(...Q)=>A("dd",...Q),div:(...Q)=>A("div",...Q),dl:(...Q)=>A("dl",...Q),dt:(...Q)=>A("dt",...Q),figcaption:(...Q)=>A("figcaption",...Q),figure:(...Q)=>A("figure",...Q),hr:()=>A("hr"),li:(...Q)=>A("li",...Q),ol:(...Q)=>A("ol",...Q),p:(...Q)=>A("p",...Q),pre:(...Q)=>A("pre",...Q),ul:(...Q)=>A("ul",...Q),a:(...Q)=>A("a",...Q),abbr:(...Q)=>A("abbr",...Q),b:(...Q)=>A("b",...Q),br:()=>A("br"),cite:(...Q)=>A("cite",...Q),code:(...Q)=>A("code",...Q),data:(...Q)=>A("data",...Q),del:(...Q)=>A("del",...Q),dfn:(...Q)=>A("dfn",...Q),em:(...Q)=>A("em",...Q),i:(...Q)=>A("i",...Q),ins:(...Q)=>A("ins",...Q),kbd:(...Q)=>A("kbd",...Q),mark:(...Q)=>A("mark",...Q),q:(...Q)=>A("q",...Q),s:(...Q)=>A("s",...Q),samp:(...Q)=>A("samp",...Q),small:(...Q)=>A("small",...Q),span:(...Q)=>A("span",...Q),strong:(...Q)=>A("strong",...Q),sub:(...Q)=>A("sub",...Q),sup:(...Q)=>A("sup",...Q),time:(...Q)=>A("time",...Q),u:(...Q)=>A("u",...Q),wbr:()=>A("wbr"),area:(Q)=>A("area",Q),audio:(...Q)=>A("audio",...Q),img:(Q)=>A("img",Q),map:(...Q)=>A("map",...Q),track:(Q)=>A("track",Q),video:(...Q)=>A("video",...Q),embed:(Q)=>A("embed",Q),iframe:(...Q)=>A("iframe",...Q),object:(...Q)=>A("object",...Q),param:(Q)=>A("param",Q),picture:(...Q)=>A("picture",...Q),portal:(...Q)=>A("portal",...Q),source:(Q)=>A("source",Q),svg:(...Q)=>A("svg",...Q),math:(...Q)=>A("math",...Q),canvas:(...Q)=>A("canvas",...Q),caption:(...Q)=>A("caption",...Q),col:(Q)=>A("col",Q),colgroup:(...Q)=>A("colgroup",...Q),table:(...Q)=>A("table",...Q),tbody:(...Q)=>A("tbody",...Q),td:(...Q)=>A("td",...Q),tfoot:(...Q)=>A("tfoot",...Q),th:(...Q)=>A("th",...Q),thead:(...Q)=>A("thead",...Q),tr:(...Q)=>A("tr",...Q),button:(...Q)=>A("button",...Q),datalist:(...Q)=>A("datalist",...Q),fieldset:(...Q)=>A("fieldset",...Q),form:(...Q)=>A("form",...Q),input:(Q)=>A("input",Q),label:(...Q)=>A("label",...Q),legend:(...Q)=>A("legend",...Q),meter:(...Q)=>A("meter",...Q),optgroup:(...Q)=>A("optgroup",...Q),option:(...Q)=>A("option",...Q),output:(...Q)=>A("output",...Q),progress:(...Q)=>A("progress",...Q),select:(...Q)=>A("select",...Q),textarea:(...Q)=>A("textarea",...Q),details:(...Q)=>A("details",...Q),dialog:(...Q)=>A("dialog",...Q),summary:(...Q)=>A("summary",...Q),slot:(...Q)=>A("slot",...Q),template:(...Q)=>A("template",...Q)}}function IC({window:A}={}){let Q=!1,B=0,C=[];function E(){return A??globalThis}function K(Z){let R=E().requestAnimationFrame;return typeof R==="function"?R.call(E(),Z):setTimeout(Z,16)}function J(Z){let R=E().cancelAnimationFrame;if(typeof R==="function")R.call(E(),Z);else clearTimeout(Z)}function Y(){return E().performance?.now()??Date.now()}function I(Z){for(let R of Z)try{R()}catch(F){console.error("Error in scheduled function:",F)}}function D(){let Z=Y();B=0;while(C.length>0){let R=C.splice(0,100);if(I(R),Y()-Z>10&&C.length>0){B=K(D);return}}Q=!1}function L(Z,{signal:R}={}){if(R?.aborted)return;let F=Z;if(R)F=()=>{if(!R.aborted)Z()};if(C.push(F),!Q)Q=!0,B=K(D)}function G(){if(B)J(B),B=0;Q=!0;while(C.length>0){let Z=C;C=[],I(Z)}Q=!1}function X(){if(B)J(B);C=[],Q=!1,B=0}return{schedule:L,flush:G,clear:X}}function DE(A){let Q=YC(A),B=UB(Q),C=A?.scheduler??IC(A);return{...Q,...B,...C}}var NY=DE();var{h:qY,alias:zY,special:OY,reconcile:jY,settings:SY,title:wY,meta:TY,link:_Y,style:kY,script:xY,noscript:gY,address:yY,article:hY,aside:vY,footer:bY,header:fY,h1:uY,h2:mY,h3:pY,h4:cY,h5:lY,h6:dY,main:nY,nav:oY,section:aY,blockquote:sY,dd:iY,div:rY,dl:tY,dt:eY,figcaption:AI,figure:QI,hr:BI,li:CI,ol:EI,p:KI,pre:JI,ul:YI,a:II,abbr:LI,b:DI,br:GI,cite:XI,code:HI,data:$I,del:ZI,dfn:UI,em:WI,i:RI,ins:FI,kbd:MI,mark:VI,q:PI,s:NI,samp:qI,small:zI,span:OI,strong:jI,sub:SI,sup:wI,time:TI,u:_I,wbr:kI,area:xI,audio:gI,img:yI,map:hI,track:vI,video:bI,embed:fI,iframe:uI,object:mI,param:pI,picture:cI,portal:lI,source:dI,svg:nI,math:oI,canvas:aI,caption:sI,col:iI,colgroup:rI,table:tI,tbody:eI,td:AL,tfoot:QL,th:BL,thead:CL,tr:EL,button:KL,datalist:JL,fieldset:YL,form:IL,input:LL,label:DL,legend:GL,meter:XL,optgroup:HL,option:$L,output:ZL,progress:UL,select:WL,textarea:RL,details:FL,dialog:ML,summary:VL,slot:PL,template:NL,schedule:qL,flush:zL,clear:OL}=NY;function jL(A,{signal:Q}={}){queueMicrotask(()=>{if(!Q?.aborted)A()})}function SL(A){return(Q)=>A("pre",{$styling:{"background-color":"#fdd",color:"#330",padding:"1em","white-space":"pre-wrap"}},A("strong",null,`Error: ${Q?.message??String(Q)}`),`
|
|
2
|
+
|
|
3
|
+
`,Q?.stack??"")}function GE(A){return A!=null&&typeof A.special==="function"&&typeof A.reconcile==="function"}function LC(A){let Q=GE(A)?{dodo:A}:A,B=Q?.dodo;if(!GE(B))throw Error("a dodo instance must be provided in settings, e.g. reactive({dodo})");return{schedule:typeof B.schedule==="function"?B.schedule:jL,renderError:SL(B.h),...Q,dodo:B,...B.settings}}var pA=Symbol("dodo.reactive.PENDING"),XA=Symbol("dodo.reactive.NOTHING");function GQ(A){return A!=null&&typeof A.onDirty==="function"&&typeof A.getValue==="function"}function xQ(A){return GQ(A)?A.getValue():A}function wL(A){if(typeof A==="function")return A;if(A&&typeof A.unsubscribe==="function")return()=>A.unsubscribe();return()=>{}}function DC(){let A=new Set;return{listeners:A,notify(){for(let Q of Array.from(A))try{Q()}catch(B){console.error("Error in dodo cell listener:",B)}}}}function WB(A,Q){let{listeners:B,notify:C}=DC(),E=null;return{onDirty(K){if(B.add(K),B.size===1)try{E=wL(A(C))}catch(Y){throw B.delete(K),Y}let J=!1;return()=>{if(J)return;if(J=!0,B.delete(K),B.size===0&&E){let Y=E;E=null,Y()}}},getValue(){return Q()}}}function f(A){let Q=A,{listeners:B,notify:C}=DC();return{onDirty(E){return B.add(E),()=>B.delete(E)},getValue(){return Q},setValue(E){if(Object.is(E,Q))return;Q=E,C()},update(E){this.setValue(E(Q))}}}function RB(A){return{onDirty(){return()=>{}},getValue(){return A}}}function XQ(A,Q){let B=Array.isArray(A)?A:[A],{listeners:C,notify:E}=DC(),K=null,J=XA,Y=()=>{J=XA,E()},I=()=>{let D=Array(B.length);for(let L=0;L<B.length;L++){let G=xQ(B[L]);if(G===pA)return pA;D[L]=G}return Q(...D)};return{onDirty(D){if(C.add(D),C.size===1)J=XA,K=B.map((G)=>GQ(G)?G.onDirty(Y):null);let L=!1;return()=>{if(L)return;if(L=!0,C.delete(D),C.size===0&&K){for(let G of K)G?.();K=null,J=XA}}},getValue(){if(J===XA||!K)J=I();return J}}}function XE(A,Q){return XQ([A],Q)}function HE(A,{initial:Q=pA}={}){return TL(A,{initial:Q},(B,C)=>B.subscribe({next:C.next,error:C.error,complete:C.complete}))}function TL(A,{initial:Q},B){let C=Q,E=XA;return WB((J)=>{return B(A,{next(I){C=I,E=XA,J()},error(I){E=I,J()},complete(){}})},()=>{if(E!==XA)throw E;return C})}function $E(A){return{subscribe(Q){let B=typeof Q==="function"?{next:Q}:Q??{},C=()=>{let K;try{K=xQ(A)}catch(J){B.error?.(J);return}if(K!==pA)B.next?.(K)},E=GQ(A)?A.onDirty(C):()=>{};return C(),{unsubscribe:E}}}}function _A(A,Q){let B=()=>{let E;try{E=xQ(A)}catch(K){console.error("Error reading cell in effect:",K);return}if(E===pA)return;Q(E)},C=GQ(A)?A.onDirty(B):()=>{};return B(),C}var DQ=Symbol("dodo.reactive.watch");function FB(A){let Q=LC(A),{dodo:B,schedule:C,renderError:E}=Q,{special:K,reconcile:J}=B,Y=Q.mapGet??((G,X)=>G[X]),I=(G,X)=>G==null?void 0:Y(G,X),D=Q.shouldUpdate??((G,X)=>G!==X);return{watch:K({attach(G){G[DQ]={source:XA,builder:null,placeholder:void 0,errorBuilder:void 0,unsubscribe:null,abortController:null,renderScheduled:!1,lastValue:XA,lastBuilder:XA}},update(G,[X,Z,R]){let F=G[DQ];if(!F)return;if(F.builder=Z,F.placeholder=I(R,"placeholder"),F.errorBuilder=I(R,"error"),F.source!==X){if(F.unsubscribe?.(),F.unsubscribe=null,F.abortController?.abort(),F.abortController=new AbortController,F.source=X,F.lastValue=XA,GQ(X))try{F.unsubscribe=X.onDirty(()=>this.invalidate(G))}catch(V){this.renderError(G,V);return}}this.render(G)},invalidate(G){let X=G[DQ];if(!X||X.renderScheduled)return;X.renderScheduled=!0,C(()=>this.render(G),{signal:X.abortController?.signal})},render(G){let X=G[DQ];if(!X)return;X.renderScheduled=!1;let Z;try{Z=xQ(X.source===XA?void 0:X.source)}catch(R){this.renderError(G,R);return}if(X.builder===X.lastBuilder&&X.lastValue!==XA&&!D(X.lastValue,Z))return;X.lastValue=Z,X.lastBuilder=X.builder;try{if(Z===pA)J(G,X.placeholder?[X.placeholder()]:[]);else J(G,[X.builder(Z)])}catch(R){this.renderError(G,R)}},renderError(G,X){let Z=G[DQ];if(!Z)return;Z.lastValue=XA,Z.lastBuilder=XA,console.error("Error in watched cell:",X);try{J(G,[(Z.errorBuilder??E)(X)])}catch(R){console.error("Error rendering the error view:",R)}},detach(G){let X=G[DQ];if(!X)return;X.unsubscribe?.(),X.abortController?.abort(),delete G[DQ],J(G,null)}})}}var{watch:MB}=FB({dodo:dQ});var w=dQ;function nQ(A){let Q={status:"idle"};return WB((B)=>{if(Q.status==="idle")Q={status:"running"},Promise.resolve().then(A).then((C)=>{Q={status:"done",value:C},B()},(C)=>{Q={status:"failed",error:C},B()});return()=>{}},()=>{if(Q.status==="failed")throw Q.error;return Q.status==="done"?Q.value:pA})}var ZE={watch:MB,cell:f,derive:XQ,constant:RB,mapCell:XE,connectable:WB,fromObservable:HE,fromAsync:nQ,toObservable:$E,effect:_A,isCell:GQ,readCell:xQ,PENDING:pA};var v=Object.freeze({NOT_FOUND:"not_found",ALREADY_EXISTS:"already_exists",INVALID:"invalid",CONFLICT:"conflict",UNAUTHORIZED:"unauthorized",FORBIDDEN:"forbidden",UNSUPPORTED:"unsupported",QUOTA:"quota",TOO_LARGE:"too_large",BAD_RANGE:"bad_range",TRANSIENT:"transient",TIMEOUT:"timeout",ABORTED:"aborted",INTERNAL:"internal"}),_L=new Set([v.TRANSIENT,v.TIMEOUT,v.QUOTA]),kL={[v.NOT_FOUND]:404,[v.ALREADY_EXISTS]:409,[v.INVALID]:400,[v.CONFLICT]:412,[v.UNAUTHORIZED]:401,[v.FORBIDDEN]:403,[v.UNSUPPORTED]:501,[v.QUOTA]:429,[v.TOO_LARGE]:413,[v.BAD_RANGE]:416,[v.TRANSIENT]:503,[v.TIMEOUT]:504,[v.ABORTED]:499,[v.INTERNAL]:500};class P extends Error{constructor(A,Q,B={}){super(Q,B.cause!==void 0?{cause:B.cause}:void 0);if(this.name="TroveError",this.code=A||v.INTERNAL,this.retryable=B.retryable??_L.has(this.code),this.details=B.details??null,this.status=kL[this.code]??500,this.code===v.QUOTA&&!this.retryable)this.status=507}toJSON(){return{error:{code:this.code,message:this.message,retryable:this.retryable,...this.details?{details:this.details}:{}}}}static notFound(A,Q){return new P(v.NOT_FOUND,A?`${A} not found`:"Not found",Q)}static alreadyExists(A,Q){return new P(v.ALREADY_EXISTS,`${A} already exists`,Q)}static invalid(A,Q){return new P(v.INVALID,A,Q)}static conflict(A,Q){return new P(v.CONFLICT,A,Q)}static unsupported(A,Q){return new P(v.UNSUPPORTED,A,Q)}static transient(A,Q){return new P(v.TRANSIENT,A,{retryable:!0,...Q})}static timeout(A,Q){return new P(v.TIMEOUT,A,{retryable:!0,...Q})}static aborted(A="Operation aborted",Q){return new P(v.ABORTED,A,{retryable:!1,...Q})}static unauthorized(A="Unauthorized",Q){return new P(v.UNAUTHORIZED,A,Q)}static tooLarge(A="Too large",Q){return new P(v.TOO_LARGE,A,{retryable:!1,...Q})}static badRange(A="Range not satisfiable",Q){return new P(v.BAD_RANGE,A,{retryable:!1,...Q})}static forbidden(A="Forbidden",Q){return new P(v.FORBIDDEN,A,Q)}static internal(A="Internal error",Q){return new P(v.INTERNAL,A,Q)}}function oQ(A,Q="Unexpected error"){if(A instanceof P)return A;if(A?.name==="AbortError"||A?.code==="ABORT_ERR")return P.aborted(A.message||"Operation aborted",{cause:A});if(new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","EPIPE","ENOTFOUND","UND_ERR_SOCKET"]).has(A?.code)||A instanceof TypeError&&/fetch|network/i.test(A.message||""))return P.transient(A.message||"Network error",{cause:A});switch(A?.code){case"ENOENT":return P.notFound(null,{cause:A});case"EEXIST":return P.alreadyExists("Path",{cause:A});case"EACCES":case"EPERM":return new P(v.FORBIDDEN,"Permission denied",{cause:A});case"ENOSPC":return new P(v.QUOTA,"The storage volume is full — free some space and try again",{cause:A,retryable:!1});case"EDQUOT":return new P(v.QUOTA,"The storage quota for this volume has been reached",{cause:A,retryable:!1});case"EFBIG":return new P(v.QUOTA,"That file is larger than this filesystem can store",{cause:A,retryable:!1})}return P.internal(A?.message||Q,{cause:A})}function UE(A){if(A instanceof P)return A.retryable;return oQ(A).retryable}function WE(A=""){let Q=(globalThis.crypto?.randomUUID?.()??xL()).replace(/-/g,"");return A?`${A}_${Q}`:Q}function xL(){let A="";for(let Q=0;Q<32;Q++)A+=Math.floor(Math.random()*16).toString(16);return A}function RE(A){let Q=String(A||"").lastIndexOf(".");return Q>0?String(A).slice(Q).toLowerCase():""}function FE(A,Q){if(!A||!Q)return!1;if(typeof A.match==="function")try{if(A.match(Q))return!0}catch{}let B=RE(Q.name||"");if(B&&(A.ext||[]).some((K)=>(K.startsWith(".")?K:"."+K).toLowerCase()===B))return!0;let C=Q.contentType||"";return(A.mime||A.contentType||[]).some((K)=>K.endsWith("/*")?C.startsWith(K.slice(0,-1)):C===K)}var gQ="trove+contrib:",ME="core",gL=/^(?:core|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)$/,yL=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function hL(A){return typeof A==="string"&&gL.test(A)}function VB(A){return typeof A==="string"&&yL.test(A)}function yA(A){return PB(A),`${A.domain}/${A.name}`}function AQ(A,Q){if(!VB(Q))throw P.invalid(`Invalid contribution name "${Q}"`);return`${gQ}${yA(A)}/${Q}`}var vL="workbench";function VE(A){return`${gQ}${ME}/${vL}/${A}`}function QQ(A){if(typeof A!=="string"||!A.startsWith(gQ))return null;let Q=A.slice(gQ.length),B=Q.indexOf("/"),C=Q.indexOf("/",B+1);if(B<0||C<0)return null;let E=Q.slice(0,B),K=Q.slice(B+1,C),J=Q.slice(C+1);if(!E||!K||!J)return null;return{domain:E,plugin:K,name:J,pluginId:`${E}/${K}`}}function PE(A,Q){let B=QQ(Q);return!!B&&B.pluginId===`${A.domain}/${A.name}`}function PB(A){if(!hL(A?.domain))throw P.invalid(`Plugin manifest needs a valid "domain" (got ${JSON.stringify(A?.domain)})`);if(!VB(A?.name))throw P.invalid(`Plugin manifest needs a valid "name" (got ${JSON.stringify(A?.name)})`);if(A.domain===ME)throw P.invalid('The "core" domain is reserved for built-in contributions')}var qE={command:{normalize:(A)=>({title:A.title||null,category:A.category||null,icon:A.icon||null,when:A.when||null,palette:A.palette!==!1,offline:!!A.offline})},opener:{needsEntry:!0,normalize:(A)=>({title:A.title||null,match:NE(A.match),priority:A.priority??50,when:A.when||null,offline:!!A.offline,dock:A.dock||null})},indexer:{needsEntry:!0,normalize:(A)=>({title:A.title||null,match:NE(A.match)})},statusItem:{normalize:(A)=>{let Q=A.slot==="left"?"left":"right",B=A.render||"html";if(B!=="html")throw P.invalid(`statusItem "render" must be "html" (got ${JSON.stringify(B)})`);return{slot:Q,render:B,order:A.order??0,when:A.when||null,offline:!!A.offline,command:A.command||null}}},register:{normalize:(A)=>({default:A.default??null,description:A.description||null})},keymap:{normalize:(A)=>{if(!A.path||typeof A.path!=="string")throw P.invalid('keymap contribution needs a "path" to a JSON file in the package');return{path:A.path}}}},GC=Object.keys(qE);function cA(A){let Q=A?.contributes;if(Q==null)return[];if(typeof Q!=="object"||Array.isArray(Q))throw P.invalid('manifest "contributes" must be a map of name -> contribution');let B=[];for(let[C,E]of Object.entries(Q)){if(!E||typeof E!=="object")throw P.invalid(`Contribution "${C}" must be an object`);if(!VB(C))throw P.invalid(`Invalid contribution name "${C}"`);let K=qE[E.type];if(!K)throw P.invalid(`Contribution "${C}" has unknown type ${JSON.stringify(E.type)} (expected one of ${GC.join(", ")})`);let J=E.entry||A.entry;if(K.needsEntry&&!J)throw P.invalid(`Contribution "${C}" (${E.type}) needs an "entry" module`);B.push({name:C,uri:AQ(A,C),pluginId:yA(A),type:E.type,...K.normalize(E),...K.needsEntry?{entry:J}:{}})}return B}function bL(A,Q){return cA(A).filter((B)=>B.type===Q)}function XC(A){return bL(A,"indexer").map((Q)=>({id:Q.uri,name:Q.name,title:Q.title||Q.name,match:Q.match,entry:Q.entry}))}function zE(A){let Q;try{Q=JSON.parse(A)}catch(C){throw P.invalid("Keymap file is not valid JSON",{cause:C})}let B=Array.isArray(Q)?Q:Array.isArray(Q?.bindings)?Q.bindings:null;if(!B)throw P.invalid("Keymap file must be a JSON array of bindings");return B.filter((C)=>C&&typeof C.key==="string"&&typeof C.command==="string").map((C)=>({key:C.key,command:C.command,when:typeof C.when==="string"?C.when:null,args:Array.isArray(C.args)?C.args:void 0}))}function NE(A){if(!A||typeof A!=="object"||Array.isArray(A))return{};let Q=(K)=>K==null?void 0:(Array.isArray(K)?K:[K]).filter((J)=>typeof J==="string"),B={},C=Q(A.ext),E=Q(A.mime??A.contentType);if(C)B.ext=C;if(E)B.mime=E;if(typeof A.match==="function")B.match=A.match;return B}var fL=[...GC,"view"];function NB(A){return String(A).startsWith(gQ)?A:VE(A)}class HC{constructor(){this.items=new Map,this.cell=f([]),this.byType=new Map}#A(){this.cell.setValue([...this.items.values()])}register(A,Q){let B=Q?.type;if(!fL.includes(B))throw Error(`Unknown contribution type "${B}" for ${A}`);let C=NB(A),E=QQ(C);if(!E)throw Error(`Not a contribution URI: ${C}`);let K=Q.pluginId??(E.domain==="core"?null:E.pluginId),J={...Q,uri:C,type:B,id:E.domain==="core"?E.name:C,name:E.name,pluginId:K};return this.items.set(C,J),this.#A(),()=>this.unregister(C)}update(A,Q){let B=NB(A),C=this.items.get(B);if(!C)return!1;return this.items.set(B,{...C,...Q}),this.#A(),!0}unregister(A){if(this.items.delete(NB(A)))this.#A()}unregisterPlugin(A){let Q=!1;for(let[B,C]of this.items)if(C.pluginId===A)this.items.delete(B),Q=!0;if(Q)this.#A()}get(A){return A?this.items.get(NB(A))||null:null}all(){return[...this.items.values()]}ofType(A){return this.all().filter((Q)=>Q.type===A)}ofPlugin(A,Q){return this.all().filter((B)=>B.pluginId===A&&(!Q||B.type===Q))}observe(){return this.cell}observeType(A){let Q=this.byType.get(A);if(!Q)Q=XQ([this.cell],(B)=>B.filter((C)=>C.type===A)),this.byType.set(A,Q);return Q}openersFor(A){return this.ofType("opener").filter((Q)=>FE(Q.match,A)).sort((Q,B)=>(B.priority??0)-(Q.priority??0))}openerFor(A,Q,B){return this.openersFor(A).find((C)=>(!C.when||Q(C.when))&&(!B||B(C)))||null}keybindings(){return this.ofType("keymap").flatMap((A)=>(A.bindings||[]).map((Q)=>({...Q,keymap:A.uri,pluginId:A.pluginId})))}}var $C=new Map;function uL(A){if(!A)return()=>!0;if($C.has(A))return $C.get(A);let Q;try{Q=new jE(A).parseExpression()}catch(B){console.warn(`Invalid when clause: "${A}" — ${B.message}`),Q=()=>!1}return $C.set(A,Q),Q}function OE(A,Q){return uL(A)(Q||{})}var qB=/\s*(=~|==|!=|>=|<=|&&|\|\||[()!<>]|trove\+contrib:[A-Za-z0-9_./-]+|\/(?:\\.|[^/])*\/|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|[A-Za-z0-9_.:-]+)/y;class jE{constructor(A){this.src=A,this.tokens=this.#A(A),this.pos=0}#A(A){let Q=[],B=0;qB.lastIndex=0;while(B<A.length){qB.lastIndex=B;let C=qB.exec(A);if(!C||C.index==null){if(!A.slice(B).trim())break;throw Error(`Unexpected "${A.slice(B)}"`)}Q.push(C[1]),B=qB.lastIndex}return Q}#Q(){return this.tokens[this.pos]}#B(){return this.tokens[this.pos++]}#C(A){if(this.#Q()!==A)throw Error(`Expected "${A}"`);this.pos++}parseExpression(){let A=this.#E();if(this.pos!==this.tokens.length)throw Error(`Trailing "${this.#Q()}"`);return A}#E(){let A=this.#K();while(this.#Q()==="||"){this.#B();let Q=this.#K(),B=A;A=(C)=>B(C)||Q(C)}return A}#K(){let A=this.#J();while(this.#Q()==="&&"){this.#B();let Q=this.#J(),B=A;A=(C)=>B(C)&&Q(C)}return A}#J(){if(this.#Q()==="!"){this.#B();let A=this.#J();return(Q)=>!A(Q)}return this.#Y()}#Y(){let A=this.#I(),Q=this.#Q();if(["==","!=",">=","<=",">","<","=~"].includes(Q)){if(this.#B(),Q==="=~"){let C=this.#B(),E=mL(C);return(K)=>E.test(String(A(K)??""))}let B=this.#I();return(C)=>cL(Q,A(C),B(C))}return(B)=>pL(A(B))}#I(){let A=this.#B();if(A===void 0)throw Error("Unexpected end");if(A==="("){let Q=this.#E();return this.#C(")"),Q}if(A==="true")return()=>!0;if(A==="false")return()=>!1;if(/^-?\d+(\.\d+)?$/.test(A)){let Q=Number(A);return()=>Q}if(A[0]==="'"||A[0]==='"'){let Q=A.slice(1,-1).replace(/\\(.)/g,"$1");return()=>Q}return(Q)=>Q[A]}}function mL(A){let Q=/^\/((?:\\.|[^/])*)\/([a-z]*)$/.exec(A);if(!Q)throw Error(`Bad regex ${A}`);return new RegExp(Q[1],Q[2])}function pL(A){return!(A===void 0||A===null||A===!1||A===""||A===0)}function cL(A,Q,B){switch(A){case"==":return Q==B;case"!=":return Q!=B;case">":return Q>B;case"<":return Q<B;case">=":return Q>=B;case"<=":return Q<=B}return!1}class ZC{constructor(A={}){this.state={platform:SE(),isMac:/mac/i.test(SE()),...A},this.cell=f(this.state)}get(A){return this.state[A]}snapshot(){return this.state}observe(){return this.cell}set(A,Q){if(this.state[A]===Q)return;this.state={...this.state,[A]:Q},this.cell.setValue(this.state)}setMany(A){let Q=!1,B={...this.state};for(let[C,E]of Object.entries(A))if(B[C]!==E)B[C]=E,Q=!0;if(Q)this.state=B,this.cell.setValue(B)}remove(A){if(!(A in this.state))return;let{[A]:Q,...B}=this.state;this.state=B,this.cell.setValue(B)}evaluate(A){return OE(A,this.state)}scopedFor(A){let Q=`${A}.`;return{set:(B,C)=>this.set(Q+B,C),remove:(B)=>this.remove(Q+B)}}}function SE(){return typeof navigator<"u"?navigator.platform||navigator.userAgent||"":""}class UC{constructor(A,Q,B){this.contributions=A,this.context=Q,this.notifications=B,this.handlers=new Map}register(A,Q){let B=typeof A==="string"?{id:A,handler:Q}:A;if(B.handler)this.handlers.set(B.id,B.handler);let C=this.contributions.register(B.id,{type:"command",title:B.title??B.id,category:B.category,icon:B.icon,when:B.when,palette:B.palette??!0,pluginId:B.pluginId,offline:B.offline});return()=>{this.handlers.delete(B.id),C()}}has(A){return this.handlers.has(A)}isEnabled(A){let Q=this.contributions.get(A);if(Q?.when&&!this.context.evaluate(Q.when))return!1;return this.isAvailable(Q)}isAvailable(A){if(!A)return!0;return this.availability?this.availability(A):!0}async execute(A,...Q){let B=this.handlers.get(A);if(!B){this.notifications.error(`Command not found: ${A}`);return}let C=this.contributions.get(A);if(!this.isAvailable(C)){this.notifications.warn(`“${C?.title||A}” isn’t available${this.availability?" offline":""} right now.`);return}if(!this.isEnabled(A))return;try{return await B(...Q)}catch(E){throw console.error(`Command ${A} failed`,E),this.notifications.error(E?.message||`Command failed: ${A}`),E}}paletteCommands(){return this.contributions.ofType("command").filter((A)=>A.palette!==!1&&(!A.when||this.context.evaluate(A.when))).sort((A,Q)=>(A.category||"").localeCompare(Q.category||"")||A.title.localeCompare(Q.title))}}function WC(A){let Q=A.trim().toLowerCase().split("+").map((K)=>K.trim()),B=new Set,C="";for(let K of Q)if(["ctrl","control"].includes(K))B.add("ctrl");else if(["cmd","meta","super","win"].includes(K))B.add("meta");else if(K==="alt"||K==="option")B.add("alt");else if(K==="shift")B.add("shift");else if(["ctrlcmd","mod"].includes(K))B.add(wE()?"meta":"ctrl");else C=K;return[...["ctrl","meta","alt","shift"].filter((K)=>B.has(K)),C].filter(Boolean).join("+")}function RC(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let B=A.key.toLowerCase();return B={" ":"space",escape:"escape",enter:"enter",arrowup:"up",arrowdown:"down",arrowleft:"left",arrowright:"right"}[B]||B,[...Q.filter((E)=>B!==E),B].join("+")}class yQ{constructor(A,Q,B,C=null){this.contributions=A,this.commands=Q,this.context=B,this.settings=C,this.chordPrefix=null,this.chordTimer=null,this._onKeyDown=this.#B.bind(this)}install(A=window){return A.addEventListener("keydown",this._onKeyDown),()=>A.removeEventListener("keydown",this._onKeyDown)}overrides(){return this.settings?.get("keybindings.overrides")||{}}static bindingId(A){return`${A.command}\x00${WC(A.defaultKey||A.key)}`}rebind(A,Q){if(!this.settings)return;let B=typeof A==="string"?this.#A(A):yQ.bindingId(A);if(!B)return;let C={...this.overrides()};if(Q)C[B]=Q;else delete C[B];this.settings.set("keybindings.overrides",C)}#A(A){let Q=this.contributions.keybindings().find((B)=>B?.command===A&&B.key);return Q?yQ.bindingId({...Q,defaultKey:Q.key}):null}resolved(){let A=this.overrides();return this.contributions.keybindings().filter((Q)=>Q?.key&&Q.command).map((Q)=>{let B=WC(Q.key),C=yQ.bindingId({command:Q.command,defaultKey:B});return{...Q,defaultKey:B,bindingId:C,key:WC(A[C]||Q.key)}})}#Q(A){let Q=this.context.snapshot(),B=this.resolved();for(let C=B.length-1;C>=0;C--){let E=B[C];if(E.key!==A)continue;if(E.when&&!this.context.evaluate(E.when))continue;return E}return null}#B(A){if(A.defaultPrevented)return;let Q=RC(A),B=A.ctrlKey||A.metaKey||A.altKey;if(lL(A.target)&&!B&&A.key!=="Escape"){this.#C();return}let E=this.chordPrefix?`${this.chordPrefix} ${Q}`:Q,K=this.#Q(E);if(K){A.preventDefault(),this.#C(),this.commands.execute(K.command,...K.args||[]);return}if(!this.chordPrefix&&this.resolved().some((J)=>J.key.startsWith(Q+" "))){A.preventDefault(),this.chordPrefix=Q,this.chordTimer=setTimeout(()=>this.#C(),1500);return}this.#C()}#C(){if(this.chordPrefix=null,this.chordTimer)clearTimeout(this.chordTimer);this.chordTimer=null}labelFor(A){let Q=this.resolved().find((B)=>B.command===A);return Q?aQ(Q.key):null}}function lL(A){if(!A)return!1;let Q=A.tagName;return Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||A.isContentEditable}function wE(){return typeof navigator<"u"&&/mac/i.test(navigator.platform||navigator.userAgent||"")}function aQ(A){let Q=wE(),B=Q?{ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",enter:"↵",escape:"esc",up:"↑",down:"↓",left:"←",right:"→",space:"␣"}:{ctrl:"Ctrl",meta:"Win",alt:"Alt",shift:"Shift",enter:"Enter",escape:"Esc",up:"↑",down:"↓",left:"←",right:"→",space:"Space"};return A.split(" ").map((C)=>C.split("+").map((E)=>B[E]||(E.length===1?E.toUpperCase():E[0].toUpperCase()+E.slice(1))).join(Q?"":"+")).join(" ")}var _E="trove.settings";class FC{constructor(){this.schema=new Map,this.values=dL(),this.cell=f(this.effective())}register(A){for(let Q of[].concat(A))this.schema.set(Q.key,Q);return this.cell.setValue(this.effective()),()=>{for(let Q of[].concat(A))this.schema.delete(Q.key);this.cell.setValue(this.effective())}}get(A){if(A in this.values)return this.values[A];return this.schema.get(A)?.default}set(A,Q){let B=this.schema.get(A);if(B&&Q===B.default)delete this.values[A];else this.values[A]=Q;TE(this.values),this.cell.setValue(this.effective())}reset(A){delete this.values[A],TE(this.values),this.cell.setValue(this.effective())}effective(){let A={};for(let[Q,B]of this.schema)A[Q]=Q in this.values?this.values[Q]:B.default;for(let[Q,B]of Object.entries(this.values))if(!(Q in A))A[Q]=B;return A}observe(){return this.cell}grouped(){let A=new Map;for(let Q of[...this.schema.values()].sort((B,C)=>(B.order??0)-(C.order??0))){if(Q.hidden)continue;let B=Q.category||"General";if(!A.has(B))A.set(B,[]);A.get(B).push({...Q,value:this.get(Q.key)})}return[...A.entries()].map(([Q,B])=>({category:Q,items:B}))}scopedFor(A){let Q=`${A}.`;return{register:(B)=>this.register([].concat(B).map((C)=>({...C,key:Q+C.key,category:C.category||A}))),get:(B)=>this.get(Q+B),set:(B,C)=>this.set(Q+B,C)}}}function dL(){try{return JSON.parse(localStorage.getItem(_E))||{}}catch{return{}}}function TE(A){try{localStorage.setItem(_E,JSON.stringify(A))}catch{}}var nL=0;class MC{constructor(){this.items=[],this.cell=f([])}observe(){return this.cell}#A(A,Q,B={}){let C={id:++nL,level:A,message:Q,actions:B.actions||null,createdAt:Date.now(),sticky:B.sticky||A==="error"};if(this.items=[...this.items,C],this.cell.setValue(this.items),!C.sticky)setTimeout(()=>this.dismiss(C.id),B.timeout??4000);return C.id}info(A,Q){return this.#A("info",A,Q)}success(A,Q){return this.#A("success",A,Q)}warn(A,Q){return this.#A("warn",A,Q)}error(A,Q){return this.#A("error",A,Q)}update(A,Q){this.items=this.items.map((B)=>B.id===A?{...B,...Q}:B),this.cell.setValue(this.items)}dismiss(A){this.items=this.items.filter((Q)=>Q.id!==A),this.cell.setValue(this.items)}}var oL={retries:4,minDelayMs:250,maxDelayMs:8000,factor:2,jitter:!0};function aL(A,Q){return new Promise((B,C)=>{if(Q?.aborted)return C(P.aborted());let E=(Y)=>(I)=>{clearTimeout(K),Q?.removeEventListener("abort",J),Y(I)},K=setTimeout(()=>E(B)(),A),J=()=>E(C)(P.aborted());Q?.addEventListener("abort",J,{once:!0})})}async function sQ(A,Q={}){let B={...oL,...Q},C=B.shouldRetry??UE,E=0;for(;;){if(B.signal?.aborted)throw P.aborted();try{return await A(E)}catch(K){let J=oQ(K);if(!(E<B.retries&&C(J)&&J.code!=="aborted"))throw J;let I=Math.min(B.maxDelayMs,B.minDelayMs*B.factor**E),D=B.jitter?Math.random()*I:I;B.onRetry?.({attempt:E+1,delayMs:D,error:J}),await aL(D,B.signal),E++}}}class VC{constructor({baseUrl:A="",fetch:Q=globalThis.fetch.bind(globalThis),token:B=null}={}){this.baseUrl=A.replace(/\/$/,""),this._fetch=Q,this._token=B}token(){return(typeof this._token==="function"?this._token():this._token)||null}authHeaders(){let A=this.token();return A?{authorization:`Bearer ${A}`}:{}}async request(A,Q,{body:B,query:C,signal:E,raw:K}={}){let J=this.baseUrl+Q+(C?"?"+new URLSearchParams(C):"");return sQ(async()=>{let Y=await this._fetch(J,{method:A,headers:{...this.authHeaders(),...B?{"content-type":"application/json"}:{}},body:B?JSON.stringify(B):void 0,signal:E});if(Y.status===429||Y.status>=500){if(!K){let L;try{let G=await Y.text();L=(G?JSON.parse(G):null)?.error}catch{}if(L&&L.retryable===!1)throw new P(L.code,L.message,{retryable:!1,details:L.details});throw P.transient(L?.message||`Server ${Y.status}`)}throw P.transient(`Server ${Y.status}`)}if(K)return Y;let I=await Y.text(),D=I?JSON.parse(I):null;if(!Y.ok){let L=D?.error||{code:"internal",message:`Request failed (${Y.status})`};throw new P(L.code,L.message,{retryable:L.retryable,details:L.details})}return D},{signal:E,retries:3})}capabilities(){return this.request("GET","/api/capabilities")}async reachable(A=4000){try{let Q=AbortSignal.timeout?AbortSignal.timeout(A):void 0;return(await this._fetch(this.baseUrl+"/api/capabilities",{method:"GET",signal:Q,headers:this.authHeaders()})).ok}catch{return!1}}list(A={}){return this.request("GET","/api/items",{query:A})}stat(A,Q={}){let B=String(A).startsWith("trove:")?"uri":"id";return this.request("GET","/api/items/resolve",{query:{[B]:A,...Q}})}backlinks(A,Q={}){return this.request("GET","/api/items/backlinks",{query:{id:A,...Q}})}rename(A,Q){return this.request("POST","/api/items/rename",{body:{id:A,newName:Q}})}remove(A){return this.request("POST","/api/items/delete",{body:{id:A}})}trash(A){return this.request("GET","/api/trash",{query:A?{collection:A}:{}})}restore(A){return this.request("POST","/api/trash/restore",{body:{id:A}})}purgeTrash({id:A,collection:Q}={}){return this.request("POST","/api/trash/purge",{body:A?{id:A}:{collection:Q}})}search(A,Q={}){return this.request("GET","/api/search",{query:{q:A,...Q}})}query(A,Q={}){return this.request("POST","/api/query",{body:{q:A,...Q}})}tagSearch(A,Q,B={}){return this.request("POST","/api/tags/search",{body:{filters:A,q:Q,...B}})}indexers(){return this.request("GET","/api/indexers")}tasks(){return this.request("GET","/api/tasks")}cancelTask(A){return this.request("POST",`/api/tasks/${encodeURIComponent(A)}/cancel`)}dismissTask(A){return this.request("DELETE",`/api/tasks/${encodeURIComponent(A)}`)}issues(){return this.request("GET","/api/issues")}retryIssue(A){return this.request("POST",`/api/issues/${encodeURIComponent(A)}/retry`)}dismissIssue(A){return this.request("DELETE",`/api/issues/${encodeURIComponent(A)}`)}reindex(){return this.request("POST","/api/reindex")}scanCollection(A){return this.request("POST",`/api/collections/${encodeURIComponent(A)}/scan`)}async installPlugin(A,Q){let B=Q&&Q.length?"?grants="+encodeURIComponent(Q.join(",")):"",C=await this._fetch(this.baseUrl+"/api/plugins/install"+B,{method:"POST",body:A,headers:this.authHeaders()}),E=await C.json().catch(()=>null);if(!C.ok){let K=E?.error||{code:"internal",message:`Install failed (${C.status})`};throw new P(K.code,K.message,{details:K.details})}return E.install}installedPlugins(){return this.request("GET","/api/plugins/installed")}async pluginPackage(A){let Q=await this._fetch(`${this.baseUrl}/api/plugins/${encodeURIComponent(A)}/package`,{headers:this.authHeaders()});if(!Q.ok)throw new P("not_found",`Package for "${A}" not found`);return new Uint8Array(await Q.arrayBuffer())}uninstallPluginServer(A){return this.request("DELETE",`/api/plugins/${encodeURIComponent(A)}/install`)}pushIndex(A,Q,B){return this.request("POST",`/api/index/${encodeURIComponent(A)}`,{body:{nodeId:Q,...B}})}me(){return this.request("GET","/api/me")}collections(){return this.request("GET","/api/collections")}createCollection(A){return this.request("POST","/api/collections",{body:A})}sidecar(A){return this.request("GET",`/api/items/${encodeURIComponent(A)}/sidecar`)}addComment(A,{body:Q,parentId:B,mentions:C}={}){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments`,{body:{body:Q,parentId:B,mentions:C}})}editComment(A,Q,B){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}/edit`,{body:{body:B}})}deleteComment(A,Q){return this.request("DELETE",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}`)}reactComment(A,Q,B,C){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}/react`,{body:{emoji:B,on:C}})}setTag(A,Q,B){return this.request("POST",`/api/items/${encodeURIComponent(A)}/tags`,{body:{name:Q,value:B}})}removeTag(A,Q){return this.request("DELETE",`/api/items/${encodeURIComponent(A)}/tags/${encodeURIComponent(Q)}`)}notifications(){return this.request("GET","/api/notifications")}markNotificationsRead(A){return this.request("POST","/api/notifications/read",{body:{ids:A}})}vapidKey(){return this.request("GET","/api/push/vapid")}subscribePush(A){return this.request("POST","/api/push/subscribe",{body:{subscription:A}})}downloadUrl(A,{attachment:Q}={}){return`${this.baseUrl}/api/items/download?id=${encodeURIComponent(A)}${Q?"&disposition=attachment":""}`}mintUrls(A,Q="media"){return this.request("POST","/api/items/urls",{body:{ids:A,op:Q}})}async download(A,Q,{attachment:B=!0}={}){let C=this.downloadUrl(A,{attachment:B});if(!this.token())return{url:C,streamed:!0};let E=await this._fetch(C,{headers:this.authHeaders()});if(!E.ok)throw new P("internal",`Download failed (${E.status})`);return{url:URL.createObjectURL(await E.blob()),streamed:!1,revoke:!0}}async readBytes(A,{signal:Q}={}){let B=await this._fetch(this.downloadUrl(A),{signal:Q,headers:this.authHeaders()});if(!B.ok)throw new P("internal",`Download failed (${B.status})`);return new Uint8Array(await B.arrayBuffer())}async readText(A,Q){return new TextDecoder().decode(await this.readBytes(A,Q))}async readTextCapped(A,{maxBytes:Q=524288,size:B=null,signal:C}={}){let E=B==null||B>Q,K=await this._fetch(this.downloadUrl(A),{signal:C,headers:{...this.authHeaders(),...E?{range:`bytes=0-${Q-1}`}:{}}});if(K.status===416)return{text:"",truncated:!1,total:0};if(!K.ok&&K.status!==206)throw new P("internal",`Download failed (${K.status})`);let J=new Uint8Array(await K.arrayBuffer()),Y=Number(/\/(\d+)$/.exec(K.headers.get("content-range")||"")?.[1])||null,I=J.length>=Q&&(Y==null||Y>J.length),D=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(I){let L=D.lastIndexOf(`
|
|
4
|
+
`);if(L>0)D=D.slice(0,L)}return{text:D,truncated:I,total:Y}}async upload(A,Q){let B=Q.name||A.name||"untitled",C=A.size,E=await this.request("POST","/api/uploads",{body:{collection:Q.collection,name:B,size:C,contentType:A.type||void 0},signal:Q.signal});if(E.uploadId)Q.onStart?.(E.uploadId);let K=new kE(C,Q.onProgress),J=E.transfer||{},Y=E.endpoints?.complete||`/api/uploads/${E.uploadId}/complete`;if(E.strategy==="single")return await zB(J.url||E.url,A,{headers:J.requiredHeaders,signal:Q.signal,onProgress:(y)=>K.set("single",y)}),(await this.request("POST",Y,{body:{},signal:Q.signal})).node;if(E.strategy==="direct-single")return await zB(this.baseUrl+this.#A(E,1),A,{headers:{...this.authHeaders(),...J.authHeaders},signal:Q.signal,onProgress:(y)=>K.set(1,y)}),(await this.request("POST",Y,{body:{},signal:Q.signal})).node;let I=E.partSize,D=E.partCount??Math.ceil(C/I),L=new Set;try{let z=E.endpoints?.status||`/api/uploads/${E.uploadId}/status`,y=await this.request("GET",z,{signal:Q.signal});L=new Set(y.received||[])}catch{}let G=[],X=[];for(let z=1;z<=D;z++){let y=(z-1)*I,p=A.slice(y,Math.min(y+I,C));X.push({n:z,blob:p})}let Z=Array(D),R=Math.min(Q.concurrency??4,X.length),F=0,V=new AbortController,g=()=>V.abort();if(Q.signal)if(Q.signal.aborted)V.abort();else Q.signal.addEventListener("abort",g,{once:!0});let b=async()=>{while(F<X.length){if(V.signal.aborted)return;let{n:z,blob:y}=X[F++];if(L.has(z)){K.set(z,y.size);continue}let p=await sQ(()=>this.#Q(E,z,y,{signal:V.signal,onProgress:(S)=>K.set(z,S)}),{signal:V.signal,retries:4});Z[z-1]={partNumber:z,etag:p}}};try{await Promise.all(Array.from({length:R},b))}catch(z){throw V.abort(),z}finally{Q.signal?.removeEventListener("abort",g)}let M=Z.filter(Boolean);return(await this.request("POST",Y,{body:{parts:M},signal:Q.signal})).node}#A(A,Q){return(A.transfer?.partUrl||`/api/uploads/${A.uploadId}/parts/{partNumber}`).replace("{partNumber}",String(Q))}async#Q(A,Q,B,{signal:C,onProgress:E}){let K=A.transfer||{};if(A.strategy==="presign"){let I=(K.parts||A.parts)?.find((X)=>X.partNumber===Q)?.url;if(!I){let X=A.endpoints?.sign||`/api/uploads/${A.uploadId}/parts/{partNumber}/sign`;I=(await this.request("POST",X.replace("{partNumber}",String(Q)),{signal:C})).url}let L=(await zB(I,B,{signal:C,onProgress:E,wantEtag:!0})).etag,G=A.endpoints?.report||`/api/uploads/${A.uploadId}/parts/{partNumber}/report`;return await this.request("POST",G.replace("{partNumber}",String(Q)),{body:{etag:L},signal:C}),L}return(await zB(this.baseUrl+this.#A(A,Q),B,{headers:{...this.authHeaders(),...K.authHeaders},signal:C,onProgress:E,wantJson:!0})).json?.etag}async abortUpload(A){return this.request("DELETE",`/api/uploads/${A}`)}}class kE{constructor(A,Q){this.total=A,this.cb=Q,this.parts=new Map}set(A,Q){let B=this.parts.get(A)||0;if(Q<B)return;if(this.parts.set(A,Q),!this.cb)return;let C=0;for(let K of this.parts.values())C+=K;let E=Math.min(C,this.total);this.cb({loaded:E,total:this.total,ratio:this.total?E/this.total:1})}}function zB(A,Q,{signal:B,onProgress:C,wantEtag:E,wantJson:K,headers:J}={}){return new Promise((Y,I)=>{let D=new XMLHttpRequest;D.open("PUT",A,!0);for(let[L,G]of Object.entries(J||{}))try{D.setRequestHeader(L,G)}catch{}if(B){if(B.aborted)return D.abort(),I(P.aborted());B.addEventListener("abort",()=>D.abort(),{once:!0})}D.upload.onprogress=(L)=>C?.(L.loaded),D.onload=()=>{if(D.status>=200&&D.status<300){let L={status:D.status};if(E)L.etag=D.getResponseHeader("ETag")||D.getResponseHeader("etag");if(K)try{L.json=JSON.parse(D.responseText)}catch{}Y(L)}else if(D.status===429||D.status>=500)I(P.transient(`Upload part failed (${D.status})`));else I(new P("internal",`Upload failed (${D.status})`))},D.onerror=()=>I(P.transient("Network error during upload")),D.onabort=()=>I(P.aborted()),D.send(Q)})}var s=Uint8Array,PA=Uint16Array,kC=Int32Array,OB=new s([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),jB=new s([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),OC=new s([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),fE=function(A,Q){var B=new PA(31);for(var C=0;C<31;++C)B[C]=Q+=1<<A[C-1];var E=new kC(B[30]);for(var C=1;C<30;++C)for(var K=B[C];K<B[C+1];++K)E[K]=K-B[C]<<5|C;return{b:B,r:E}},uE=fE(OB,2),mE=uE.b,jC=uE.r;mE[28]=258,jC[258]=28;var pE=fE(jB,0),sL=pE.b,xE=pE.r,SC=new PA(32768);for(h=0;h<32768;++h)hA=(h&43690)>>1|(h&21845)<<1,hA=(hA&52428)>>2|(hA&13107)<<2,hA=(hA&61680)>>4|(hA&3855)<<4,SC[h]=((hA&65280)>>8|(hA&255)<<8)>>1;var hA,h,bA=function(A,Q,B){var C=A.length,E=0,K=new PA(Q);for(;E<C;++E)if(A[E])++K[A[E]-1];var J=new PA(Q);for(E=1;E<Q;++E)J[E]=J[E-1]+K[E-1]<<1;var Y;if(B){Y=new PA(1<<Q);var I=15-Q;for(E=0;E<C;++E)if(A[E]){var D=E<<4|A[E],L=Q-A[E],G=J[A[E]-1]++<<L;for(var X=G|(1<<L)-1;G<=X;++G)Y[SC[G]>>I]=D}}else{Y=new PA(C);for(E=0;E<C;++E)if(A[E])Y[E]=SC[J[A[E]-1]++]>>15-A[E]}return Y},BQ=new s(288);for(h=0;h<144;++h)BQ[h]=8;var h;for(h=144;h<256;++h)BQ[h]=9;var h;for(h=256;h<280;++h)BQ[h]=7;var h;for(h=280;h<288;++h)BQ[h]=8;var h,tQ=new s(32);for(h=0;h<32;++h)tQ[h]=5;var h,iL=bA(BQ,9,0),rL=bA(BQ,9,1),tL=bA(tQ,5,0),eL=bA(tQ,5,1),PC=function(A){var Q=A[0];for(var B=1;B<A.length;++B)if(A[B]>Q)Q=A[B];return Q},kA=function(A,Q,B){var C=Q/8|0;return(A[C]|A[C+1]<<8)>>(Q&7)&B},NC=function(A,Q){var B=Q/8|0;return(A[B]|A[B+1]<<8|A[B+2]<<16)>>(Q&7)},xC=function(A){return(A+7)/8|0},eQ=function(A,Q,B){if(Q==null||Q<0)Q=0;if(B==null||B>A.length)B=A.length;return new s(A.subarray(Q,B))};var A8=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],HA=function(A,Q,B){var C=Error(Q||A8[A]);if(C.code=A,Error.captureStackTrace)Error.captureStackTrace(C,HA);if(!B)throw C;return C},Q8=function(A,Q,B,C){var E=A.length,K=C?C.length:0;if(!E||Q.f&&!Q.l)return B||new s(0);var J=!B,Y=J||Q.i!=2,I=Q.i;if(J)B=new s(E*3);var D=function(rA){var tA=B.length;if(rA>tA){var eA=new s(Math.max(tA*2,rA));eA.set(B),B=eA}},L=Q.f||0,G=Q.p||0,X=Q.b||0,Z=Q.l,R=Q.d,F=Q.m,V=Q.n,g=E*8;do{if(!Z){L=kA(A,G,1);var b=kA(A,G+1,3);if(G+=3,!b){var M=xC(G)+4,j=A[M-4]|A[M-3]<<8,z=M+j;if(z>E){if(I)HA(0);break}if(Y)D(X+j);B.set(A.subarray(M,z),X),Q.b=X+=j,Q.p=G=z*8,Q.f=L;continue}else if(b==1)Z=rL,R=eL,F=9,V=5;else if(b==2){var y=kA(A,G,31)+257,p=kA(A,G+10,15)+4,S=y+kA(A,G+5,31)+1;G+=14;var _=new s(S),r=new s(19);for(var t=0;t<p;++t)r[OC[t]]=kA(A,G+t*3,7);G+=p*3;var a=PC(r),gA=(1<<a)-1,IA=bA(r,a,1);for(var t=0;t<S;){var LA=IA[kA(A,G,gA)];G+=LA&15;var M=LA>>4;if(M<16)_[t++]=M;else{var e=0,o=0;if(M==16)o=3+kA(A,G,3),G+=2,e=_[t-1];else if(M==17)o=3+kA(A,G,7),G+=3;else if(M==18)o=11+kA(A,G,127),G+=7;while(o--)_[t++]=e}}var JA=_.subarray(0,y),AA=_.subarray(y);F=PC(JA),V=PC(AA),Z=bA(JA,F,1),R=bA(AA,V,1)}else HA(1);if(G>g){if(I)HA(0);break}}if(Y)D(X+131072);var YQ=(1<<F)-1,ZA=(1<<V)-1,TA=G;for(;;TA=G){var e=Z[NC(A,G)&YQ],UA=e>>4;if(G+=e&15,G>g){if(I)HA(0);break}if(!e)HA(2);if(UA<256)B[X++]=UA;else if(UA==256){TA=G,Z=null;break}else{var DA=UA-254;if(UA>264){var t=UA-257,n=OB[t];DA=kA(A,G,(1<<n)-1)+mE[t],G+=n}var qA=R[NC(A,G)&ZA],aA=qA>>4;if(!qA)HA(3);G+=qA&15;var AA=sL[aA];if(aA>3){var n=jB[aA];AA+=NC(A,G)&(1<<n)-1,G+=n}if(G>g){if(I)HA(0);break}if(Y)D(X+131072);var sA=X+DA;if(X<AA){var jQ=K-AA,iA=Math.min(AA,sA);if(jQ+X<0)HA(3);for(;X<iA;++X)B[X]=C[jQ+X]}for(;X<sA;++X)B[X]=B[X-AA]}}if(Q.l=Z,Q.p=TA,Q.b=X,Q.f=L,Z)L=1,Q.m=F,Q.d=R,Q.n=V}while(!L);return X!=B.length&&J?eQ(B,0,X):B.subarray(0,X)},lA=function(A,Q,B){B<<=Q&7;var C=Q/8|0;A[C]|=B,A[C+1]|=B>>8},iQ=function(A,Q,B){B<<=Q&7;var C=Q/8|0;A[C]|=B,A[C+1]|=B>>8,A[C+2]|=B>>16},qC=function(A,Q){var B=[];for(var C=0;C<A.length;++C)if(A[C])B.push({s:C,f:A[C]});var E=B.length,K=B.slice();if(!E)return{t:lE,l:0};if(E==1){var J=new s(B[0].s+1);return J[B[0].s]=1,{t:J,l:1}}B.sort(function(z,y){return z.f-y.f}),B.push({s:-1,f:25001});var Y=B[0],I=B[1],D=0,L=1,G=2;B[0]={s:-1,f:Y.f+I.f,l:Y,r:I};while(L!=E-1)Y=B[B[D].f<B[G].f?D++:G++],I=B[D!=L&&B[D].f<B[G].f?D++:G++],B[L++]={s:-1,f:Y.f+I.f,l:Y,r:I};var X=K[0].s;for(var C=1;C<E;++C)if(K[C].s>X)X=K[C].s;var Z=new PA(X+1),R=wC(B[L-1],Z,0);if(R>Q){var C=0,F=0,V=R-Q,g=1<<V;K.sort(function(y,p){return Z[p.s]-Z[y.s]||y.f-p.f});for(;C<E;++C){var b=K[C].s;if(Z[b]>Q)F+=g-(1<<R-Z[b]),Z[b]=Q;else break}F>>=V;while(F>0){var M=K[C].s;if(Z[M]<Q)F-=1<<Q-Z[M]++-1;else++C}for(;C>=0&&F;--C){var j=K[C].s;if(Z[j]==Q)--Z[j],++F}R=Q}return{t:new s(Z),l:R}},wC=function(A,Q,B){return A.s==-1?Math.max(wC(A.l,Q,B+1),wC(A.r,Q,B+1)):Q[A.s]=B},gE=function(A){var Q=A.length;while(Q&&!A[--Q]);var B=new PA(++Q),C=0,E=A[0],K=1,J=function(I){B[C++]=I};for(var Y=1;Y<=Q;++Y)if(A[Y]==E&&Y!=Q)++K;else{if(!E&&K>2){for(;K>138;K-=138)J(32754);if(K>2)J(K>10?K-11<<5|28690:K-3<<5|12305),K=0}else if(K>3){J(E),--K;for(;K>6;K-=6)J(8304);if(K>2)J(K-3<<5|8208),K=0}while(K--)J(E);K=1,E=A[Y]}return{c:B.subarray(0,C),n:Q}},rQ=function(A,Q){var B=0;for(var C=0;C<Q.length;++C)B+=A[C]*Q[C];return B},cE=function(A,Q,B){var C=B.length,E=xC(Q+2);A[E]=C&255,A[E+1]=C>>8,A[E+2]=A[E]^255,A[E+3]=A[E+1]^255;for(var K=0;K<C;++K)A[E+K+4]=B[K];return(E+4+C)*8},yE=function(A,Q,B,C,E,K,J,Y,I,D,L){lA(Q,L++,B),++E[256];var G=qC(E,15),X=G.t,Z=G.l,R=qC(K,15),F=R.t,V=R.l,g=gE(X),b=g.c,M=g.n,j=gE(F),z=j.c,y=j.n,p=new PA(19);for(var S=0;S<b.length;++S)++p[b[S]&31];for(var S=0;S<z.length;++S)++p[z[S]&31];var _=qC(p,7),r=_.t,t=_.l,a=19;for(;a>4&&!r[OC[a-1]];--a);var gA=D+5<<3,IA=rQ(E,BQ)+rQ(K,tQ)+J,LA=rQ(E,X)+rQ(K,F)+J+14+3*a+rQ(p,r)+2*p[16]+3*p[17]+7*p[18];if(I>=0&&gA<=IA&&gA<=LA)return cE(Q,L,A.subarray(I,I+D));var e,o,JA,AA;if(lA(Q,L,1+(LA<IA)),L+=2,LA<IA){e=bA(X,Z,0),o=X,JA=bA(F,V,0),AA=F;var YQ=bA(r,t,0);lA(Q,L,M-257),lA(Q,L+5,y-1),lA(Q,L+10,a-4),L+=14;for(var S=0;S<a;++S)lA(Q,L+3*S,r[OC[S]]);L+=3*a;var ZA=[b,z];for(var TA=0;TA<2;++TA){var UA=ZA[TA];for(var S=0;S<UA.length;++S){var DA=UA[S]&31;if(lA(Q,L,YQ[DA]),L+=r[DA],DA>15)lA(Q,L,UA[S]>>5&127),L+=UA[S]>>12}}}else e=iL,o=BQ,JA=tL,AA=tQ;for(var S=0;S<Y;++S){var n=C[S];if(n>255){var DA=n>>18&31;if(iQ(Q,L,e[DA+257]),L+=o[DA+257],DA>7)lA(Q,L,n>>23&31),L+=OB[DA];var qA=n&31;if(iQ(Q,L,JA[qA]),L+=AA[qA],qA>3)iQ(Q,L,n>>5&8191),L+=jB[qA]}else iQ(Q,L,e[n]),L+=o[n]}return iQ(Q,L,e[256]),L+o[256]},B8=new kC([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lE=new s(0),C8=function(A,Q,B,C,E,K){var J=K.z||A.length,Y=new s(C+J+5*(1+Math.ceil(J/7000))+E),I=Y.subarray(C,Y.length-E),D=K.l,L=(K.r||0)&7;if(Q){if(L)I[0]=K.r>>3;var G=B8[Q-1],X=G>>13,Z=G&8191,R=(1<<B)-1,F=K.p||new PA(32768),V=K.h||new PA(R+1),g=Math.ceil(B/3),b=2*g,M=function(pQ){return(A[pQ]^A[pQ+1]<<g^A[pQ+2]<<b)&R},j=new kC(25000),z=new PA(288),y=new PA(32),p=0,S=0,_=K.i||0,r=0,t=K.w||0,a=0;for(;_+2<J;++_){var gA=M(_),IA=_&32767,LA=V[gA];if(F[IA]=LA,V[gA]=IA,t<=_){var e=J-_;if((p>7000||r>24576)&&(e>423||!D)){L=yE(A,I,0,j,z,y,S,r,a,_-a,L),r=p=S=0,a=_;for(var o=0;o<286;++o)z[o]=0;for(var o=0;o<30;++o)y[o]=0}var JA=2,AA=0,YQ=Z,ZA=IA-LA&32767;if(e>2&&gA==M(_-ZA)){var TA=Math.min(X,e)-1,UA=Math.min(32767,_),DA=Math.min(258,e);while(ZA<=UA&&--YQ&&IA!=LA){if(A[_+JA]==A[_+JA-ZA]){var n=0;for(;n<DA&&A[_+n]==A[_+n-ZA];++n);if(n>JA){if(JA=n,AA=ZA,n>TA)break;var qA=Math.min(ZA,n-2),aA=0;for(var o=0;o<qA;++o){var sA=_-ZA+o&32767,jQ=F[sA],iA=sA-jQ&32767;if(iA>aA)aA=iA,LA=sA}}}IA=LA,LA=F[IA],ZA+=IA-LA&32767}}if(AA){j[r++]=268435456|jC[JA]<<18|xE[AA];var rA=jC[JA]&31,tA=xE[AA]&31;S+=OB[rA]+jB[tA],++z[257+rA],++y[tA],t=_+JA,++p}else j[r++]=A[_],++z[A[_]]}}for(_=Math.max(_,t);_<J;++_)j[r++]=A[_],++z[A[_]];if(L=yE(A,I,D,j,z,y,S,r,a,_-a,L),!D)K.r=L&7|I[L/8|0]<<3,L-=7,K.h=V,K.p=F,K.i=_,K.w=t}else{for(var _=K.w||0;_<J+D;_+=65535){var eA=_+65535;if(eA>=J)I[L/8|0]=D,eA=J;L=cE(I,L+1,A.subarray(_,eA))}K.i=J}return eQ(Y,0,C+xC(L)+E)},E8=function(){var A=new Int32Array(256);for(var Q=0;Q<256;++Q){var B=Q,C=9;while(--C)B=(B&1&&-306674912)^B>>>1;A[Q]=B}return A}(),K8=function(){var A=-1;return{p:function(Q){var B=A;for(var C=0;C<Q.length;++C)B=E8[B&255^Q[C]]^B>>>8;A=B},d:function(){return~A}}};var J8=function(A,Q,B,C,E){if(!E){if(E={l:1},Q.dictionary){var K=Q.dictionary.subarray(-32768),J=new s(K.length+A.length);J.set(K),J.set(A,K.length),A=J,E.w=K.length}}return C8(A,Q.level==null?6:Q.level,Q.mem==null?E.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+Q.mem,B,C,E)},dE=function(A,Q){var B={};for(var C in A)B[C]=A[C];for(var C in Q)B[C]=Q[C];return B};var vA=function(A,Q){return A[Q]|A[Q+1]<<8},zA=function(A,Q){return(A[Q]|A[Q+1]<<8|A[Q+2]<<16|A[Q+3]<<24)>>>0},zC=function(A,Q){return zA(A,Q)+zA(A,Q+4)*4294967296},YA=function(A,Q,B){for(;B;++Q)A[Q]=B,B>>>=8};function Y8(A,Q){return J8(A,Q||{},0,0)}function I8(A,Q){return Q8(A,{i:2},Q&&Q.out,Q&&Q.dictionary)}var nE=function(A,Q,B,C){for(var E in A){var K=A[E],J=Q+E,Y=C;if(Array.isArray(K))Y=dE(C,K[1]),K=K[0];if(ArrayBuffer.isView(K))B[J]=[K,Y];else B[J+="/"]=[new s(0),Y],nE(K,J,B,C)}},hE=typeof TextEncoder<"u"&&new TextEncoder,TC=typeof TextDecoder<"u"&&new TextDecoder,L8=0;try{TC.decode(lE,{stream:!0}),L8=1}catch(A){}var D8=function(A){for(var Q="",B=0;;){var C=A[B++],E=(C>127)+(C>223)+(C>239);if(B+E>A.length)return{s:Q,r:eQ(A,B-1)};if(!E)Q+=String.fromCharCode(C);else if(E==3)C=((C&15)<<18|(A[B++]&63)<<12|(A[B++]&63)<<6|A[B++]&63)-65536,Q+=String.fromCharCode(55296|C>>10,56320|C&1023);else if(E&1)Q+=String.fromCharCode((C&31)<<6|A[B++]&63);else Q+=String.fromCharCode((C&15)<<12|(A[B++]&63)<<6|A[B++]&63)}};function vE(A,Q){if(Q){var B=new s(A.length);for(var C=0;C<A.length;++C)B[C]=A.charCodeAt(C);return B}if(hE)return hE.encode(A);var E=A.length,K=new s(A.length+(A.length>>1)),J=0,Y=function(L){K[J++]=L};for(var C=0;C<E;++C){if(J+5>K.length){var I=new s(J+8+(E-C<<1));I.set(K),K=I}var D=A.charCodeAt(C);if(D<128||Q)Y(D);else if(D<2048)Y(192|D>>6),Y(128|D&63);else if(D>55295&&D<57344)D=65536+(D&1047552)|A.charCodeAt(++C)&1023,Y(240|D>>18),Y(128|D>>12&63),Y(128|D>>6&63),Y(128|D&63);else Y(224|D>>12),Y(128|D>>6&63),Y(128|D&63)}return eQ(K,0,J)}function G8(A,Q){if(Q){var B="";for(var C=0;C<A.length;C+=16384)B+=String.fromCharCode.apply(null,A.subarray(C,C+16384));return B}else if(TC)return TC.decode(A);else{var E=D8(A),K=E.s,B=E.r;if(B.length)HA(8);return K}}var X8=function(A,Q){return Q+30+vA(A,Q+26)+vA(A,Q+28)},H8=function(A,Q,B){var C=vA(A,Q+28),E=vA(A,Q+30),K=G8(A.subarray(Q+46,Q+46+C),!(vA(A,Q+8)&2048)),J=Q+46+C,Y=$8(A,J,E,B,zA(A,Q+20),zA(A,Q+24),zA(A,Q+42)),I=Y[0],D=Y[1],L=Y[2];return[vA(A,Q+10),I,D,K,J+E+vA(A,Q+32),L]},$8=function(A,Q,B,C,E,K,J){var Y=E==4294967295,I=K==4294967295,D=J==4294967295,L=Q+B,G=Y+I+D;if(C&&G){for(;Q+4<L;Q+=4+vA(A,Q+2))if(vA(A,Q)==1)return[Y?zC(A,Q+4+8*I):E,I?zC(A,Q+4):K,D?zC(A,Q+4+8*(I+Y)):J,1];if(C<2)HA(13)}return[E,K,J,0]},_C=function(A){var Q=0;if(A)for(var B in A){var C=A[B].length;if(C>65535)HA(9);Q+=C+4}return Q},bE=function(A,Q,B,C,E,K,J,Y){var I=C.length,D=B.extra,L=Y&&Y.length,G=_C(D);if(YA(A,Q,J!=null?33639248:67324752),Q+=4,J!=null)A[Q++]=20,A[Q++]=B.os;A[Q]=20,Q+=2,A[Q++]=B.flag<<1|(K<0&&8),A[Q++]=E&&8,A[Q++]=B.compression&255,A[Q++]=B.compression>>8;var X=new Date(B.mtime==null?Date.now():B.mtime),Z=X.getFullYear()-1980;if(Z<0||Z>119)HA(10);if(YA(A,Q,Z<<25|X.getMonth()+1<<21|X.getDate()<<16|X.getHours()<<11|X.getMinutes()<<5|X.getSeconds()>>1),Q+=4,K!=-1)YA(A,Q,B.crc),YA(A,Q+4,K<0?-K-2:K),YA(A,Q+8,B.size);if(YA(A,Q+12,I),YA(A,Q+14,G),Q+=16,J!=null)YA(A,Q,L),YA(A,Q+6,B.attrs),YA(A,Q+10,J),Q+=14;if(A.set(C,Q),Q+=I,G)for(var R in D){var F=D[R],V=F.length;YA(A,Q,+R),YA(A,Q+2,V),A.set(F,Q+4),Q+=4+V}if(L)A.set(Y,Q),Q+=L;return Q},Z8=function(A,Q,B,C,E){YA(A,Q,101010256),YA(A,Q+8,B),YA(A,Q+10,B),YA(A,Q+12,C),YA(A,Q+16,E)};function oE(A,Q){if(!Q)Q={};var B={},C=[];nE(A,"",B,Q);var E=0,K=0;for(var J in B){var Y=B[J],I=Y[0],D=Y[1],L=D.level==0?0:8,G=vE(J),X=G.length,Z=D.comment,R=Z&&vE(Z),F=R&&R.length,V=_C(D.extra);if(X>65535)HA(11);var g=L?Y8(I,D):I,b=g.length,M=K8();M.p(I),C.push(dE(D,{size:I.length,crc:M.d(),c:g,f:G,m:R,u:X!=J.length||R&&Z.length!=F,o:E,compression:L})),E+=30+X+V+b,K+=76+2*(X+V)+(F||0)+b}var j=new s(K+22),z=E,y=K-E;for(var p=0;p<C.length;++p){var G=C[p];bE(j,G.o,G,G.f,G.u,G.c.length);var S=30+G.f.length+_C(G.extra);j.set(G.c,G.o+S),bE(j,E,G,G.f,G.u,G.c.length,G.o,G.m),E+=16+S+(G.m?G.m.length:0)}return Z8(j,E,C.length,y,z),j}function aE(A,Q){var B={},C=A.length-22;for(;zA(A,C)!=101010256;--C)if(!C||A.length-C>65558)HA(13);var E=vA(A,C+8);if(!E)return{};var K=zA(A,C+16),J=zA(A,C-20)==117853008;if(J){var Y=zA(A,C-12);if(J=zA(A,Y)==101075792,J)E=zA(A,Y+32),K=zA(A,Y+48)}var I=Q&&Q.filter;for(var D=0;D<E;++D){var L=H8(A,K,J),G=L[0],X=L[1],Z=L[2],R=L[3],F=L[4],V=L[5],g=X8(A,V);if(K=F,!I||I({name:R,size:X,originalSize:Z,compression:G}))if(!G)B[R]=eQ(A,g,g+X);else if(G==8)B[R]=I8(A.subarray(g,g+X),{out:new s(Z)});else HA(14,"unknown compression type "+G)}return B}function U8(){return new Promise((A,Q)=>{let B=indexedDB.open("trove-plugins",1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains("installs"))C.createObjectStore("installs",{keyPath:"id"})},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function SB(A,Q,B){return new Promise((C,E)=>{let K=A.transaction("installs",Q),J=K.objectStore("installs"),Y;Promise.resolve(B(J)).then((I)=>Y=I),K.oncomplete=()=>C(Y),K.onerror=()=>E(K.error)})}var sE=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)});class gC{constructor(){this._db=null}async#A(){return this._db??=await U8()}async save(A){let Q=await this.#A();return await SB(Q,"readwrite",(B)=>B.put(A)),A}async get(A){let Q=await this.#A();return SB(Q,"readonly",(B)=>sE(B.get(A)))}async list(){let A=await this.#A();return SB(A,"readonly",(Q)=>sE(Q.getAll()))}async remove(A){let Q=await this.#A();await SB(Q,"readwrite",(B)=>B.delete(A))}async patch(A,Q){let B=await this.get(A);if(!B)return null;let C={...B,...Q};return await this.save(C),C}}var wB=null;function F8(){if(!wB)wB=import("./chunk-h05bxfbs.js").then((m)=>W8(m.default,1)).then((A)=>(A.default||A)({locateFile:()=>"/sql-wasm.wasm"})).catch((A)=>{throw wB=null,A});return wB}var M8="trove-plugin-clientdb",TB="dbs";function V8(){return new Promise((A,Q)=>{let B=indexedDB.open(M8,1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains(TB))C.createObjectStore(TB)},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function yC(A,Q){return V8().then((B)=>new Promise((C,E)=>{let K=B.transaction(TB,A),J;Promise.resolve(Q(K.objectStore(TB))).then((Y)=>J=Y),K.oncomplete=()=>{B.close(),C(J)},K.onerror=()=>{B.close(),E(K.error)}}))}var P8=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),N8=(A)=>yC("readonly",(Q)=>P8(Q.get(A))),q8=(A,Q)=>yC("readwrite",(B)=>B.put(Q,A)),z8=(A)=>yC("readwrite",(Q)=>Q.delete(A));class iE{constructor(A,Q){this.key=A,this.db=Q,this._saveTimer=null}#A(){clearTimeout(this._saveTimer),this._saveTimer=setTimeout(()=>{this.flush().catch((A)=>{console.error(`persisting plugin storage "${this.key}" failed`,A),this.onError?.(A,this.key)})},150)}async flush(){clearTimeout(this._saveTimer),this._saveTimer=null,await q8(this.key,this.db.export())}async exec(A){return this.db.exec(A),this.#A(),{ok:!0}}async run(A,...Q){return this.db.run(A,Q),this.#A(),{ok:!0}}async get(A,...Q){let B=this.db.prepare(A);try{return B.bind(Q),B.step()?B.getAsObject():null}finally{B.free()}}async all(A,...Q){let B=this.db.prepare(A),C=[];try{B.bind(Q);while(B.step())C.push(B.getAsObject())}finally{B.free()}return C}async batch(A=[]){this.db.run("BEGIN");try{for(let{sql:Q,params:B=[]}of A)this.db.run(Q,B);this.db.run("COMMIT")}catch(Q){try{this.db.run("ROLLBACK")}catch{}throw Q}return this.#A(),{ok:!0}}close(){clearTimeout(this._saveTimer),this.db.close()}}class hC{constructor({onError:A}={}){this._pool=new Map,this.onError=A||null}async obtain(A){let Q=this._pool.get(A);if(!Q){let B=await F8(),C=await N8(A);Q=new iE(A,new B.Database(C||void 0)),Q.onError=this.onError,this._pool.set(A,Q)}return Q}async drop(A){let Q=this._pool.get(A);if(Q)Q.close(),this._pool.delete(A);await z8(A)}}var rE=new TextEncoder;function vC(A){let Q=atob(A.replace(/-/g,"+").replace(/_/g,"/")),B=new Uint8Array(Q.length);for(let C=0;C<Q.length;C++)B[C]=Q.charCodeAt(C);return B}function tE(A){let Q=new Uint8Array(A),B="";for(let C=0;C<Q.length;C++)B+=Q[C].toString(16).padStart(2,"0");return B}async function eE(A){return new Uint8Array(await crypto.subtle.digest("SHA-256",A))}function O8(A){let Q={...A};return delete Q.signature,JSON.stringify(bC(Q))}function bC(A){if(Array.isArray(A))return A.map(bC);if(A&&typeof A==="object"){let Q={};for(let B of Object.keys(A).sort())Q[B]=bC(A[B]);return Q}return A}async function j8(A){let Q=[...A.keys()].filter((J)=>J!=="manifest.json").sort(),B=[];for(let J of Q){let Y=A.get(J),I=rE.encode(J),D=new Uint8Array(4);new DataView(D.buffer).setUint32(0,Y.length),B.push(I,new Uint8Array([0]),D,Y)}let C=B.reduce((J,Y)=>J+Y.length,0),E=new Uint8Array(C),K=0;for(let J of B)E.set(J,K),K+=J.length;return tE(await eE(E))}async function S8(A){return tE(await eE(vC(A)))}async function w8({manifest:A,files:Q}){if(!A.signature||!A.publicKey)return{signed:!1,valid:!1};let B=await j8(Q);if(A.contentHash&&A.contentHash!==B)return{signed:!0,valid:!1,reason:"File contents do not match the manifest hash"};try{let C=await crypto.subtle.importKey("spki",vC(A.publicKey),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,vC(A.signature),rE.encode(O8(A))))return{signed:!0,valid:!1,reason:"Signature does not verify"};return{signed:!0,valid:!0,fingerprint:await S8(A.publicKey)}}catch(C){return{signed:!0,valid:!1,reason:"Bad key/signature: "+C.message}}}function T8(A,Q,B){let C=(J)=>(J||"").toLowerCase().replace(/:/g,""),E=C(Q),K=[B.name,`${B.domain}/${B.name}`];for(let J of A?.keys||[]){if(C(J.fingerprint)!==E)continue;if((J.plugins||[]).some((Y)=>Y==="*"||K.includes(Y)))return!0}return!1}async function AK({manifest:A,files:Q},B){let C=await w8({manifest:A,files:Q});if(!C.signed)return{status:"unverified",reason:"Package is not signed"};if(!C.valid)return{status:"invalid",reason:C.reason||"Invalid signature — the package may have been tampered with"};let E=null;try{E=await B(A.domain)}catch{}if(E&&T8(E,C.fingerprint,A))return{status:"verified",domain:A.domain,fingerprint:C.fingerprint};return{status:"signed",domain:A.domain,fingerprint:C.fingerprint,reason:E?"Domain does not list this key":"Could not reach the domain"}}function fC(A){let Q=/^([a-z][a-z0-9+.-]*:\/\/)\*\.(.+)$/i.exec(A),B=!!Q,C;try{C=new URL(B?Q[1]+Q[2]:A)}catch{throw Error(`Invalid network endpoint "${A}" (must be an absolute http(s) URL)`)}if(C.protocol!=="http:"&&C.protocol!=="https:")throw Error(`Network endpoint "${A}" must use http or https`);let E=C.hostname.toLowerCase();if(!E)throw Error(`Network endpoint "${A}" has no host`);return{scheme:C.protocol,host:E,wildcard:B,port:C.port,pathPrefix:C.pathname||"/",raw:A}}function QK(A){let Q=[];for(let B of A||[])try{Q.push(fC(B))}catch{}return Q}function _8(A,Q){let B;try{B=new URL(Q)}catch{return!1}if(B.protocol!==A.scheme)return!1;let C=B.hostname.toLowerCase();if(A.wildcard){if(C!==A.host&&!C.endsWith("."+A.host))return!1}else if(C!==A.host)return!1;if(B.port!==A.port)return!1;return B.pathname.startsWith(A.pathPrefix)}function _B(A,Q){return QK(A).some((B)=>_8(B,Q))}function kB(A){return QK(A).map((Q)=>({scheme:Q.scheme.replace(":",""),host:(Q.wildcard?"*.":"")+Q.host+(Q.port?":"+Q.port:""),path:Q.pathPrefix==="/"?"":Q.pathPrefix,raw:Q.raw}))}var k8={files:"Read your files, folders, and search index (via the host).",storage:"Keep its own SQLite database(s) — on the server and/or on this device.",ui:"Show a popup panel and toasts.",commands:"Add commands to the palette, and run the specific host commands it lists.",opener:"Preview/open file types.",indexer:"Add searchable content to your files.",network:"Connect to the internet — only the endpoints it declares (shown below).",media:"Show playback controls on your lock screen and notifications while it plays media.",dock:"Keep its viewer in a small floating window when you navigate away."},uC=new Set;function BK(A){let Q=pC(A,"storage");if(!Q)return{plugin:!1,domain:!1};if(Q===!0||typeof Q==="object"&&!("plugin"in Q)&&!("domain"in Q))return{plugin:!0,domain:!1};return{plugin:!!Q.plugin,domain:!!Q.domain}}function x8(A){return k8[A]||A}function CK(A){let Q=A&&A.capabilities,B={};if(Array.isArray(Q)){for(let C of Q)if(C)B[C]={}}else if(Q&&typeof Q==="object")for(let[C,E]of Object.entries(Q)){if(E===!1||E==null)continue;B[C]=E===!0?{}:E}return B}function mC(A){return Object.keys(CK(A))}function pC(A,Q){let B=CK(A);return Object.prototype.hasOwnProperty.call(B,Q)?B[Q]:null}function HQ(A){let Q=pC(A,"network");if(Q){if(Array.isArray(Q))return Q;if(Array.isArray(Q.endpoints))return Q.endpoints;if(Array.isArray(Q.prefixes))return Q.prefixes}if(Array.isArray(A.network))return A.network;return[]}function OA(A){let Q=A?.displayName??A?.name;return typeof Q==="string"&&Q.trim()?Q:"Plugin"}function EK(A){let Q=pC(A,"commands");if(!Q)return[];if(Array.isArray(Q))return Q.filter(Boolean);if(Array.isArray(Q.execute))return Q.execute.filter(Boolean);return[]}function xB(A,Q,B){if(!Q)return!1;if(QQ(Q)&&PE(A,Q))return!0;return EK(A).includes(Q)}function $Q(A){let Q;try{Q=aE(A instanceof Uint8Array?A:new Uint8Array(A))}catch(K){throw Error("Not a valid zip archive: "+K.message)}let B=new Map;for(let[K,J]of Object.entries(Q))if(!K.endsWith("/"))B.set(K.replace(/^\.?\//,""),J);let C=B.get("manifest.json");if(!C)throw Error("Package is missing manifest.json");let E;try{E=JSON.parse(new TextDecoder().decode(C))}catch(K){throw Error("manifest.json is not valid JSON: "+K.message)}return g8(E,B),{manifest:E,files:B,raw:A}}function g8(A,Q){let B=(C,E)=>{if(!C)throw Error(E)};if(PB(A),B(A.entry,"manifest.entry (path to the plugin script) is required"),B(Q.has(A.entry),`entry "${A.entry}" is not in the package`),A.capabilities!=null)B(Array.isArray(A.capabilities)||typeof A.capabilities==="object","capabilities must be an object of { capability: options } (or an array of ids)");if(A.icon)B(Q.has(A.icon),`icon "${A.icon}" is not in the package`);for(let C of cA(A)){if(C.entry)B(Q.has(C.entry),`contribution "${C.name}" points at "${C.entry}", which is not in the package`);if(C.type==="keymap")B(Q.has(C.path),`keymap "${C.name}" points at "${C.path}", which is not in the package`)}for(let C of HQ(A))fC(C)}async function KK(A,Q=globalThis.fetch.bind(globalThis)){let B;try{B=await Q(A)}catch(E){throw Error("Could not fetch the plugin: "+E.message)}if(!B.ok)throw Error(`Could not fetch the plugin (HTTP ${B.status})`);let C=new Uint8Array(await B.arrayBuffer());return $Q(C)}function JK(A,Q){let B=A.manifest,C=cA(B).map((J)=>({kind:J.type,name:J.name,uri:J.uri,title:J.title||J.name,detail:J.type==="opener"||J.type==="indexer"?y8(J.match):J.type==="statusItem"?`${J.slot} of the status bar${J.command?` — runs ${J.command}`:""}`:J.type==="keymap"?J.path:"",offline:!!J.offline})),E=Q?.status==="verified",K=BK(B);return{id:yA(B),name:OA(B),version:B.version||"0.0.0",description:B.description||"",author:B.author||"Unknown",domain:B.domain,capabilities:mC(B).map((J)=>({id:J,description:x8(J),adminOnly:uC.has(J)})),contributions:C,settings:(B.settings||[]).map((J)=>({key:J.key,title:J.title||J.key,type:J.type,secret:!!J.secret})),network:kB(HQ(B)),commands:EK(B),storage:K.plugin||K.domain?{plugin:K.plugin,domain:K.domain,domainBlocked:K.domain&&!E}:null,fileCount:A.files.size,sizeBytes:[...A.files.values()].reduce((J,Y)=>J+Y.length,0),trust:Q}}function cC(A,Q){let B=BK(A);return{plugin:B.plugin,domain:B.domain&&Q?.status==="verified"}}function y8(A){if(!A)return"";let Q=[];if(A.ext?.length)Q.push(A.ext.join(", "));if(A.mime?.length)Q.push(A.mime.join(", "));return Q.join(" · ")}class lC{constructor(){this.owner=null}#A(){return typeof navigator<"u"?navigator.mediaSession:null}apply(A,Q,B={}){let C=this.#A();if(!C)return{ok:!1};if(A&&Q!=="clear")this.owner=A,A.mediaOwner=!0;try{if(Q==="metadata")C.metadata=typeof MediaMetadata<"u"?new MediaMetadata({title:B.title||"",artist:B.artist||"",album:B.album||"",artwork:B.artwork||[]}):C.metadata;else if(Q==="playbackState")C.playbackState=B.state||"none";else if(Q==="position"&&C.setPositionState)C.setPositionState({duration:B.duration||0,position:B.position||0,playbackRate:B.playbackRate||1});else if(Q==="action"){if(C.setActionHandler?.(B.action,B.on?()=>A?.channel?.emit("media:action",{action:B.action}):null),A)A.mediaActions||=new Set,B.on?A.mediaActions.add(B.action):A.mediaActions.delete(B.action)}else if(Q==="clear"){if(A&&this.owner&&this.owner!==A)return{ok:!0};this.releaseActions(A),C.metadata=null,C.playbackState="none",this.owner=null}}catch{}return{ok:!0}}releaseActions(A){let Q=this.#A();if(!Q||!A?.mediaActions)return;for(let B of A.mediaActions)try{Q.setActionHandler?.(B,null)}catch{}A.mediaActions.clear()}releaseFrame(A){if(this.owner===A)this.owner=null,this.apply(A,"clear",{});this.releaseActions(A)}}class dC{constructor({destroyFrame:A,openFile:Q,onChange:B}={}){this.destroyFrame=A,this.openFile=Q,this.onChange=B||(()=>{}),this.docked=null,this.el=null}place(A,Q,B,C=""){this.stopPlace(A);let E=A.iframe;E.style.cssText=`position:fixed;border:0;visibility:visible;display:block;background:transparent;z-index:${B};margin:0;padding:0;border-radius:${C};`;let K=()=>{let I=Q.getBoundingClientRect(),D=I.width>0&&I.height>0&&document.contains(Q);E.style.left=`${I.left}px`,E.style.top=`${I.top}px`,E.style.width=`${I.width}px`,E.style.height=`${I.height}px`,E.style.visibility=D?"visible":"hidden"};K();let J=typeof ResizeObserver<"u"?new ResizeObserver(K):null;if(J?.observe(Q),document.body)J?.observe(document.body);let Y=typeof IntersectionObserver<"u"?new IntersectionObserver(K,{threshold:[0,1]}):null;Y?.observe(Q),window.addEventListener("scroll",K,!0),window.addEventListener("resize",K),A.place={target:Q,stop:()=>{J?.disconnect(),Y?.disconnect(),window.removeEventListener("scroll",K,!0),window.removeEventListener("resize",K)}}}stopPlace(A){if(A.place)A.place.stop(),A.place=null}hide(A){this.stopPlace(A),A.iframe.style.cssText="position:fixed;left:0;top:0;width:0;height:0;border:0;visibility:hidden;"}releaseFrame(A){if(this.stopPlace(A),this.docked===A)this.docked=null,this.#A()}#A(){if(this.el)this.el.style.display="none"}dock(A){if(this.docked&&this.docked!==A)this.closeDock(this.docked);let Q=A.dock?.minSize||{width:300,height:90},B=this.#Q();B.style.width=`${YK(Q.width,200,480)}px`,B.style.height=`${YK(Q.height,56,360)+26}px`,B.querySelector(".vd-title").textContent=A.node?.name||(A.record.manifest.displayName||A.record.manifest.name),B.style.display="flex",this.place(A,B.querySelector(".vd-body"),61,"0 0 11px 11px"),this.docked=A,A.channel?.emit("dock:state",{docked:!0}),this.onChange()}undock(A){if(this.#A(),this.docked===A)this.docked=null;A.channel?.emit("dock:state",{docked:!1})}closeDock(A){if(this.#A(),this.docked===A)this.docked=null;A.channel?.emit("dock:state",{docked:!1,closed:!0}),this.destroyFrame?.(A),this.onChange()}#Q(){if(this.el)return this.el;let A=document.createElement("div");return A.className="viewer-dock",A.innerHTML='<div class="vd-bar"><span class="vd-title"></span><button class="vd-expand" title="Reopen">↗</button><button class="vd-close" title="Close">✕</button></div><div class="vd-body"></div>',A.querySelector(".vd-expand").addEventListener("click",()=>{let Q=this.docked;if(Q?.node)this.openFile?.(Q.node,Q.openerId)}),A.querySelector(".vd-close").addEventListener("click",()=>{if(this.docked)this.closeDock(this.docked)}),document.body.appendChild(A),this.el=A,A}}function YK(A,Q,B){return Math.max(Q,Math.min(B,A||Q))}class nC{constructor(A,Q={}){if(this.port=A,this.onCall=Q.onCall,this.onEvent=Q.onEvent,this.targetOrigin=Q.targetOrigin,this.seq=0,this.pending=new Map,this._listener=(B)=>this._receive(B.data,B),typeof A.addEventListener==="function")A.addEventListener("message",this._listener);else A.onmessage=this._listener;A.start?.()}_post(A,Q){if(this.targetOrigin)this.port.postMessage(A,this.targetOrigin,Q);else this.port.postMessage(A,Q)}call(A,Q,{timeout:B=30000,transfer:C}={}){let E=++this.seq;return new Promise((K,J)=>{let Y=B?setTimeout(()=>{this.pending.delete(E),J(Error(`RPC timeout: ${A}`))},B):null;this.pending.set(E,{resolve:K,reject:J,timer:Y}),this._post({__trove:"req",id:E,method:A,params:Q},C)})}emit(A,Q,B){this._post({__trove:"event",method:A,params:Q},B)}async _receive(A,Q){if(!A||A.__trove==null)return;if(A.__trove==="res"){let B=this.pending.get(A.id);if(!B)return;if(this.pending.delete(A.id),B.timer)clearTimeout(B.timer);if(A.error)B.reject(Object.assign(Error(A.error.message),A.error));else B.resolve(A.result);return}if(A.__trove==="event"){try{await this.onEvent?.(A.method,A.params,Q)}catch(B){console.error("rpc event handler error",B)}return}if(A.__trove==="req"){let B,C;try{B=await this.onCall?.(A.method,A.params,Q)}catch(E){C={message:E?.message||String(E),code:E?.code||"error"}}this._post({__trove:"res",id:A.id,result:B,error:C})}}dispose(){if(typeof this.port.removeEventListener==="function")this.port.removeEventListener("message",this._listener);for(let A of this.pending.values()){if(A.timer)clearTimeout(A.timer);A.reject(Error("RPC channel disposed"))}this.pending.clear(),this.port.close?.()}}var oC=`// Injectable browser build of the Trove plugin SDK — a single self-contained IIFE
|
|
5
|
+
// with NO imports, so the host can inline it into a sandboxed iframe's srcdoc
|
|
6
|
+
// alongside the plugin's entry script. The iframe runs on an opaque origin
|
|
7
|
+
// (sandbox="allow-scripts", no allow-same-origin), so it can't fetch its own
|
|
8
|
+
// package files; instead it reaches everything — resources, files, settings,
|
|
9
|
+
// storage — through the host over a transferred MessagePort. Package resources
|
|
10
|
+
// are handed back as raw bytes (or iframe-local blob: URLs), never host URLs, so
|
|
11
|
+
// the plugin only ever holds opaque handles.
|
|
12
|
+
//
|
|
13
|
+
// Plugins use it as: trove.activate(async (ctx) => { ... })
|
|
14
|
+
(function () {
|
|
15
|
+
'use strict';
|
|
16
|
+
// Wire-protocol version this SDK speaks. MUST equal PROTOCOL_VERSION in
|
|
17
|
+
// protocol.js — this file is injected as text and cannot import it, so
|
|
18
|
+
// protocol.test.js asserts the two stay in step.
|
|
19
|
+
const SDK_PROTOCOL_VERSION = '1.0';
|
|
20
|
+
let port = null, manifest = null, capabilities = [], storageScopes = {}, online = true, seq = 0, role = 'primary';
|
|
21
|
+
const pending = new Map();
|
|
22
|
+
const commandHandlers = new Map();
|
|
23
|
+
const openerHandlers = new Map();
|
|
24
|
+
let onConnectivity = null, onDeactivate = null, onSettingsChange = null, onDock = null;
|
|
25
|
+
const mediaHandlers = {}; // action -> handler, for OS media-session controls
|
|
26
|
+
|
|
27
|
+
const now = () => { try { return Date.now(); } catch { return 0; } };
|
|
28
|
+
|
|
29
|
+
// The HOST times its own calls out; this side did not, and \`pending\` was never
|
|
30
|
+
// rejected — not on a dropped reply, not on port close. A plugin awaiting one hung
|
|
31
|
+
// forever with no way to find out, and the entry leaked with it.
|
|
32
|
+
const CALL_TIMEOUT_MS = 30_000;
|
|
33
|
+
|
|
34
|
+
function call(method, params, transfer) {
|
|
35
|
+
const id = ++seq;
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const timer = setTimeout(() => {
|
|
38
|
+
pending.delete(id);
|
|
39
|
+
reject(new Error(\`Timed out waiting for the host to answer "\${method}"\`));
|
|
40
|
+
}, CALL_TIMEOUT_MS);
|
|
41
|
+
if (timer && timer.unref) timer.unref();
|
|
42
|
+
pending.set(id, { resolve, reject, timer });
|
|
43
|
+
port.postMessage({ __trove: 'req', id, method, params }, transfer || []);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const emit = (method, params) => port.postMessage({ __trove: 'event', method, params });
|
|
47
|
+
|
|
48
|
+
// What this frame reports about itself on every heartbeat. Contributions are the
|
|
49
|
+
// host's own manifest reading — all the plugin can usefully say is which of its
|
|
50
|
+
// declared contributions it actually bound a handler to, plus whether it thinks
|
|
51
|
+
// it's online.
|
|
52
|
+
function buildManifest() {
|
|
53
|
+
return {
|
|
54
|
+
domain: manifest && manifest.domain, name: manifest && manifest.name,
|
|
55
|
+
online, role, ts: now(),
|
|
56
|
+
handlers: [...commandHandlers.keys()],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const announce = () => port && emit('manifest', buildManifest());
|
|
60
|
+
|
|
61
|
+
function onPort(e) {
|
|
62
|
+
const m = e.data;
|
|
63
|
+
if (!m || m.__trove == null) return;
|
|
64
|
+
if (m.__trove === 'res') {
|
|
65
|
+
const p = pending.get(m.id);
|
|
66
|
+
if (!p) return;
|
|
67
|
+
clearTimeout(p.timer);
|
|
68
|
+
pending.delete(m.id);
|
|
69
|
+
m.error ? p.reject(Object.assign(new Error(m.error.message), m.error)) : p.resolve(m.result);
|
|
70
|
+
} else if (m.__trove === 'req') {
|
|
71
|
+
Promise.resolve().then(() => dispatch(m.method, m.params))
|
|
72
|
+
.then((result) => port.postMessage({ __trove: 'res', id: m.id, result }))
|
|
73
|
+
.catch((err) => port.postMessage({ __trove: 'res', id: m.id, error: { message: err.message } }));
|
|
74
|
+
} else if (m.__trove === 'event') {
|
|
75
|
+
dispatchEvent(m.method, m.params);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function dispatch(method, params) {
|
|
80
|
+
if (method === 'command:execute') {
|
|
81
|
+
const h = commandHandlers.get(params.id);
|
|
82
|
+
// Throw, like \`opener:open\` two lines down. Resolving \`undefined\` for an id with
|
|
83
|
+
// no handler told the host the command had RUN when nothing had.
|
|
84
|
+
if (!h) throw new Error(\`No handler registered for command "\${params.id}"\`);
|
|
85
|
+
return h(...(params.args || []));
|
|
86
|
+
}
|
|
87
|
+
if (method === 'opener:open') {
|
|
88
|
+
// An opener frame boots at that opener's entry module and runs exactly one
|
|
89
|
+
// opener, so an unkeyed onOpen(fn) handler is the normal case.
|
|
90
|
+
const f = openerHandlers.get(params.openerId) || openerHandlers.get('*');
|
|
91
|
+
if (!f) throw new Error('no opener ' + params.openerId);
|
|
92
|
+
return f(params.file, params.context);
|
|
93
|
+
}
|
|
94
|
+
if (method === 'manifest') return buildManifest();
|
|
95
|
+
throw new Error('Unknown host call ' + method);
|
|
96
|
+
}
|
|
97
|
+
async function dispatchEvent(method, params) {
|
|
98
|
+
if (method === 'deactivate') return onDeactivate && onDeactivate();
|
|
99
|
+
if (method === 'connectivity') { online = !!params.online; try { onConnectivity && (await onConnectivity({ online })); } catch (e) { console.error(e); } announce(); }
|
|
100
|
+
if (method === 'settings:changed') { try { onSettingsChange && onSettingsChange(params.key, params.value); } catch (e) { console.error(e); } }
|
|
101
|
+
// The OS/host fired a media transport control (play/pause/next/seek…).
|
|
102
|
+
if (method === 'media:action') { try { mediaHandlers[params.action] && mediaHandlers[params.action](params); } catch (e) { console.error(e); } }
|
|
103
|
+
// The host docked or undocked this viewer (see ctx.dock).
|
|
104
|
+
if (method === 'dock:state') { try { onDock && onDock(params); } catch (e) { console.error(e); } }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function requireCap(cap) { if (!capabilities.includes(cap)) throw new Error('Plugin lacks capability "' + cap + '"'); }
|
|
108
|
+
|
|
109
|
+
// Storage: one async SQL handle (mirrors the host SqliteDatabase interface) per
|
|
110
|
+
// scope+side, over RPC. Only granted scopes are exposed on ctx.storage.
|
|
111
|
+
function sqlHandle(scope, side) {
|
|
112
|
+
var send = function (op, extra) { return call('storage:sql', Object.assign({ scope: scope, side: side, op: op }, extra)); };
|
|
113
|
+
return {
|
|
114
|
+
exec: function (sql) { return send('exec', { sql: sql }); },
|
|
115
|
+
run: function (sql) { return send('run', { sql: sql, params: [].slice.call(arguments, 1) }); },
|
|
116
|
+
get: function (sql) { return send('get', { sql: sql, params: [].slice.call(arguments, 1) }); },
|
|
117
|
+
all: function (sql) { return send('all', { sql: sql, params: [].slice.call(arguments, 1) }); },
|
|
118
|
+
batch: function (statements) { return send('batch', { statements: statements }); },
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function scopeHandle(scope) {
|
|
122
|
+
return { server: sqlHandle(scope, 'server'), client: sqlHandle(scope, 'client') };
|
|
123
|
+
}
|
|
124
|
+
function makeStorage() {
|
|
125
|
+
var s = {};
|
|
126
|
+
if (storageScopes.plugin) s.plugin = scopeHandle('plugin');
|
|
127
|
+
if (storageScopes.domain) s.domain = scopeHandle('domain');
|
|
128
|
+
return s;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function hasHeader(h, name) { name = name.toLowerCase(); for (var k in h) if (k.toLowerCase() === name) return true; return false; }
|
|
132
|
+
// Wrap the host's brokered-fetch result in a minimal Response-like object.
|
|
133
|
+
function makeResponse(r) {
|
|
134
|
+
var bytes = new Uint8Array(r.bytes || new ArrayBuffer(0));
|
|
135
|
+
var decode = function () { return new TextDecoder().decode(bytes); };
|
|
136
|
+
return {
|
|
137
|
+
ok: r.ok, status: r.status, statusText: r.statusText, url: r.url, headers: r.headers || {},
|
|
138
|
+
arrayBuffer: function () { return Promise.resolve(bytes.slice().buffer); },
|
|
139
|
+
bytes: function () { return Promise.resolve(bytes); },
|
|
140
|
+
text: function () { return Promise.resolve(decode()); },
|
|
141
|
+
json: function () { return Promise.resolve(JSON.parse(decode())); },
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function makeContext() {
|
|
146
|
+
return {
|
|
147
|
+
manifest, capabilities,
|
|
148
|
+
// Which instance this is: 'primary' is the plugin's single background frame
|
|
149
|
+
// (register commands/indexers, do one-time setup here); 'viewer' is a
|
|
150
|
+
// per-open frame hosting an opener for one file (drive media/dock from here).
|
|
151
|
+
role,
|
|
152
|
+
get online() { return online; },
|
|
153
|
+
// Contributions are DECLARED IN THE MANIFEST (openers, indexers, commands,
|
|
154
|
+
// statusItems, keybindings). The host registers them before this code runs, so
|
|
155
|
+
// a plugin never registers anything at runtime — it only supplies the behaviour
|
|
156
|
+
// for what it declared, addressed by id.
|
|
157
|
+
commands: {
|
|
158
|
+
/** Implement a command this plugin's manifest declares, by its short name. */
|
|
159
|
+
handle(name, handler) { commandHandlers.set(name, handler); return this; },
|
|
160
|
+
/**
|
|
161
|
+
* Run a command. Its OWN commands by short name; anyone else's by full address
|
|
162
|
+
* (a built-in like 'explorer.download', or a \`trove+contrib:\` URI) — and only
|
|
163
|
+
* if the manifest's \`commands\` capability lists it.
|
|
164
|
+
*/
|
|
165
|
+
execute(id) { const a = [].slice.call(arguments, 1); return call('command:execute', { id, args: a }); },
|
|
166
|
+
},
|
|
167
|
+
/** Implement the opener this frame was booted for (its entry module). The id is
|
|
168
|
+
* optional — an opener frame runs exactly one opener. */
|
|
169
|
+
onOpen(idOrHandler, maybeHandler) {
|
|
170
|
+
const [id, handler] = typeof idOrHandler === 'function' ? ['*', idOrHandler] : [idOrHandler, maybeHandler];
|
|
171
|
+
openerHandlers.set(id, handler);
|
|
172
|
+
return this;
|
|
173
|
+
},
|
|
174
|
+
// NOTE: there is no onIndex(). Indexers run on the SERVER (in its isolate
|
|
175
|
+
// runtime), not in this sandbox — indexing has to happen once per upload for the
|
|
176
|
+
// drive, not in whichever tab is open. An indexer's entry module is plain ESM
|
|
177
|
+
// exporting \`index(node, ctx)\`; it doesn't use this SDK at all. What a plugin can
|
|
178
|
+
// do from here is PUSH contributions for a node via ctx.files.index (the
|
|
179
|
+
// \`indexer\` capability).
|
|
180
|
+
// Package resources — opaque handles. read() copies bytes into the iframe;
|
|
181
|
+
// url() wraps them in an iframe-local blob: URL.
|
|
182
|
+
resources: {
|
|
183
|
+
list() { return call('resources:list', {}); },
|
|
184
|
+
async read(path) { const r = await call('resources:read', { path }); return new Uint8Array(r.bytes); },
|
|
185
|
+
async text(path) { return new TextDecoder().decode(await this.read(path)); },
|
|
186
|
+
async url(path, type) {
|
|
187
|
+
const bytes = await this.read(path);
|
|
188
|
+
return URL.createObjectURL(new Blob([bytes], { type: type || 'application/octet-stream' }));
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
ui: {
|
|
192
|
+
toast: (text, opts) => emit('ui:toast', Object.assign({ text }, opts)),
|
|
193
|
+
showPanel: () => call('ui:showPanel', {}),
|
|
194
|
+
setBadge: (text) => emit('ui:badge', { text }),
|
|
195
|
+
/**
|
|
196
|
+
* Drive a status-bar slot this plugin's manifest declares. \`html\` is sanitized
|
|
197
|
+
* by the host down to a small inline-formatting allowlist before it renders.
|
|
198
|
+
* ctx.ui.status('sync').set('<b>3</b> queued')
|
|
199
|
+
* ctx.ui.status('sync').hide()
|
|
200
|
+
*/
|
|
201
|
+
status(name) {
|
|
202
|
+
return {
|
|
203
|
+
set: (html, opts) => call('ui:status', Object.assign({ name, html, visible: true }, opts || {})),
|
|
204
|
+
show: () => call('ui:status', { name, visible: true }),
|
|
205
|
+
hide: () => call('ui:status', { name, visible: false }),
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
/**
|
|
210
|
+
* Registers — context value slots this plugin's manifest declares, which
|
|
211
|
+
* when-clauses (its own keymap's, its commands') read by contribution URI.
|
|
212
|
+
* ctx.registers.set('busy', true)
|
|
213
|
+
*/
|
|
214
|
+
registers: {
|
|
215
|
+
set: (name, value) => call('context:setRegister', { name, value }),
|
|
216
|
+
},
|
|
217
|
+
// Media session — surfaces this viewer's playback to the OS (lock-screen /
|
|
218
|
+
// notification transport controls, so phones can play/pause/seek). The host
|
|
219
|
+
// owns navigator.mediaSession; action handlers are called back over RPC.
|
|
220
|
+
media: {
|
|
221
|
+
setMetadata: (m) => (requireCap('media'), call('media:metadata', m || {})),
|
|
222
|
+
setPlaybackState: (state) => (requireCap('media'), call('media:playbackState', { state })),
|
|
223
|
+
setPositionState: (p) => (requireCap('media'), call('media:position', p || {})),
|
|
224
|
+
setActionHandler: (action, handler) => { requireCap('media'); if (handler) mediaHandlers[action] = handler; else delete mediaHandlers[action]; return call('media:action', { action, on: !!handler }); },
|
|
225
|
+
clear: () => call('media:clear', {}),
|
|
226
|
+
},
|
|
227
|
+
// Dock — register this viewer to persist as a small floating frame when the
|
|
228
|
+
// user navigates away (a docked video = picture-in-picture; docked audio = a
|
|
229
|
+
// mini transport). Enable while playing/active, disable otherwise. \`minSize\`/
|
|
230
|
+
// \`maxSize\` are {width,height} constraints. onDock is notified on (un)dock.
|
|
231
|
+
dock: {
|
|
232
|
+
enable: (opts) => (requireCap('dock'), call('dock:enable', opts || {})),
|
|
233
|
+
disable: () => (requireCap('dock'), call('dock:disable', {})),
|
|
234
|
+
close: () => call('dock:close', {}),
|
|
235
|
+
onChange: (fn) => { onDock = fn; },
|
|
236
|
+
},
|
|
237
|
+
// Network — there is no direct fetch in the sandbox; the host performs the
|
|
238
|
+
// request, but ONLY to endpoints declared in the manifest's \`network\` list
|
|
239
|
+
// (and only with the "network" capability). Returns a Response-like object.
|
|
240
|
+
net: {
|
|
241
|
+
fetch(url, opts) {
|
|
242
|
+
requireCap('network');
|
|
243
|
+
opts = opts || {};
|
|
244
|
+
var body = opts.body;
|
|
245
|
+
var headers = Object.assign({}, opts.headers);
|
|
246
|
+
if (body && typeof body === 'object' && !(body instanceof ArrayBuffer) && !(body instanceof Uint8Array)) {
|
|
247
|
+
body = JSON.stringify(body);
|
|
248
|
+
if (!hasHeader(headers, 'content-type')) headers['Content-Type'] = 'application/json';
|
|
249
|
+
}
|
|
250
|
+
// \`.buffer\` ignores byteOffset/byteLength, so any view produced by \`subarray\` or
|
|
251
|
+
// \`slice\` — or a view into a pooled buffer — sent the WHOLE backing store: the wrong
|
|
252
|
+
// payload, and an out-of-band leak of whatever else was in it.
|
|
253
|
+
if (ArrayBuffer.isView(body)) {
|
|
254
|
+
body = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
|
|
255
|
+
}
|
|
256
|
+
return call('net:fetch', { url: String(url), method: opts.method || 'GET', headers: headers, body: body })
|
|
257
|
+
.then(makeResponse);
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
files: {
|
|
261
|
+
read: (id, opts) => (requireCap('files'), call('files:read', Object.assign({ id }, opts))),
|
|
262
|
+
list: (pathOrId, opts) => (requireCap('files'), call('files:list', Object.assign({ pathOrId }, opts))),
|
|
263
|
+
stat: (id) => (requireCap('files'), call('files:stat', { id })),
|
|
264
|
+
downloadUrl: (id) => (requireCap('files'), call('files:downloadUrl', { id })),
|
|
265
|
+
// index(indexerId, nodeId, contribution) where contribution is
|
|
266
|
+
// { semanticTexts?, tags?, metadata? }. Legacy (indexerId, nodeId, documents[], facet)
|
|
267
|
+
// is still accepted when the 3rd arg is an array of documents.
|
|
268
|
+
index: (indexerId, nodeId, contribution, facet) => {
|
|
269
|
+
requireCap('indexer');
|
|
270
|
+
var payload = Array.isArray(contribution) ? { documents: contribution, facet: facet } : (contribution || {});
|
|
271
|
+
return call('files:index', Object.assign({ indexerId: indexerId, nodeId: nodeId }, payload));
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
// Persistent storage: an isolated SQLite database per granted scope. \`plugin\`
|
|
275
|
+
// is private to this plugin; \`domain\` (verified packages only) is shared with
|
|
276
|
+
// the vendor's other plugins. Each scope exposes a \`.server\` handle (and, from
|
|
277
|
+
// Stage 3, an on-device \`.client\` handle) with the same async SQL surface.
|
|
278
|
+
storage: makeStorage(),
|
|
279
|
+
// The plugin's own settings (declared in the manifest). getSecret reads a
|
|
280
|
+
// secret-typed value the host stores separately.
|
|
281
|
+
settings: {
|
|
282
|
+
get: (key) => call('settings:get', { key }),
|
|
283
|
+
getSecret: (key) => call('settings:getSecret', { key }),
|
|
284
|
+
set: (key, value) => call('settings:set', { key, value }),
|
|
285
|
+
onChange: (fn) => { onSettingsChange = fn; },
|
|
286
|
+
},
|
|
287
|
+
onConnectivity: (fn) => { onConnectivity = fn; },
|
|
288
|
+
announce,
|
|
289
|
+
onDeactivate: (fn) => { onDeactivate = fn; },
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async function activate(setup) {
|
|
294
|
+
await new Promise((resolve) => {
|
|
295
|
+
function onInit(e) {
|
|
296
|
+
if (!e.data || e.data.__trove !== 'init') return;
|
|
297
|
+
window.removeEventListener('message', onInit);
|
|
298
|
+
manifest = e.data.manifest; capabilities = e.data.capabilities || []; storageScopes = e.data.storage || {}; online = e.data.online != null ? e.data.online : true; role = e.data.role || 'primary';
|
|
299
|
+
port = e.ports[0];
|
|
300
|
+
port.onmessage = onPort;
|
|
301
|
+
resolve();
|
|
302
|
+
}
|
|
303
|
+
window.addEventListener('message', onInit);
|
|
304
|
+
parent.postMessage({ __trove: 'ready', protocolVersion: SDK_PROTOCOL_VERSION }, '*');
|
|
305
|
+
});
|
|
306
|
+
const ctx = makeContext();
|
|
307
|
+
try {
|
|
308
|
+
await setup(ctx);
|
|
309
|
+
await call('activated', { ok: true });
|
|
310
|
+
announce();
|
|
311
|
+
} catch (err) {
|
|
312
|
+
await call('activated', { ok: false, error: err && err.message });
|
|
313
|
+
throw err;
|
|
314
|
+
}
|
|
315
|
+
return ctx;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
globalThis.trove = { activate };
|
|
319
|
+
})();
|
|
320
|
+
`;var aC="1.0";function IK(A){return String(A||"").split(".")[0]||"0"}function LK(A){if(!A)return!0;return IK(A)===IK("1.0")}var DK;(function(A){A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase",A[A.StaticDeferPhase=6]="StaticDeferPhase",A[A.DynamicDeferPhase=7]="DynamicDeferPhase"})(DK||(DK={}));var v8=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function sC(A,Q="@"){if(!c)return iC.then(()=>sC(A));let B=A.length+1,C=(c.__heap_base.value||c.__heap_base)+4*B-c.memory.buffer.byteLength;C>0&&c.memory.grow(Math.ceil(C/65536));let E=c.sa(B-1);if((v8?f8:b8)(A,new Uint16Array(c.memory.buffer,E,B)),!c.parse())throw Object.assign(Error(`Parse error ${Q}:${A.slice(0,c.e()).split(`
|
|
321
|
+
`).length}:${c.e()-A.lastIndexOf(`
|
|
322
|
+
`,c.e()-1)}`),{idx:c.e()});let K=[],J=[];for(;c.ri();){let I=c.is(),D=c.ie(),L=c.it(),G=c.ai(),X=c.id(),Z=c.ss(),R=c.se(),F;c.ip()&&(F=Y(A.slice(X===-1?I-1:I,X===-1?D+1:D))),K.push({n:F,t:L,s:I,e:D,ss:Z,se:R,d:X,a:G})}for(;c.re();){let I=c.es(),D=c.ee(),L=c.els(),G=c.ele(),X=A.slice(I,D),Z=X[0],R=L<0?void 0:A.slice(L,G),F=R?R[0]:"";J.push({s:I,e:D,ls:L,le:G,n:Z==='"'||Z==="'"?Y(X):X,ln:F==='"'||F==="'"?Y(R):R})}function Y(I){try{return(0,eval)(I)}catch(D){}}return[K,J,!!c.f(),!!c.ms()]}function b8(A,Q){let B=A.length,C=0;for(;C<B;){let E=A.charCodeAt(C);Q[C++]=(255&E)<<8|E>>>8}}function f8(A,Q){let B=A.length,C=0;for(;C<B;)Q[C]=A.charCodeAt(C++)}var c,u8=()=>{return A="AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQuFDAEKf0EAQQAoArAKIgBBDGoiATYCsApBARApIQJBACgCsAohAwJAAkACQAJAAkACQAJAAkAgAkEuRw0AQQAgA0ECajYCsAoCQEEBECkiAkHkAEYNAAJAIAJB8wBGDQAgAkHtAEcNB0EAKAKwCiICQQJqQZwIQQYQLw0HAkBBACgCnAoiAxAqDQAgAy8BAEEuRg0ICyAAIAAgAkEIakEAKALUCRABDwtBACgCsAoiAkECakGiCEEKEC8NBgJAQQAoApwKIgMQKg0AIAMvAQBBLkYNBwtBACEEQQAgAkEMajYCsApBASEFQQUhBkEBECkhAkEAIQdBASEIDAILQQAoArAKIgIpAAJC5YCYg9CMgDlSDQUCQEEAKAKcCiIDECoNACADLwEAQS5GDQYLQQAhBEEAIAJBCmo2ArAKQQIhCEEHIQZBASEHQQEQKSECQQEhBQwBCwJAAkACQAJAIAJB8wBHDQAgAyABTQ0AIANBAmpBoghBChAvDQACQCADLwEMIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAgsgBEGgAUYNAQtBACEHQQchBkEBIQQgAkHkAEYNAQwCC0EAIQRBACADQQxqIgI2ArAKQQEhBUEBECkhCQJAQQAoArAKIgYgAkYNAEHmACECAkAgCUHmAEYNAEEFIQZBACEHQQEhCCAJIQIMBAtBACEHQQEhCCAGQQJqQawIQQYQLw0EIAYvAQgQIEUNBAtBACEHQQAgAzYCsApBByEGQQEhBEEAIQVBACEIIAkhAgwCCyADIABBCmpNDQBBACEIQeQAIQICQCADKQACQuWAmIPQjIA5Ug0AAkACQCADLwEKIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAQtBACEIIARBoAFHDQELQQAhBUEAIANBCmo2ArAKQSohAkEBIQdBAiEIQQEQKSIJQSpGDQRBACADNgKwCkEBIQRBACEHQQAhCCAJIQIMAgsgAyEGQQAhBwwCC0EAIQVBACEICwJAIAJBKEcNAEEAKAKkCkEALwGYCiICQQN0aiIDQQAoArAKNgIEQQAgAkEBajsBmAogA0EFNgIAQQAoApwKLwEAQS5GDQRBAEEAKAKwCiIDQQJqNgKwCkEBECkhAiAAQQAoArAKQQAgAxABAkACQCAFDQBBACgC8AkhAQwBC0EAKALwCSIBIAY2AhwLQQBBAC8BlgoiA0EBajsBlgpBACgCqAogA0ECdGogATYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKwCkF+ajYCsAoPCyACEBpBAEEAKAKwCkECaiICNgKwCgJAAkACQEEBEClBV2oOBAECAgACC0EAQQAoArAKQQJqNgKwCkEBECkaQQAoAvAJIgMgAjYCBCADQQE6ABggA0EAKAKwCiICNgIQQQAgAkF+ajYCsAoPC0EAKALwCSIDIAI2AgQgA0EBOgAYQQBBAC8BmApBf2o7AZgKIANBACgCsApBAmo2AgxBAEEALwGWCkF/ajsBlgoPC0EAQQAoArAKQX5qNgKwCg8LAkAgBEEBcyACQfsAR3INAEEAKAKwCiECQQAvAZgKDQUDQAJAAkACQCACQQAoArQKTw0AQQEQKSICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKwCkECajYCsAoLQQEQKSEDQQAoArAKIQICQCADQeYARw0AIAJBAmpBrAhBBhAvDQcLQQAgAkEIajYCsAoCQEEBECkiAkEiRg0AIAJBJ0cNBwsgACACQQAQKw8LIAIQGgtBAEEAKAKwCkECaiICNgKwCgwACwsCQAJAIAJBWWoOBAMBAQMACyACQSJGDQILQQAoArAKIQYLIAYgAUcNAEEAIABBCmo2ArAKDwsgAkEqRyAHcQ0DQQAvAZgKQf//A3ENA0EAKAKwCiECQQAoArQKIQEDQCACIAFPDQECQAJAIAIvAQAiA0EnRg0AIANBIkcNAQsgACADIAgQKw8LQQAgAkECaiICNgKwCgwACwsQJQsPC0EAIAJBfmo2ArAKDwtBAEEAKAKwCkF+ajYCsAoLRwEDf0EAKAKwCkECaiEAQQAoArQKIQECQANAIAAiAkF+aiABTw0BIAJBAmohACACLwEAQXZqDgQBAAABAAsLQQAgAjYCsAoLmAEBA39BAEEAKAKwCiIBQQJqNgKwCiABQQZqIQFBACgCtAohAgNAAkACQAJAIAFBfGogAk8NACABQX5qLwEAIQMCQAJAIAANACADQSpGDQEgA0F2ag4EAgQEAgQLIANBKkcNAwsgAS8BAEEvRw0CQQAgAUF+ajYCsAoMAQsgAUF+aiEBC0EAIAE2ArAKDwsgAUECaiEBDAALC4gBAQR/QQAoArAKIQFBACgCtAohAgJAAkADQCABIgNBAmohASADIAJPDQEgAS8BACIEIABGDQICQCAEQdwARg0AIARBdmoOBAIBAQIBCyADQQRqIQEgAy8BBEENRw0AIANBBmogASADLwEGQQpGGyEBDAALC0EAIAE2ArAKECUPC0EAIAE2ArAKC2wBAX8CQAJAIABBX2oiAUEFSw0AQQEgAXRBMXENAQsgAEFGakH//wNxQQZJDQAgAEEpRyAAQVhqQf//A3FBB0lxDQACQCAAQaV/ag4EAQAAAQALIABB/QBHIABBhX9qQf//A3FBBElxDwtBAQsuAQF/QQEhAQJAIABBpglBBRAdDQAgAEGWCEEDEB0NACAAQbAJQQIQHSEBCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALcCSIFSQ0AIAAgASACEC8NAAJAIAAgBUcNAEEBDwsgBBAmIQMLIAMLgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQbwJQQYQHQ8LIABBfmovAQBBPUYPCyAAQX5qQbQJQQQQHQ8LIABBfmpByAlBAxAdDwtBACEBCyABC7QDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQAJAIAAvAQBBnH9qDhQAAQIJCQkJAwkJBAUJCQYJBwkJCAkLAkACQCAAQX5qLwEAQZd/ag4EAAoKAQoLIABBfGpByghBAhAdDwsgAEF8akHOCEEDEB0PCwJAAkACQCAAQX5qLwEAQY1/ag4DAAECCgsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCiAAQXpqQeUAECcPCyAAQXpqQeMAECcPCyAAQXxqQdQIQQQQHQ8LIABBfGpB3AhBBhAdDwsgAEF+ai8BAEHvAEcNBiAAQXxqLwEAQeUARw0GAkAgAEF6ai8BACICQfAARg0AIAJB4wBHDQcgAEF4akHoCEEGEB0PCyAAQXhqQfQIQQIQHQ8LIABBfmpB+AhBBBAdDwtBASEBIABBfmoiAEHpABAnDQQgAEGACUEFEB0PCyAAQX5qQeQAECcPCyAAQX5qQYoJQQcQHQ8LIABBfmpBmAlBBBAdDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECcPCyAAQXxqQaAJQQMQHSEBCyABCzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAEChxIQELIAELMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC04BAn9BACEBAkACQCAALwEAIgJB5QBGDQAgAkHrAEcNASAAQX5qQfgIQQQQHQ8LIABBfmovAQBB9QBHDQAgAEF8akHcCEEGEB0hAQsgAQveAQEEf0EAKAKwCiEAQQAoArQKIQECQAJAAkADQCAAIgJBAmohACACIAFPDQECQAJAAkAgAC8BACIDQaR/ag4FAgMDAwEACyADQSRHDQIgAi8BBEH7AEcNAkEAIAJBBGoiADYCsApBAEEALwGYCiICQQFqOwGYCkEAKAKkCiACQQN0aiICQQQ2AgAgAiAANgIEDwtBACAANgKwCkEAQQAvAZgKQX9qIgA7AZgKQQAoAqQKIABB//8DcUEDdGooAgBBA0cNAwwECyACQQRqIQAMAAsLQQAgADYCsAoLECULC3ABAn8CQAJAA0BBAEEAKAKwCiIAQQJqIgE2ArAKIABBACgCtApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQLhoMAQtBACAAQQRqNgKwCgwACwsQJQsLNQEBf0EAQQE6APwJQQAoArAKIQBBAEEAKAK0CkECajYCsApBACAAQQAoAtwJa0EBdTYCkAoLQwECf0EBIQECQCAALwEAIgJBd2pB//8DcUEFSQ0AIAJBgAFyQaABRg0AQQAhASACEChFDQAgAkEuRyAAECpyDwsgAQs9AQJ/QQAhAgJAQQAoAtwJIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC5wBAQN/QQAoArAKIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBAYDAILIAAQGQwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQIUUNAwwBCyACQaABRw0CC0EAQQAoArAKIgNBAmoiATYCsAogA0EAKAK0CkkNAAsLIAILMQEBf0EAIQECQCAALwEAQS5HDQAgAEF+ai8BAEEuRw0AIABBfGovAQBBLkYhAQsgAQumBAEBfwJAIAFBIkYNACABQSdGDQAQJQ8LQQAoArAKIQMgARAaIAAgA0ECakEAKAKwCkEAKALQCRABAkAgAkEBSA0AQQAoAvAJQQRBBiACQQFGGzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=",typeof Buffer<"u"?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(Q)=>Q.charCodeAt(0));var A},iC=WebAssembly.compile(u8()).then(WebAssembly.instantiate).then(({exports:A})=>{c=A});var m8=/\.m?js$/i;function gB(A){return/^src\//i.test(A)&&m8.test(A)}function GK(A){return gB(A.entry||"")}function p8(A){let Q=A.lastIndexOf("/");return(Q<0?"":A.slice(0,Q)).split("/").filter(Boolean)}function c8(A,Q){let B=p8(A);for(let C of Q.split("/"))if(C===""||C===".")continue;else if(C==="..")B.pop();else B.push(C);return B.join("/")}async function XK(A){await iC;let Q={};for(let[K,J]of A.files)if(gB(K))Q[K]=new TextDecoder().decode(J);let B=(K)=>Object.prototype.hasOwnProperty.call(Q,K),C=(K,J)=>{let Y=c8(K,J);if(B(Y))return Y;if(B(Y+".js"))return Y+".js";if(B(Y+".mjs"))return Y+".mjs";if(B(Y+"/index.js"))return Y+"/index.js";return Y},E={};for(let[K,J]of Object.entries(Q))E[K]=l8(J,K,C);return{modules:E,entry:A.manifest.entry}}function l8(A,Q,B){let[C]=sC(A),E="",K=0;for(let J of C){if(J.n==null)continue;if(J.n[0]!==".")continue;let Y="trove:/"+B(Q,J.n),I=J.d===-1?Y:JSON.stringify(Y);E+=A.slice(K,J.s)+I,K=J.e}return E+A.slice(K)}var d8=15000;class rC{constructor({media:A,dock:Q}={}){this.media=A,this.dock=Q}async spawn(A,Q,B){let C=document.createElement("iframe");C.style.cssText=n8,C.setAttribute("sandbox","allow-scripts allow-forms"),C.setAttribute("referrerpolicy","no-referrer");let E=B?.entry;if(E)A._entrySrcdoc||={},A._entrySrcdoc[E]||=await HK({...A.manifest,entry:E},A.files),C.srcdoc=A._entrySrcdoc[E];else A._srcdoc||=await HK(A.manifest,A.files),C.srcdoc=A._srcdoc;let K={role:Q,iframe:C,channel:null,record:A,place:null,dock:null,mediaActions:null};document.body.appendChild(C);try{await this.#A(A,K,B)}catch(J){try{K.channel?.dispose()}catch{}throw C.remove(),J}return K}#A(A,Q,{onCall:B,onEvent:C,online:E}){return new Promise((K,J)=>{let{iframe:Y}=Q,I=A.manifest,D=!1,L=0,G=()=>{if(window.removeEventListener("message",Z),L)clearTimeout(L)},X=(R)=>{if(D)return;D=!0,G(),J(Error(R))},Z=(R)=>{if(R.source!==Y.contentWindow)return;if(R.data?.__trove==="boot-error")return X(R.data.error||"Plugin failed to load its modules");if(R.data?.__trove!=="ready")return;if(!LK(R.data.protocolVersion))return X(`Plugin speaks protocol ${R.data.protocolVersion}, this host speaks ${aC}`);window.removeEventListener("message",Z);let F=new MessageChannel;Q.channel=new nC(F.port1,{onCall:(V,g)=>B(A,V,g,Q),onEvent:(V,g)=>C(A,V,g,Q)}),Q.resolveActivated=(V)=>{if(D)return;if(D=!0,L)clearTimeout(L);K(V)},Q.rejectActivated=(V)=>{if(D)return;if(D=!0,L)clearTimeout(L);J(V)},Y.contentWindow.postMessage({__trove:"init",manifest:I,capabilities:A.grants,storage:A.storage,online:E,role:Q.role,protocolVersion:aC},"*",[F.port2])};L=setTimeout(()=>X("Plugin handshake timed out"),d8),window.addEventListener("message",Z),Y.addEventListener("error",()=>X("Failed to load plugin iframe"))})}destroy(A){if(!A)return;this.dock?.releaseFrame(A),this.media?.releaseFrame(A);try{A.channel?.emit("deactivate")}catch{}try{A.channel?.dispose()}catch{}A.iframe.remove(),A.record?.frames?.delete(A)}}var n8="position:fixed;left:0;top:0;width:0;height:0;border:0;visibility:hidden;",o8=["default-src 'none'","script-src 'unsafe-inline' 'unsafe-eval' blob:","style-src 'unsafe-inline'","img-src blob: data:","media-src blob: data:","font-src 'none'","connect-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),ZK=`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${o8}"></head><body>`;async function HK(A,Q){if(GK(A))return a8(await XK({manifest:A,files:Q}));let B=new TextDecoder().decode(Q.get(A.entry)??new Uint8Array);return`${ZK}
|
|
323
|
+
<script>${oC}</script>
|
|
324
|
+
<script>${B}</script>
|
|
325
|
+
</body></html>`}function $K(A){return JSON.stringify(A).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function a8(A){let Q=$K("trove:/"+A.entry);return`${ZK}
|
|
326
|
+
<script>${oC}</script>
|
|
327
|
+
<script id="__trove_src" type="application/json">${$K(A.modules)}</script>
|
|
328
|
+
<script>
|
|
329
|
+
(function () {
|
|
330
|
+
var src = JSON.parse(document.getElementById('__trove_src').textContent);
|
|
331
|
+
var imports = {};
|
|
332
|
+
for (var p in src) imports['trove:/' + p] = URL.createObjectURL(new Blob([src[p] + '\\n//# sourceURL=trove:/' + p], { type: 'text/javascript' }));
|
|
333
|
+
imports['trove'] = URL.createObjectURL(new Blob(['export const activate = globalThis.trove.activate;\\nexport default globalThis.trove;'], { type: 'text/javascript' }));
|
|
334
|
+
var im = document.createElement('script');
|
|
335
|
+
im.type = 'importmap';
|
|
336
|
+
im.textContent = JSON.stringify({ imports: imports });
|
|
337
|
+
document.head.appendChild(im);
|
|
338
|
+
import(${Q}).catch(function (e) {
|
|
339
|
+
try { parent.postMessage({ __trove: 'boot-error', error: String((e && e.message) || e) }, '*'); } catch (_) {}
|
|
340
|
+
});
|
|
341
|
+
})();
|
|
342
|
+
</script>
|
|
343
|
+
</body></html>`}var s8=/\b(ATTACH|DETACH|VACUUM|PRAGMA)\b/i;function i8(A){let Q="",B=0;while(B<A.length){let C=A[B];if(C==="-"&&A[B+1]==="-"){let E=A.indexOf(`
|
|
344
|
+
`,B);B=E<0?A.length:E;continue}if(C==="/"&&A[B+1]==="*"){let E=A.indexOf("*/",B+2);B=E<0?A.length:E+2,Q+=" ";continue}if(C==="'"||C==='"'||C==="`"){let E=C;B++;while(B<A.length){if(A[B]===E){if(A[B+1]===E){B+=2;continue}B++;break}B++}Q+=" ";continue}if(C==="["){let E=A.indexOf("]",B);B=E<0?A.length:E+1,Q+=" ";continue}Q+=C,B++}return Q}function tC(A){if(typeof A!=="string"||!A)throw P.invalid("SQL statement is required");if(s8.test(i8(A)))throw P.invalid("ATTACH, DETACH, VACUUM and PRAGMA are not permitted in plugin storage")}var r8=26214400;async function t8(A,Q){let B=Number(A.headers.get("content-length")||0);if(B&&B>Q)throw Error("Response too large");let C=A.body?.getReader?.();if(!C){let I=await A.arrayBuffer();if(I.byteLength>Q)throw Error("Response too large");return I}let E=[],K=0;for(;;){let{done:I,value:D}=await C.read();if(I)break;if(K+=D.byteLength,K>Q)throw await C.cancel().catch(()=>{}),Error("Response too large");E.push(D)}let J=new Uint8Array(K),Y=0;for(let I of E)J.set(I,Y),Y+=I.byteLength;return J.buffer}class eC{constructor({platform:A,clientDb:Q,media:B,dock:C,onChange:E}={}){this.platform=A,this.clientDb=Q,this.media=B,this.dock=C,this.onChange=E||(()=>{})}async hostCall(A,Q,B,C){let E=(J)=>{if(!A.grants.includes(J))throw Error(`Capability "${J}" not granted`)},K=A.id;switch(Q){case"activated":{let J=C||A.frame;if(clearTimeout(J?._timer),B.ok)J?.resolveActivated?.(J);else J?.rejectActivated?.(Error(B.error||"activate() failed"));return{ok:!0}}case"command:execute":{let J=this.#A(A,B.id);if(!xB(A.manifest,J))throw Error(`Command "${B.id}" is not in this plugin's declared commands`);return{ok:!0,result:await this.platform.commands.execute(J,...B.args||[])??null}}case"ui:status":{E("ui");let J=this.#Q(A,B.name,"statusItem");return this.platform.contributions.update(J.uri,{...B.html!==void 0?{html:String(B.html??"")}:{},...B.tooltip!==void 0?{tooltip:String(B.tooltip??"")}:{},...B.visible!==void 0?{visible:!!B.visible}:{visible:!0}}),{ok:!0}}case"context:setRegister":{let J=this.#Q(A,B.name,"register");return this.platform.context.set(J.uri,B.value),{ok:!0}}case"resources:list":return[...A.files.keys()].filter(WK);case"resources:read":{if(!WK(B.path))throw Error(`No such resource ${B.path}`);let J=A.files.get(B.path);if(!J)throw Error(`No such resource ${B.path}`);return{bytes:J.slice().buffer}}case"files:read":return E("files"),{text:await this.platform.api.readText(B.id)};case"files:list":return E("files"),this.platform.api.list({collection:B.collection||B.pathOrId||void 0,sort:B.sort,order:B.order,limit:B.limit,cursor:B.cursor});case"files:stat":return E("files"),this.platform.api.stat(B.id);case"files:downloadUrl":return E("files"),{url:this.platform.api.downloadUrl(B.id)};case"files:index":{E("indexer");let J=QQ(B.indexerId)?B.indexerId:AQ(A.manifest,B.indexerId||"default");return this.platform.api.pushIndex(J,B.nodeId,{semanticTexts:B.semanticTexts,tags:B.tags,metadata:B.metadata,documents:B.documents,facet:B.facet})}case"net:fetch":return E("network"),this.#C(A,B);case"storage:sql":return E("storage"),this.#E(A,B);case"settings:get":return this.platform.settings.get(`${K}.${B.key}`);case"settings:getSecret":return A.secrets?.[B.key]??null;case"settings:set":return this.platform.settings.set(`${K}.${B.key}`,B.value),{ok:!0};case"ui:showPanel":return E("ui"),A.hasUi=!0,this.platform.openPluginPanel?.(K),this.onChange(),{ok:!0};case"media:metadata":{E("media");let J=(B.artwork||[]).filter((Y)=>this.#B(A,Y?.src));return this.media.apply(C,"metadata",{...B,artwork:J})}case"media:playbackState":return E("media"),this.media.apply(C,"playbackState",B);case"media:position":return E("media"),this.media.apply(C,"position",B);case"media:action":return E("media"),this.media.apply(C,"action",B);case"media:clear":return this.media.apply(C,"clear",B);case"dock:enable":if(E("dock"),C)C.dock={enabled:!0,minSize:B.minSize,maxSize:B.maxSize,dismissed:!1};return{ok:!0};case"dock:disable":if(E("dock"),C?.dock)C.dock.enabled=!1;if(C&&this.dock.docked===C)this.dock.closeDock(C);return{ok:!0};case"dock:close":if(C)this.dock.closeDock(C);return{ok:!0};default:throw Error(`Unknown host method ${Q}`)}}hostEvent(A,Q,B,C){switch(Q){case"manifest":if(C&&C.role!=="primary")break;A.live=B,A.responsive=!0,this.onChange();break;case"ui:toast":this.platform.notifications[B.level||"info"](`${OA(A.manifest)}: ${B.text}`);break;case"ui:badge":A.badge=B.text,this.onChange();break}}#A(A,Q){if(!Q||QQ(Q))return Q;let B=this.platform.contributions.get(AQ(A.manifest,Q));return B?.type==="command"?B.uri:Q}#Q(A,Q,B){let C=Q?this.platform.contributions.get(AQ(A.manifest,Q)):null;if(!C||C.pluginId!==A.id||C.type!==B)throw Error(`"${Q}" is not a ${B} declared by this plugin`);return C}#B(A,Q){if(!Q)return!1;if(/^(blob:|data:image\/)/i.test(Q))return!0;return _B(HQ(A.manifest),Q)}async#C(A,{url:Q,method:B="GET",headers:C,body:E}){let K=HQ(A.manifest);if(UK(Q,this.platform.api?.baseUrl))throw Error("Blocked: a plugin may not call the drive's own API through the network broker");if(!_B(K,Q))throw Error(`Blocked: "${Q}" is not one of this plugin's declared network endpoints`);let J={method:B,credentials:"omit",redirect:"follow",headers:AD(C)};if(E!=null&&B!=="GET"&&B!=="HEAD")J.body=E instanceof ArrayBuffer?new Uint8Array(E):E;let Y=await fetch(Q,J);if(Y.url&&Y.url!==Q){if(UK(Y.url,this.platform.api?.baseUrl))throw Error("Blocked: request redirected onto the drive's own API");if(!_B(K,Y.url))throw Error(`Blocked: request redirected off this plugin's declared endpoints (${Y.url})`)}let I=await t8(Y,r8),D={};return Y.headers.forEach((L,G)=>{D[G]=L}),{ok:Y.ok,status:Y.status,statusText:Y.statusText,url:Y.url,headers:D,bytes:I}}async#E(A,{scope:Q="plugin",side:B="server",op:C,sql:E,params:K=[],statements:J}){if(!A.storage?.[Q])throw Error(`Storage scope "${Q}" not granted${Q==="domain"?" (needs a verified domain)":""}`);if(B==="client"){if(C==="batch")for(let G of Array.isArray(J)?J:[])tC(G?.sql);else tC(E);let D=Q==="domain"?`dom:${A.manifest.domain}`:`plg:${A.id}`,L=await this.clientDb.obtain(D);return QD(L,C,E,K,J)}let Y={scope:Q,op:C,sql:E,params:K,statements:J,domain:Q==="domain"?A.manifest.domain:void 0};return(await this.platform.api.request("POST",`/api/plugins/${encodeURIComponent(A.id)}/sql`,{body:Y})).result}}function UK(A,Q){try{let B=new URL(Q||"",globalThis.location?.href||"http://localhost/");return new URL(A,B).origin===B.origin}catch{return!1}}function WK(A){return A!=="manifest.json"&&!gB(A)}var e8=new Set(["host","cookie","cookie2","set-cookie","origin","referer","content-length","connection"]);function AD(A){let Q={};for(let[B,C]of Object.entries(A||{}))if(!e8.has(String(B).toLowerCase()))Q[B]=C;return Q}function QD(A,Q,B,C=[],E){switch(Q){case"exec":return A.exec(B);case"run":return A.run(B,...C);case"get":return A.get(B,...C);case"all":return A.all(B,...C);case"batch":return A.batch(E);default:throw Error(`Unknown storage op "${Q}"`)}}var RK=["files","storage","ui","commands","indexer","opener","network","media","dock"];class A0{constructor(A,{heartbeatMs:Q=20000}={}){this.platform=A,this.plugins=new Map,this.registry=new gC,this.clientDb=new hC({onError:(B,C)=>this.platform.notifications.error(`A plugin's on-device data couldn't be saved (${C}): ${B.message}`)}),this.online=typeof navigator<"u"?navigator.onLine:!0,this.heartbeatMs=Q,this._heartbeat=null,this._probing=!1,this.cell=A.reactive.cell([]),this.media=new lC,this.dock=new dC({destroyFrame:(B)=>this.frames.destroy(B),openFile:(B,C)=>this.platform.workbench.openFile(B,C),onChange:()=>this.#A()}),this.frames=new rC({media:this.media,dock:this.dock}),this.rpc=new eC({platform:A,clientDb:this.clientDb,media:this.media,dock:this.dock,onChange:()=>this.#A()})}observe(){return this.cell}#A(){this.cell.setValue(this.list())}#Q(A,Q,B){return this.frames.spawn(A,Q,{onCall:(C,E,K,J)=>this.rpc.hostCall(C,E,K,J),onEvent:(C,E,K,J)=>this.rpc.hostEvent(C,E,K,J),online:this.online,entry:B})}#B(A){let Q=A.id,B=this.platform.contributions,C=(K)=>A.disposers.push(K),E=OA(A.manifest);for(let K of cA(A.manifest)){let J={...K,pluginId:Q};switch(K.type){case"opener":if(A.grants.includes("opener"))C(B.register(K.uri,J));break;case"command":C(this.platform.commands.register({id:K.uri,title:K.title||`${E}: ${K.name}`,category:K.category||E,icon:K.icon,when:K.when,offline:K.offline,palette:K.palette,pluginId:Q,handler:(...Y)=>A.channel?.call("command:execute",{id:K.name,args:Y})}));break;case"statusItem":{let Y=K.command?this.#E(A,K.command,E,`status item “${K.name}”`):null;C(B.register(K.uri,{...J,command:Y,html:"",visible:!1}));break}case"register":C(B.register(K.uri,J)),this.platform.context.set(K.uri,K.default),C(()=>this.platform.context.remove(K.uri));break;case"keymap":{let Y=A.files.get(K.path);if(!Y){this.platform.notifications.warn(`Plugin "${E}": keymap file "${K.path}" is not in the package.`);break}try{let I=this.#C(A,zE(new TextDecoder().decode(Y)),E);C(B.register(K.uri,{...J,bindings:I}))}catch(I){this.platform.notifications.warn(`Plugin "${E}": ${I.message}`)}break}case"indexer":break}}}#C(A,Q,B){let C=[];for(let E of Q){let K=this.#E(A,E.command,B,`shortcut ${E.key}`);if(K)C.push({...E,command:K})}return C}#E(A,Q,B,C){let E=AQ(A.manifest,Q);if(cA(A.manifest).some((J)=>J.uri===E&&J.type==="command"))return E;if(!xB(A.manifest,Q))return this.platform.notifications.warn(`Plugin "${B}": ${C} runs "${Q}", which it isn't allowed to run — ignored.`),null;return Q}list(){return[...this.plugins.values()].map((A)=>({id:A.id,name:OA(A.manifest),version:A.manifest.version,status:A.status,capabilities:A.grants,error:A.error||null,hasUi:A.hasUi,badge:A.badge||null,trust:A.trust||null,settingsSchema:A.manifest.settings||[],endpoints:kB(HQ(A.manifest)),responsive:!!A.responsive,manifest:A.live||null,features:this.#K(A)}))}#K(A){let Q;try{Q=cA(A.manifest)}catch{return[]}return Q.map((B)=>({kind:B.type,id:B.uri,name:B.name,title:B.title||B.name,offline:!!B.offline,available:this.#J(A,B)}))}#J(A,Q){if(A.status!=="active"||!A.responsive)return!1;return this.online||!!Q.offline}isAvailable(A){if(!A?.pluginId)return!0;let Q=this.plugins.get(A.pluginId);if(!Q)return!1;return this.#J(Q,A)}canGrant(A,Q){return!uC.has(A)||!!Q}async install(A,{grants:Q,trust:B}={}){let C=yA(A.manifest),E=mC(A.manifest),K=(Q||E).filter((D)=>RK.includes(D)&&E.includes(D)),J=ED(A.manifest,K)?"account":"device";if(J==="account"){if(!A.raw)throw Error("Package bytes unavailable for a server install");await this.platform.api.installPlugin(A.raw,K)}let Y=K.includes("storage")?cC(A.manifest,B):{plugin:!1,domain:!1},I={id:C,manifest:A.manifest,files:Object.fromEntries([...A.files.entries()]),grants:K,storage:Y,trust:B||null,scope:J,settings:{},secrets:{},installedAt:Date.now()};return await this.registry.save(I),this.#I(I),await this.#L(I),this.plugins.get(C)}async restore(){let A=[];try{A=await this.registry.list()}catch{}for(let Q of A)try{this.#I(Q),this.#L(Q).catch((B)=>console.error("restore plugin failed",Q.id,B))}catch(B){console.error("skipping corrupt plugin record",Q?.id,B),this.platform.notifications.warn(`Couldn't restore plugin "${Q?.manifest?OA(Q.manifest):Q?.id||"unknown"}" — its saved data looks corrupt.`)}this.#Y(A).catch(()=>{})}async#Y(A){let Q;try{Q=(await this.platform.api.installedPlugins()).plugins||[]}catch{return}let B=new Set(Q.map((Y)=>Y.pluginId)),C=new Set(A.map((Y)=>Y.id)),E=0,K=0,J=0;for(let Y of A){if(Y.scope!=="account"||B.has(Y.id))continue;try{await this.platform.api.installPlugin(oE(CD(Y.files)),Y.grants||[])}catch(I){console.error("re-upload plugin failed",Y.id,I),E++}}for(let Y of Q){if(C.has(Y.pluginId))continue;try{let I=$Q(await this.platform.api.pluginPackage(Y.pluginId)),D=Y.grants||[],L={id:Y.pluginId,manifest:I.manifest,files:Object.fromEntries([...I.files.entries()]),grants:D,storage:D.includes("storage")?{plugin:!0,domain:!!Y.sharedStorage}:{plugin:!1,domain:!1},trust:null,scope:"account",settings:{},secrets:{},installedAt:Y.createdAt||Date.now()};await this.registry.save(L),this.#I(L),await this.#L(L),K++}catch(I){console.error("sync plugin failed",Y.pluginId,I),J++}}if(K)this.platform.notifications.info(`Synced ${K} account plugin${K>1?"s":""} from the server.`);if(E||J){let Y=[];if(J)Y.push(`${J} couldn't be downloaded`);if(E)Y.push(`${E} couldn't be uploaded`);this.platform.notifications.warn(`Some account plugins didn't sync: ${Y.join(", ")}.`)}}#I(A){let Q=(A.manifest.settings||[]).filter((B)=>!B.secret);if(Q.length)A._settingsDispose=this.platform.settings.scopedFor(A.id).register(Q.map((B)=>({...B,category:OA(A.manifest)})))}async#L(A){if(this.plugins.get(A.id)?.status==="active")return;let Q={...A,iframe:null,status:"loading",error:null,disposers:[],channel:null,hasUi:!1,responsive:!1,frame:null,frames:new Set,storage:A.storage||(A.grants?.includes("storage")?cC(A.manifest,A.trust):{plugin:!1,domain:!1}),files:BD(A.files)};this.plugins.set(A.id,Q);try{this.#B(Q)}catch(B){console.error("registering contributions failed",A.id,B)}this.#A();try{let B=await this.#Q(Q,"primary");if(this.plugins.get(A.id)!==Q)return this.frames.destroy(B),Q;Q.frame=B,Q.iframe=B.iframe,Q.channel=B.channel,Q.status="active",Q.responsive=!0,this.#G(Q).then(()=>this.#A()),this.#D()}catch(B){Q.status="error",Q.error=B?.message||String(B),this.platform.notifications.error(`Plugin "${OA(A.manifest)}" failed to load: ${Q.error}`)}return this.#A(),Q}async setSecret(A,Q,B){let C=await this.registry.get(A);if(!C)return;C.secrets={...C.secrets,[Q]:B},await this.registry.save(C);let E=this.plugins.get(A);if(E)E.secrets=C.secrets;E?.channel?.emit("settings:changed",{key:Q,value:"••••"})}async getSecret(A,Q){return(await this.registry.get(A))?.secrets?.[Q]??""}#D(){if(this._heartbeat||!this.heartbeatMs)return;if(this._heartbeat=setInterval(()=>this.#$(),this.heartbeatMs),this._heartbeat?.unref)this._heartbeat.unref()}#X(){if(this._heartbeat)clearInterval(this._heartbeat);this._heartbeat=null}async#$(){if(this._probing)return;this._probing=!0;try{let A=!1;for(let Q of this.plugins.values())if(Q.status==="active")A=await this.#G(Q)||A;if(A)this.#A()}finally{this._probing=!1}}setHeartbeat(A){if(this.heartbeatMs=A,this.#X(),A&&[...this.plugins.values()].some((Q)=>Q.status==="active"))this.#D()}async#G(A){if(A.status!=="active"||!A.channel)return!1;let Q={responsive:A.responsive,sig:FK(A.live)};try{A.live=await A.channel.call("manifest",{},{timeout:4000}),A.responsive=!0}catch{A.responsive=!1}return Q.responsive!==A.responsive||Q.sig!==FK(A.live)}async setOnline(A){if(this.online===A)return;this.online=A,await Promise.all([...this.plugins.values()].filter((Q)=>Q.status==="active").map(async(Q)=>{try{Q.channel?.emit("connectivity",{online:A})}catch{}for(let B of Q.frames||[])try{B.channel?.emit("connectivity",{online:A})}catch{}await this.#G(Q)})),this.#A()}async refresh(A){let Q=this.plugins.get(A);if(Q)await this.#G(Q),this.#A()}mountPanel(A,Q,{width:B=380,height:C=480}={}){let E=this.plugins.get(A);if(!E?.frame)return null;return Q.style.width=`${B}px`,Q.style.height=`${C}px`,this.dock.place(E.frame,Q,50),E.hasUi=!0,()=>this.dock.hide(E.frame)}mountViewer(A,Q,B,C,E={}){let K=this.plugins.get(A);if(!K)return E.onError?.("Plugin is not available"),null;let J=this.dock.docked;if(J&&J.record===K&&J.node?.id===B.id&&J.openerId===C)return this.dock.undock(J),this.dock.place(J,Q,3),E.onReady?.(),()=>this.#H(J);let Y=this.platform.contributions.get(C),I={cancelled:!1,frame:null};return this.#Q(K,"viewer",Y?.entry).then(async(D)=>{if(I.cancelled){this.frames.destroy(D);return}I.frame=D,D.node=B,D.openerId=C,K.frames.add(D),this.dock.place(D,Q,3);try{if(await D.channel?.call("opener:open",{openerId:C,file:B,context:{}}),!I.cancelled)E.onReady?.()}catch(L){if(!I.cancelled)E.onError?.(L?.message||"Failed to open")}}).catch((D)=>{if(console.error("viewer frame failed to load",D),!I.cancelled)E.onError?.(D?.message||"This viewer failed to load")}),K.hasUi=!0,()=>{if(I.cancelled=!0,I.frame)this.#H(I.frame)}}#H(A){if(A.dock?.enabled&&!A.dock.dismissed)this.dock.dock(A);else this.frames.destroy(A)}async uninstall(A,{wipeData:Q=!0}={}){let B=this.plugins.get(A),C=B?.manifest?OA(B.manifest):A,E=B?.scope==="account"||(await this.registry.get(A).catch(()=>null))?.scope==="account";if(Q&&E)try{await this.platform.api.uninstallPluginServer(A)}catch(Y){this.platform.notifications.error(`Couldn't uninstall "${C}" from the server: ${Y.message}. It's still installed.`);return}if(B){try{B.channel?.emit("deactivate")}catch{}for(let Y of B.disposers)try{Y()}catch{}B._settingsDispose?.();for(let Y of[...B.frames||[]])this.frames.destroy(Y);if(B.frame)this.dock.stopPlace(B.frame),this.media.releaseActions(B.frame);B.channel?.dispose(),B.iframe?.remove(),this.plugins.delete(A)}let K=[];if(Q){if(!E)await this.platform.api.request("DELETE",`/api/plugins/${encodeURIComponent(A)}/data`).catch(()=>K.push("server-side data"));await this.clientDb.drop(`plg:${A}`).catch(()=>K.push("on-device data"))}let J=!1;try{await this.registry.remove(A)}catch(Y){J=!0,console.error("removing the persisted plugin record failed",A,Y)}if(![...this.plugins.values()].some((Y)=>Y.status==="active"))this.#X();if(this.#A(),J)this.platform.notifications.error(`Removed "${C}", but its saved record couldn't be deleted — it may come back when you reload.`);else if(K.length)this.platform.notifications.warn(`Uninstalled "${C}", but couldn't clear its ${K.join(" and ")}.`)}fetchAssetlinks=async(A)=>{return(await this.platform.api.request("GET","/api/plugins/assetlinks",{query:{domain:A}}))?.assetlinks||null};assessTrust(A){return AK(A,this.fetchAssetlinks)}}function BD(A){let Q=new Map;for(let[B,C]of Object.entries(A))Q.set(B,C instanceof Uint8Array?C:new Uint8Array(C));return Q}function CD(A){let Q={};for(let[B,C]of Object.entries(A||{}))Q[B]=C instanceof Uint8Array?C:new Uint8Array(C);return Q}function ED(A,Q){if(Q.includes("storage"))return!0;return XC(A).length>0}function FK(A){if(!A)return"";return`${A.online?1:0}|${[...A.handlers||[]].sort().join(",")}`}class Q0{constructor(A){this.context=A,this.state={palette:null,dialog:null,contextMenu:null,pluginPanel:null},this.cell=f(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}openPalette(A="commands",Q=""){this.#A({palette:{mode:A,query:Q,index:0}}),this.context.set("palette.open",!0)}setPaletteQuery(A){if(this.state.palette)this.#A({palette:{...this.state.palette,query:A,index:0}})}movePalette(A,Q){if(!this.state.palette||!Q)return;this.#A({palette:{...this.state.palette,index:B0(this.state.palette.index,A,Q)}})}setPaletteIndex(A){if(this.state.palette)this.#A({palette:{...this.state.palette,index:A}})}closePalette(){this.#A({palette:null}),this.context.set("palette.open",!1)}showDialog(A){this.#A({dialog:A})}updateDialog(A){if(this.state.dialog)this.#A({dialog:{...this.state.dialog,...A}})}closeDialog(){this.#A({dialog:null})}showContextMenu(A,Q,B){this.#A({contextMenu:{x:A,y:Q,items:B}})}closeContextMenu(){this.#A({contextMenu:null})}openPluginPanel(A){this.#A({pluginPanel:A})}closePluginPanel(){this.#A({pluginPanel:null})}}function B0(A,Q,B){return(A+Q+B)%B}var MK="trove.recents",KD=12;class C0{constructor(A){this.context=A,this.state={stack:[{kind:"search"}],activeTabId:null,activeFile:null,recents:JD()},this.cell=f(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}#Q(){return this.state.stack[this.state.stack.length-1]}activeTab(){let A=this.#Q();return A?.kind==="file"?A:null}#B(A,{history:Q=!0}={}){let B=A[A.length-1],C=B&&B.kind==="file"?B:null;if(this.#A({stack:A,activeTabId:C?C.id:null,activeFile:C?C.node:null}),this.context.setMany({"editor.open":!!C,"editor.openerId":C?.openerId||"","editor.contentType":C?.node.contentType||""}),Q)this.#C()}reset(){this.#B([{kind:"search"}])}openFile(A,Q,{reset:B=!1}={}){let C={kind:"file",id:A.id,node:A,openerId:Q},E;if(B)E=[{kind:"search"},C];else{let K=this.state.stack.findIndex((J)=>J.kind==="file"&&J.id===A.id);if(K>=0)E=this.state.stack.slice(0,K+1),E[K]=C;else E=[...this.state.stack,C]}this.#E(A),this.#B(E)}back(){if(this.state.stack.length<=1)return;try{history.back()}catch{this.pop()}}pop(){if(this.state.stack.length>1)this.#B(this.state.stack.slice(0,-1),{history:!1})}closeTab(A){let Q=this.state.stack.filter((B)=>!(B.kind==="file"&&B.id===A));this.#B(Q.length?Q:[{kind:"search"}],{history:!1})}updateTabNode(A){let Q=this.state.stack.map((B)=>B.kind==="file"&&B.id===A.id?{...B,node:A}:B);this.#B(Q,{history:!1})}#C(A=!1){let Q=this.#Q(),B=Q?.node,C={troveDepth:this.state.stack.length,node:B?{id:B.id,name:B.name,contentType:B.contentType,collectionId:B.collectionId}:null,openerId:Q?.openerId||null};try{(A?history.replaceState:history.pushState).call(history,C,"")}catch{}}onPopState(A){let Q=A?.state||{},B=Q.troveDepth||1;if(B<=this.state.stack.length)this.#B(this.state.stack.slice(0,B),{history:!1});else if(Q.node)this.#B([...this.state.stack,{kind:"file",id:Q.node.id,node:Q.node,openerId:Q.openerId}],{history:!1})}#E(A){if(!A)return;let B=[{id:A.id,name:A.name,contentType:A.contentType||"",collectionId:A.collectionId},...this.state.recents.filter((C)=>C.id!==A.id)].slice(0,KD);this.#A({recents:B}),YD(B)}}function JD(){try{return JSON.parse(localStorage.getItem(MK))||[]}catch{return[]}}function YD(A){try{localStorage.setItem(MK,JSON.stringify(A))}catch{}}class E0{constructor(A){this.context=A,this.overlay=new Q0(A),this.nav=new C0(A),this.state={activity:"home",sidebarVisible:!0,launch:{query:"",index:0},searchModal:!1,infoPanel:!1,sheet:null},this.cell=f(this.state)}observe(){return this.cell}observeOverlay(){return this.overlay.observe()}observeNav(){return this.nav.observe()}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}touch(){this.#A({})}openPalette(A,Q){this.overlay.openPalette(A,Q)}setPaletteQuery(A){this.overlay.setPaletteQuery(A)}movePalette(A,Q){this.overlay.movePalette(A,Q)}closePalette(){this.overlay.closePalette()}showDialog(A){this.overlay.showDialog(A)}updateDialog(A){this.overlay.updateDialog(A)}closeDialog(){this.overlay.closeDialog()}showContextMenu(A,Q,B){this.overlay.showContextMenu(A,Q,B)}closeContextMenu(){this.overlay.closeContextMenu()}openPluginPanel(A){this.overlay.openPluginPanel(A)}closePluginPanel(){this.overlay.closePluginPanel()}activeTab(){return this.nav.activeTab()}back(){this.nav.back()}pop(){this.nav.pop()}closeTab(A){this.nav.closeTab(A)}updateTabNode(A){this.nav.updateTabNode(A)}onPopState(A){this.nav.onPopState(A)}setActivity(A){this.#A({activity:A,sidebarVisible:!0}),this.context.set("view.active",A)}showHome(){this.#A({activity:"home",searchModal:!1}),this.nav.reset(),this.context.set("view.active","home")}setLaunchQuery(A){this.#A({launch:{query:A,index:0}})}moveLaunch(A,Q){if(!Q)return;this.#A({launch:{...this.state.launch,index:B0(this.state.launch.index,A,Q)}})}setPaletteIndex(A){this.overlay.setPaletteIndex?.(A)}setLaunchIndex(A){this.#A({launch:{...this.state.launch,index:A}})}openSearchModal(){this.#A({searchModal:!0,launch:{query:"",index:0}}),this.context.set("searchModal.open",!0)}closeSearchModal(){this.#A({searchModal:!1}),this.context.set("searchModal.open",!1)}openFile(A,Q,B={}){this.#A({activity:"home",searchModal:!1}),this.nav.openFile(A,Q,B)}openSheet(A){this.#A({sheet:this.state.sheet===A?null:A}),this.context.set("sheet.open",this.state.sheet||"")}closeSheet(){if(!this.state.sheet)return;this.#A({sheet:null}),this.context.set("sheet.open","")}toggleInfoPanel(A){this.#A({infoPanel:A??!this.state.infoPanel}),this.context.set("infoPanel.open",this.state.infoPanel)}closeOverlays(){let A=this.overlay.state;if(A.contextMenu)return this.overlay.closeContextMenu(),!0;if(A.dialog)return this.overlay.closeDialog(),!0;if(this.state.sheet)return this.closeSheet(),!0;if(this.state.searchModal)return this.closeSearchModal(),!0;if(A.palette)return this.overlay.closePalette(),!0;if(A.pluginPanel)return this.overlay.closePluginPanel(),!0;if(this.nav.state.stack.length>1)return this.nav.back(),!0;return!1}}var VK=["auto","desktop","phone","tv"],ID=720,LD=1100,DD=/\b(smart-?tv|smarttv|appletv|googletv|android\s*tv|hbbtv|netcast|web0s|webos|tizen|viera|bravia|aquos|crkey|nettv|dtv|philipstv|roku|aft[a-z]{1,3})\b/i;function GD(A="",Q=0){if(!A)return!1;return DD.test(A)&&Q>=LD}class K0{constructor({window:A=globalThis,settings:Q=null,context:B=null}={}){this.window=A,this.settings=Q,this.context=B,this.urlOverride=$D(A),this.state=this.#Q(),this.cell=f(this.state),this._onResize=()=>this.refresh()}observe(){return this.cell}install(){if(this.window.addEventListener?.("resize",this._onResize),this.window.addEventListener?.("orientationchange",this._onResize),this.settings)_A(this.settings.observe(),()=>this.refresh());return this.#A(this.state),this}dispose(){this.window.removeEventListener?.("resize",this._onResize),this.window.removeEventListener?.("orientationchange",this._onResize)}refresh(){let A=this.#Q();if(A.mode===this.state.mode&&A.width===this.state.width&&A.height===this.state.height&&A.coarse===this.state.coarse)return;this.state=A,this.#A(A),this.cell.setValue(A)}#A(A){this.context?.set("viewport.mode",A.mode),this.context?.set("viewport.phone",A.mode==="phone"),this.context?.set("viewport.tv",A.mode==="tv");let Q=this.window.document?.documentElement;if(Q)Q.dataset.layout=A.mode}#Q(){let A=this.window,Q=A.innerWidth||1280,B=A.innerHeight||800,C=HD(A,"(pointer: coarse)"),E=A.navigator?.userAgent||"",K=this.urlOverride||this.settings?.get?.("workbench.layout")||"auto";return{mode:K!=="auto"&&VK.includes(K)?K:XD({width:Q,coarse:C,ua:E}),width:Q,height:B,coarse:C,forced:K!=="auto"}}}function XD({width:A,coarse:Q,ua:B}){if(GD(B,A))return"tv";if(A<=ID)return"phone";return"desktop"}function HD(A,Q){try{return!!A.matchMedia?.(Q)?.matches}catch{return!1}}function $D(A){try{let Q=new URL(A.location.href).searchParams.get("ui");return Q&&VK.includes(Q)?Q:null}catch{return null}}var qK='a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])',zK=".launch-item, .grid-tile, .sheet-row, .inbox-item, .plugin-card, .act-task, .act-issue, .chapter",ZD=`${qK}, ${zK}`,UD=new Set(["BrowserBack","GoBack","Backspace"]),WD=new Set([10009,461]),RD={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},FD=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA"]);class J0{constructor({workbench:A,viewport:Q,window:B=globalThis}){this.workbench=A,this.viewport=Q,this.window=B,this.active=!1,this._onKey=(C)=>this.handleKey(C),this._observer=null,this._pending=0,this._bootstrapped=!1}install(){if(this.viewport)_A(this.viewport.observe(),(A)=>this.setActive(A.mode==="tv"));return this.setActive(this.viewport?.state?.mode==="tv"),this}setActive(A){if(A===this.active)return;if(this.active=A,A)this.window.addEventListener?.("keydown",this._onKey),this.#A(),this.prime(),this.window.setTimeout?.(()=>this.prime(),60);else this.window.removeEventListener?.("keydown",this._onKey),this._observer?.disconnect(),this._observer=null,this._bootstrapped=!1}prime(){this.candidates(),this.focusFirst()}#A(){let A=this.window.MutationObserver;if(!A||this._observer)return;this._observer=new A(()=>{if(this._pending)return;this._pending=this.window.requestAnimationFrame?.(()=>{if(this._pending=0,this.active)this.prime()})||0}),this._observer.observe(this.window.document.body,{childList:!0,subtree:!0})}handleKey(A){if(!this.active||A.defaultPrevented||A.altKey||A.ctrlKey||A.metaKey)return;let Q=this.window.document,B=Q.activeElement;if(UD.has(A.key)||WD.has(A.keyCode)){if(A.key==="Backspace"&&PK(B)&&(B.value??"").length>0)return;A.preventDefault(),this.goBack();return}let C=RD[A.key];if(!C){if(A.key==="Enter"&&B&&!FD.has(B.tagName)&&B.matches(zK))A.preventDefault(),B.click();return}if((C==="left"||C==="right")&&PK(B)&&!MD(B,C))return;let E=B&&B!==Q.body?B:null,K=this.find(C,E);if(!K)return;A.preventDefault(),NK(K)}goBack(){if(this.workbench?.closeOverlays())return;this.window.history?.back?.()}candidates(){let A=this.window.document,Q=[];for(let B of A.querySelectorAll(ZD)){if(B.getAttribute?.("aria-hidden")==="true"||B.hasAttribute?.("disabled"))continue;let C=B.getBoundingClientRect();if(C.width<2||C.height<2)continue;if(C.bottom<0||C.top>this.window.innerHeight||C.right<0||C.left>this.window.innerWidth)continue;if(!B.matches(qK)&&!B.hasAttribute("tabindex"))B.setAttribute("tabindex","0");Q.push({el:B,rect:C})}return Q}find(A,Q){let B=this.candidates();if(!B.length)return null;let C=Q&&Q.getBoundingClientRect&&Q.getBoundingClientRect().width?Q.getBoundingClientRect():null;if(!C)return B[0].el;let E=null,K=1/0;for(let{el:J,rect:Y}of B){if(J===Q)continue;let I=VD(C,Y,A);if(I==null||I>=K)continue;K=I,E=J}return E}focusFirst(){if(this._bootstrapped)return;let A=this.window.document;if(A?.activeElement&&A.activeElement!==A.body)return;let Q=this.candidates();if(!Q.length)return;let B=Q.find((C)=>C.el.classList?.contains("launch-input"))||Q[0];NK(B.el),this._bootstrapped=!0}}function MD(A,Q){let{selectionStart:B,selectionEnd:C}=A;if(B==null||C==null)return!0;if(B!==C)return!1;return Q==="left"?B===0:C>=(A.value??"").length}function PK(A){if(!A)return!1;let Q=A.tagName;if(Q==="TEXTAREA")return!0;if(A.isContentEditable)return!0;if(Q!=="INPUT")return!1;return!["checkbox","radio","button","submit","range","file"].includes(A.type)}function NK(A){A.focus?.({preventScroll:!0}),A.scrollIntoView?.({block:"nearest",inline:"nearest"})}function VD(A,Q,B){let C=B==="up"||B==="down",[E,K]=C?B==="down"?[A.bottom,Q.top]:[A.top,Q.bottom]:B==="right"?[A.right,Q.left]:[A.left,Q.right],Y=B==="down"||B==="right"?K-E:E-K;if(Y<-2)return null;let[I,D,L,G]=C?[A.left,A.right,Q.left,Q.right]:[A.top,A.bottom,Q.top,Q.bottom],X=Math.max(0,Math.max(I,L)-Math.min(D,G)),Z=Math.abs((I+D)/2-(L+G)/2);return Math.max(0,Y)+X*3+Z*0.2}function AB(){if(typeof window>"u")return null;return window.SpeechRecognition||window.webkitSpeechRecognition||null}function yB(){let A=AB();return!!A&&typeof A.available==="function"}var Y0=(A)=>({langs:[A],processLocally:!0});async function OK(A=navigator.language||"en-US"){if(!yB())return"unavailable";try{return await AB().available(Y0(A))}catch{return"unavailable"}}async function jK(A=navigator.language||"en-US"){if(typeof AB()?.install!=="function")return!1;try{return await AB().install(Y0(A))}catch{return!1}}function SK({lang:A=navigator.language||"en-US",onText:Q,onEnd:B,onError:C}={}){if(!yB())throw Error("On-device speech recognition is not available here");let E=new(AB());E.lang=A,E.interimResults=!0,E.continuous=!1,E.options=Y0(A),E.processLocally=!0;let K=!1;E.onresult=(J)=>{let Y="",I=!1;for(let D=J.resultIndex;D<J.results.length;D++)if(Y+=J.results[D][0].transcript,J.results[D].isFinal)I=!0;Q?.(Y.trim(),{final:I})},E.onerror=(J)=>{if(J.error==="no-speech"||J.error==="aborted")return;C?.(Error(J.error||"Speech recognition failed"))},E.onend=()=>{if(!K)K=!0,B?.()};try{E.start()}catch(J){K=!0,C?.(J),B?.()}return{stop(){if(K)return;K=!0;try{E.stop()}catch{}B?.()}}}class I0{constructor({workbench:A,notifications:Q,settings:B}={}){this.workbench=A,this.notifications=Q,this.settings=B,this.session=null,this.state={supported:yB(),status:"unknown",listening:!1},this.cell=f(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async refresh(){if(!this.state.supported)return"unavailable";let A=await OK(this.#Q());return this.#A({status:A}),A}#Q(){return this.settings?.get?.("search.voiceLanguage")||navigator.language||"en-US"}canListen(){return this.state.supported&&(this.state.status==="available"||this.state.status==="downloadable")}async run({onText:A}={}){if(this.openSearchSurface(),await this.focusInput(),!this.state.supported)return{listening:!1,reason:"unsupported"};let Q=this.state.status==="unknown"?await this.refresh():this.state.status;if(Q==="downloadable"){this.notifications?.info("Downloading the on-device voice model — this happens once.");let B=await jK(this.#Q());if(this.#A({status:B?"available":"unavailable"}),!B)return{listening:!1,reason:"install-failed"}}else if(Q!=="available")return{listening:!1,reason:Q};return this.toggle({onText:A})}toggle({onText:A}={}){if(this.session)return this.stop(),{listening:!1};try{return this.session=SK({lang:this.#Q(),onText:A,onEnd:()=>{this.session=null,this.#A({listening:!1})},onError:(Q)=>{if(this.session=null,this.#A({listening:!1}),!/not-allowed|service-not-allowed|denied/i.test(Q.message))this.notifications?.warn(`Couldn't listen: ${Q.message}`)}}),this.#A({listening:!0}),{listening:!0}}catch(Q){return this.notifications?.warn(`Couldn't listen: ${Q.message}`),{listening:!1,reason:"error"}}}stop(){this.session?.stop(),this.session=null,this.#A({listening:!1})}openSearchSurface(){let A=this.workbench;if(!A)return;if(A.state.activity==="home"&&!A.nav?.state?.activeTabId)A.closeSearchModal?.();else A.openSearchModal()}focusInput({tries:A=12}={}){return new Promise((Q)=>{let B=A,C=()=>{let E=document.querySelector(".search-modal .launch-input")||document.querySelector(".launch-input");if(E){E.focus();try{E.setSelectionRange(E.value.length,E.value.length)}catch{}Q(document.activeElement===E);return}if(--B<=0){Q(!1);return}requestAnimationFrame(C)};C()})}}class L0{constructor({api:A,settings:Q=null}){this.api=A,this.settings=Q,this.cache=new Map,this._queue=new Map,this._timer=null}get needed(){let A=this.settings?.get("media.signedUrls");if(A==="always")return!0;if(A==="never")return!1;return!!this.api.token?.()}cacheKey(A){return this.api.downloadUrl(A)}async url(A,{op:Q="media"}={}){if(!this.needed)return{url:this.api.downloadUrl(A,{attachment:Q==="download"}),expiresAt:1/0};let B=`${Q}:${A}`,C=this.cache.get(B);if(C&&this.#A(C))return C;return this.#Q(A,Q)}invalidate(A,Q="media"){if(A==null)this.cache.clear();else this.cache.delete(`${Q}:${A}`)}#A(A){if(A.expiresAt===1/0)return!0;let Q=A.expiresAt-A.mintedAt;return Date.now()<A.mintedAt+Q*0.8}#Q(A,Q){if(!this._queue.has(Q))this._queue.set(Q,new Map);let B=this._queue.get(Q),C=B.get(A);if(C)return C.promise;let E,K,J=new Promise((Y,I)=>{E=Y,K=I});if(B.set(A,{resolve:E,reject:K,promise:J}),B.size>=200)this.#B();else if(!this._timer)this._timer=setTimeout(()=>this.#B(),20);return J}async#B(){clearTimeout(this._timer),this._timer=null;let A=this._queue;this._queue=new Map;for(let[Q,B]of A){let C=[...B.keys()];try{let E=await this.api.mintUrls(C,Q),K=Date.now();for(let[J,Y]of B){let I=E.urls?.[J];if(I){let D={url:I.url,expiresAt:I.expiresAt,mintedAt:K};this.cache.set(`${Q}:${J}`,D),Y.resolve(D)}else Y.reject(Error(E.failed?.[J]==="not_found"?"That file is gone":"You cannot open that file"))}}catch(E){for(let K of B.values())K.reject(E)}}}}function PD(){try{return localStorage.getItem("trove.token")||null}catch{return null}}function wK({baseUrl:A=""}={}){let Q=new HC,B=new ZC({"view.active":"home","sidebar.visible":!0}),C=new MC,E=new UC(Q,B,C),K=new FC,J=new yQ(Q,E,B,K),Y=new VC({baseUrl:A,token:()=>PD()}),I=new E0(B),D=new K0({settings:K,context:B}),L=new J0({workbench:I,viewport:D}),G=new I0({workbench:I,notifications:C,settings:K}),X={reactive:ZE,contributions:Q,context:B,commands:E,keybindings:J,settings:K,notifications:C,api:Y,workbench:I,viewport:D,spatialNav:L,voice:G,capabilities:null,openPluginPanel:null};return X.mediaUrls=new L0({api:X.api,settings:K}),X.plugins=new A0(X),E.availability=(Z)=>X.plugins.isAvailable(Z),ND(X),D.refresh(),X}function ND(A){A.settings.register([{key:"workbench.theme",type:"enum",enum:["dark","light","midnight"],enumLabels:["Dark","Light","Midnight"],default:"dark",title:"Color theme",category:"Appearance",order:1},{key:"workbench.density",type:"enum",enum:["comfortable","compact"],default:"comfortable",title:"List density",category:"Appearance",order:2},{key:"workbench.layout",type:"enum",enum:["auto","desktop","phone","tv"],enumLabels:["Automatic","Desktop","Phone","TV / remote"],default:"auto",title:"Layout",description:"Automatic follows the screen size. Choose TV for d-pad remote navigation.",category:"Appearance",order:3},{key:"explorer.sort",type:"enum",enum:["name","size","updatedAt"],enumLabels:["Name","Size","Modified"],default:"name",title:"Sort files by",category:"Explorer",order:1},{key:"explorer.sortOrder",type:"enum",enum:["asc","desc"],default:"asc",title:"Sort order",category:"Explorer",order:2},{key:"explorer.confirmDelete",type:"boolean",default:!0,title:"Confirm before deleting",category:"Explorer",order:3},{key:"search.mode",type:"enum",enum:["hybrid","semantic","keyword"],default:"hybrid",title:"Search mode",description:"Hybrid blends semantic meaning with keyword matches.",category:"Search",order:1},{key:"uploads.concurrency",type:"number",minimum:1,maximum:8,default:4,title:"Parallel upload parts",category:"Transfers",order:1},{key:"openers.associations",type:"object",hidden:!0,title:"Default viewers",default:{".md":"core.markdown",".markdown":"core.markdown"}},{key:"explorer.view",type:"string",hidden:!0,title:"Results view"},{key:"media.signedUrls",type:"enum",enum:["auto","always","never"],default:"auto",hidden:!0,title:"Signed media URLs"}]),A.contributions.register("keymap.default",{type:"keymap",bindings:[{key:"mod+shift+p",command:"workbench.showCommandPalette"},{key:"mod+p",command:"workbench.quickOpen"},{key:"mod+shift+f",command:"workbench.view.home"},{key:"mod+shift+e",command:"workbench.view.home"},{key:"mod+,",command:"workbench.openSettings"},{key:"mod+shift+l",command:"explorer.copyLink"},{key:"mod+u",command:"explorer.upload"},{key:"delete",command:"explorer.delete",when:"view.active == 'home' && explorer.hasSelection"},{key:"escape",command:"workbench.closeOverlays"},{key:"f5",command:"explorer.refresh"},{key:"mod+shift+i",command:"workbench.toggleInfoPanel"},{key:"mod+shift+v",command:"search.voice"},{key:"browsersearch",command:"search.voice"}]})}function NA(A){console.error(A)}var hQ="The provider has been disposed";class CQ{static deps=[];async obtain(A={}){throw Error("obtain() not implemented")}release(A,Q={}){}async flush(){}static fromSingleton(A,{dispose:Q,deps:B=[]}={}){return class extends CQ{static deps=B;#A;#Q=!1;constructor(E={}){super();this.#A=E}async obtain(){return A}release(){}async dispose(){if(this.#Q)return;if(this.#Q=!0,typeof Q==="function")await Q(A,this.#A)}}}static fromPool(A,Q,{size:B=1,deps:C=[]}={}){if(!Number.isInteger(B)||B<1)throw RangeError("fromPool() requires an integer size of at least 1");return class extends CQ{static deps=C;#A;#Q=[];#B=new Set;#C=[];#E=0;#K=!1;constructor(K={}){super();this.#A=K}async#J(K){try{await Q(K,this.#A)}catch(J){NA(J)}}#Y(){while(this.#C.length>0){if(this.#Q.length>0){let J=this.#Q.shift();this.#B.add(J),this.#C.shift().resolve(J);continue}if(this.#E>=B)return;let K=this.#C.shift();this.#E++,Promise.resolve().then(()=>A(this.#A)).then((J)=>{if(this.#K){this.#E--,this.#J(J),K.reject(Error(hQ));return}this.#B.add(J),K.resolve(J)},(J)=>{this.#E--,K.reject(J),this.#Y()})}}async obtain(){if(this.#K)throw Error(hQ);let K=Promise.withResolvers();return this.#C.push(K),this.#Y(),await K.promise}release(K){if(!this.#B.delete(K))return;if(this.#K){this.#E--,this.#J(K);return}this.#Q.push(K),this.#Y()}async dispose(){if(this.#K)return;this.#K=!0;let K=this.#C.splice(0);for(let{reject:Y}of K)Y(Error(hQ));let J=this.#Q.splice(0);this.#E-=J.length,await Promise.all(J.map((Y)=>this.#J(Y)))}}}static fromLazySingleton(A,Q,{deps:B=[]}={}){return class extends CQ{static deps=B;#A;#Q=null;#B=null;#C=!1;constructor(E={}){super();this.#A=E}async obtain(){if(this.#C)throw Error(hQ);this.#Q??=Promise.resolve().then(()=>A(this.#A));try{return this.#B=await this.#Q,this.#B}catch(E){throw this.#Q=null,this.#B=null,E}}release(){}async dispose(){if(this.#C)return;if(this.#C=!0,!this.#Q||typeof Q!=="function")return;let E=this.#B??await this.#Q.catch(()=>null);if(E!=null)await Q(E,this.#A)}}}static fromRefCounted(A,Q,{deps:B=[]}={}){return class extends CQ{static deps=B;#A;#Q=0;#B=null;#C=null;#E=null;#K=!1;constructor(E={}){super();this.#A=E}async obtain(){if(this.#K)throw Error(hQ);this.#Q++;while(this.#E)await this.#E;if(this.#K)throw this.#Q--,Error(hQ);if(!this.#B)this.#B=Promise.resolve().then(()=>A(this.#A));try{return this.#C=await this.#B,this.#C}catch(E){if(this.#Q--,this.#Q<=0)this.#Q=0,this.#B=null,this.#C=null;throw E}}async release(){if(this.#Q<=0)return;if(this.#Q--,this.#Q>0)return;let E=this.#C,K=this.#B;if(this.#C=null,this.#B=null,!K)return;this.#E=(async()=>{try{let J=E??await K.catch(()=>null);if(J!=null)await Q(J,this.#A)}catch(J){NA(J)}finally{this.#E=null}})(),await this.#E}async dispose(){if(this.#K=!0,this.#Q>0)this.#Q=1,await this.release();while(this.#E)await this.#E}}}}class D0{#A;#Q=!1;constructor(A,Q){this.resources=A,this.#A=Q}get released(){return this.#Q}async release(){if(this.#Q)return;this.#Q=!0;for(let{name:A,provider:Q,options:B}of this.#A)try{await Q.release(this.resources[A],B)}catch(C){NA(C)}this.#A=[]}}class EQ{#A=new Map;#Q=new WeakMap;#B;#C=!1;constructor({providers:A,feed:Q}={}){if(this.#B=Q??new EventTarget,!A)return;let B=(C,E)=>{if(this.#A.has(C))return this.#A.get(C);let K=A[C];if(!K)throw Error(`Dependency not found: ${C}`);let J=[...E,C];if(E.includes(C))throw Error(`Cyclic dependency detected: ${J.join(" -> ")}`);let Y={};for(let D of K.deps??[])Y[D]=B(D,J);let I=new K(Y,{engineFeed:this.#B,container:this});return this.#A.set(C,I),I};for(let C of Object.keys(A))B(C,[])}get feed(){return this.#B}get disposed(){return this.#C}has(A){return this.#A.has(A)}get(A){let Q=this.#A.get(A);if(!Q)throw Error(`Dependency not found: ${A}`);return Q}resolve(A){if(!A)return{};let Q=this.#Q.get(A);if(Q)return Q;let B={};if(Array.isArray(A))for(let C of A)B[C]={provider:this.get(C),options:void 0};else for(let C of Object.keys(A))B[C]={provider:this.get(C),options:A[C]};return this.#Q.set(A,B),B}resolveAll(...A){let Q=A.filter(Boolean);if(Q.length===1)return this.resolve(Q[0]);return Object.assign({},...Q.map((B)=>this.resolve(B)))}async lease(...A){if(this.#C)throw Error("The container has been disposed");let Q=this.resolveAll(...A),B={},C=[];try{for(let[E,{provider:K,options:J}]of Object.entries(Q))B[E]=await K.obtain(J),C.push({name:E,provider:K,options:J})}catch(E){throw await new D0(B,C).release(),E}return new D0(B,C)}async use(A,Q){let B=await this.lease(A);try{return await Q(B.resources)}finally{await B.release()}}async dispose(){if(this.#C)return;this.#C=!0;let A=[...this.#A.values()].reverse();for(let Q of A)try{await Q.flush?.()}catch(B){NA(B)}for(let Q of A)try{await Q.dispose?.()}catch(B){NA(B)}}}var qD=typeof ErrorEvent==="function"?ErrorEvent:class extends Event{constructor(Q,{error:B,message:C=""}={}){super(Q);this.error=B,this.message=C}};function zD(A){return A&&typeof A.message==="string"?A.message:String(A)}class kK extends Event{constructor({reason:A,error:Q=null}={}){super("abort");this.reason=A,this.error=Q}}var TK=["complete","error","abort"];function OD(){return typeof DOMException==="function"?new DOMException("The dispatch was aborted","AbortError"):Object.assign(Error("The dispatch was aborted"),{name:"AbortError"})}class QB{execute(){throw Error("execute() not implemented")}}class G0 extends EventTarget{#A=new AbortController;#Q;#B=null;constructor(){super();for(let A of TK)this.addEventListener(A,(Q)=>{this.#B??={type:A,event:Q}},{once:!0})}get signal(){return this.#A.signal}get settled(){return this.#B?.type??null}get reason(){return this.#Q}abort(A){if(this.#A.signal.aborted)return;this.#Q=A??OD(),this.#A.abort(this.#Q)}next(A,{signal:Q}={}){let B=new Set(Array.isArray(A)?A:[A]);if(B.size===0)throw TypeError("next() requires at least one event name");let C=B.has("abort");return new Promise((E,K)=>{if(Q?.aborted){K(Q.reason);return}if(this.#A.signal.aborted&&!C&&!this.#B){K(this.#Q);return}if(this.#B){this.#C(E,K,this.#B,B);return}let J=new AbortController,Y={signal:J.signal},I=(D)=>(L)=>{J.abort(),D(L)};for(let D of B)this.addEventListener(D,I(E),Y);for(let D of TK){if(B.has(D))continue;this.addEventListener(D,(L)=>I(K)(_K(D,L,B)),Y)}if(!C)this.#A.signal.addEventListener("abort",()=>I(K)(this.#Q),Y);Q?.addEventListener("abort",()=>I(K)(Q.reason),Y)})}#C(A,Q,B,C){if(C.has(B.type))A(B.event);else Q(_K(B.type,B.event,C))}}function _K(A,Q,B){if(A==="error")return Q.error;if(A==="abort")return Q.reason;return jD(B)}function jD(A){return Error(`The dispatch completed without emitting ${[...A].map((Q)=>`'${Q}'`).join(" or ")}`)}class hB{#A;#Q;constructor({container:A,interceptors:Q}={}){this.#A=A??new EQ,this.#Q=Q?[...Q]:[]}get container(){return this.#A}get feed(){return this.#A.feed}dispatch(A){if(!(A instanceof QB))throw TypeError("dispatch() requires an instance of Action");let Q=this.#A,B=this.#Q,C=Q.feed,E=new G0;return setTimeout(async()=>{let K=[],J={},Y=null,I=(D)=>{if(D!==void 0)J=D};try{for(let L of B){if(K.push(L),!L.enter)continue;I(await Q.use(L.deps,(G)=>L.enter(G,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J,action:A})))}let D=await Q.lease(A.constructor.deps,A.deps);try{await A.execute(D.resources,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J})}finally{await D.release()}}catch(D){Y=D}finally{for(let D=K.length-1;D>=0;D--){let L=K[D],G=E.signal.aborted;try{if(G&&L.abort)I(await Q.use(L.deps,(X)=>L.abort(X,{dispatchFeed:E,engineFeed:C,signal:E.signal,action:A,state:J,reason:E.reason,error:Y})));else if(Y&&L.error){let X={dispatchFeed:E,engineFeed:C,signal:E.signal,action:A,state:J,error:Y,handled:()=>{Y=null}};I(await Q.use(L.deps,(Z)=>L.error(Z,X)))}else if(!Y&&L.leave)I(await Q.use(L.deps,(X)=>L.leave(X,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J,action:A})))}catch(X){Y=X}}if(E.signal.aborted)E.dispatchEvent(new kK({reason:E.reason,error:Y}));else if(Y)E.dispatchEvent(new qD("error",{error:Y,message:zD(Y)}));else E.dispatchEvent(new Event("complete"))}}),E}}class vB{boot(){throw Error("boot() not implemented, and no fetch() to fall back to")}kill(){}}class xK{#A;#Q;#B=null;#C=null;#E=!1;#K=null;#J=Promise.withResolvers();#Y=!1;#I=void 0;#L=!1;#D=void 0;#X=void 0;observers=new Set;constructor(A,Q){this.#A=A,this.#Q=Q,this.notify=this.notify.bind(this)}get hasValue(){return this.#Y}get currentValue(){return this.#I}get received(){return this.#J.promise}get bootFeed(){return this.#D}get killFeed(){return this.#X}#$(A,Q){let B=this.#A._dispatch(A);return B.addEventListener("error",(C)=>{NA(Error(`${this.#Q.constructor.name} ${Q} (${A.constructor.name}) failed`,{cause:C.error}))},{once:!0}),B}notify(A){if(this.#L)return;if(this.#I=A,!this.#Y)this.#Y=!0,this.#J.resolve(!0);for(let Q of[...this.observers])try{Q.next?.(A)}catch(B){NA(B)}}boot(){if(this.#C)return this.#C;return this.#C=(async()=>{try{if(this.#Q.bootAction)this.#D=this.#$(this.#Q.bootAction,"bootAction");this.#B=await this.#A._container.lease(this.#Q.constructor.deps,this.#Q.deps);let A={notify:this.notify,engineFeed:this.#A._container.feed,bootFeed:this.#D};if(this.#Q.boot===vB.prototype.boot){if(typeof this.#Q.fetch!=="function")throw Error(`${this.#Q.constructor.name} implements neither boot() nor fetch()`);this.notify(await this.#Q.fetch(this.#B.resources,A)),await this.#H()}else await this.#Q.boot(this.#B.resources,A)}catch(A){NA(A),await this.#H(A)}finally{this.#E=!0}})(),this.#C}kill(){if(this.#K)return this.#K;return this.#K=this.#E?this.#G():Promise.resolve(this.#C).then(()=>this.#G()),this.#K}async#G(){if(this.#L)return;try{if(this.#Q.killAction)this.#X=this.#$(this.#Q.killAction,"killAction");if(this.#Q.kill)await this.#Q.kill(this.#B?.resources??{},{bootFeed:this.#D,killFeed:this.#X,engineFeed:this.#A._container.feed,notify:this.notify})}catch(A){NA(A)}finally{await this.#H()}}async#H(A){if(this.#L)return;this.#L=!0,this.#A._evict(this.#Q,this);let Q=[...this.observers];this.observers.clear();for(let C of Q)try{if(A!==void 0&&C.error)C.error(A);else C.complete?.()}catch(E){NA(E)}if(!this.#Y)this.#J.resolve(!1);let B=this.#B;if(this.#B=null,B)await B.release()}}class bB{#A;#Q;#B;#C=!1;constructor({container:A,dispatcher:Q,createControllerMap:B}={}){this.#A=A??new EQ,this.#Q=Q??null,this.#B=B?.()??new Map}get container(){return this.#A}get feed(){return this.#A.feed}get _container(){return this.#A}_dispatch(A){if(!this.#Q)throw Error("A query declared a bootAction/killAction but no dispatcher was given to QueryStore");return this.#Q.dispatch(A)}_evict(A,Q){if(this.#B.get(A)===Q)this.#B.delete(A)}#E(A){return[A.constructor.deps,A.deps]}query(A){if(!(A instanceof vB))throw TypeError("query() requires an instance of Query");return{subscribe:(Q)=>{if(this.#C)throw Error("The query store has been disposed");let B=typeof Q==="function"?{next:Q}:Q||{},C=this.#B.get(A);if(C){if(C.observers.add(B),C.hasValue)try{B.next?.(C.currentValue)}catch(K){NA(K)}}else C=new xK(this,A),this.#B.set(A,C),C.observers.add(B),C.boot();let E=!1;return{get closed(){return E},unsubscribe:()=>{if(E)return;if(E=!0,C.observers.delete(B),C.observers.size===0)this._evict(A,C),C.kill()}}},peek:async()=>{let Q=this.#B.get(A);if(Q&&await Q.received)return Q.currentValue;if(typeof A.fetch!=="function")throw TypeError(`${A.constructor.name} is not active and does not implement fetch()`);let B=await this.#A.lease(...this.#E(A));try{return await A.fetch(B.resources,{engineFeed:this.#A.feed,bootFeed:Q?.bootFeed,killFeed:Q?.killFeed})}finally{await B.release()}}}}async dispose(){if(this.#C)return;this.#C=!0;for(let A of[...this.#B.values?.()??[]])await A.kill()}}class fB{#A;#Q;#B;#C=!1;constructor({providers:A,interceptors:Q,hooks:B,container:C,dispatcher:E,queries:K}={}){this.#A=C??new EQ({providers:A}),this.#Q=E??new hB({container:this.#A,interceptors:Q}),this.#B=K??new bB({container:this.#A,dispatcher:this.#Q,createControllerMap:B?.createQueryControllersMap})}get container(){return this.#A}get dispatcher(){return this.#Q}get queries(){return this.#B}get feed(){return this.#A.feed}dispatch(A){return this.#Q.dispatch(A)}query(A){return this.#B.query(A)}async dispose(){if(this.#C)return;this.#C=!0,await this.#B.dispose(),await this.#A.dispose()}}class X0{constructor(A){this.settings=A,this.state={items:[],loading:!1,error:null,selection:[],sort:A.get("explorer.sort"),order:A.get("explorer.sortOrder"),collectionId:"default",collections:[],canCreateCollection:!1,stats:null,usage:null,nextCursor:null,loadingMore:!1,trash:null},this.cell=f(this.state)}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}select(A,{additive:Q=!1,nodes:B=null}={}){let C=Q?Array.from(new Set([...this.state.selection,...A])):A;if(C.length===this.state.selection.length&&C.every((K,J)=>K===this.state.selection[J]))return;this.set({selection:C,selectionNodes:B&&!Q?B:null})}selectedNodes(){let A=this.state.selectionNodes;if(A?.length)return A.filter((Q)=>this.state.selection.includes(Q.id));return this.state.items.filter((Q)=>this.state.selection.includes(Q.id))}}class H0{constructor(){this.state={query:"",mode:"hybrid",results:[],loading:!1,error:null,ran:!1,paletteFiles:[],paletteQuery:"",paletteLoading:!1,paletteError:null},this.cell=f(this.state)}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}}class $0{constructor(A=null){this.state={items:[]},this.cell=f(this.state),this._controllers=new Map,this.activity=A,this._tasks=new Map}observe(){return this.cell}#A(){this.cell.setValue(this.state)}start(A,Q,B,C){this._controllers.set(A,C),this.state={items:[...this.state.items,{id:A,name:Q,direction:"up",ratio:0,loaded:0,total:B,status:"active",error:null}]},this.#A();let E=this.activity?.start({kind:"transfer",title:`Uploading ${Q}`,total:B||null,unit:"bytes",onCancel:()=>this.cancel(A)});if(E)this._tasks.set(A,E)}progress(A,{loaded:Q,total:B,ratio:C}){this.state={items:this.state.items.map((E)=>E.id===A?{...E,loaded:Q,total:B,ratio:C}:E)},this.#A(),this._tasks.get(A)?.progress({done:Q,total:B||null})}finish(A,Q="done",B=null){this.state={items:this.state.items.map((E)=>E.id===A?{...E,status:Q,error:B,ratio:Q==="done"?1:E.ratio}:E)},this._controllers.delete(A),this.#A();let C=this._tasks.get(A);if(C){if(Q==="done")C.succeed();else if(Q==="cancelled")C.cancel();else C.fail(B||Error("Upload failed"));this._tasks.delete(A)}if(Q==="done")setTimeout(()=>this.dismiss(A),4000)}cancel(A){this._controllers.get(A)?.abort(),this.finish(A,"cancelled")}dismiss(A){this.state={items:this.state.items.filter((Q)=>Q.id!==A)},this.#A()}clearDone(){this.state={items:this.state.items.filter((A)=>A.status==="active")},this.#A()}}class Z0{constructor(A){this.platform=A,this.api=A.api,this.state={me:null,notifications:{items:[],unread:0},inboxOpen:!1,pushSupported:"serviceWorker"in navigator&&"PushManager"in window,pushEnabled:!1,sidecar:null,backlinks:null,posting:!1,replyTo:null},this.cell=f(this.state),this._pollTimer=null}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async init(){try{let A=await this.api.me();this.#A({me:A.principal,admin:!!A.admin})}catch{}if(await this.refreshNotifications(),this._pollTimer=setInterval(()=>this.refreshNotifications(),45000),this._pollTimer.unref)this._pollTimer.unref();this.#B(),window.addEventListener("focus",()=>this.refreshNotifications()),navigator.serviceWorker?.addEventListener?.("message",(A)=>{if(A.data?.type==="trove-push")this.refreshNotifications()})}async refreshNotifications(){try{let A=await this.api.notifications();this.#A({notifications:A})}catch{}}toggleInbox(A){let Q=A??!this.state.inboxOpen;if(this.#A({inboxOpen:Q}),Q&&this.state.notifications.unread)this.markAllRead()}async markAllRead(){try{await this.api.markNotificationsRead(),this.#A({notifications:{...this.state.notifications,unread:0,items:this.state.notifications.items.map((A)=>({...A,read:!0}))}})}catch{}}async loadSidecar(A){if(!A)return this.#A({sidecar:null,backlinks:null});this.#A({sidecar:{nodeId:A,loading:!0,tags:[],comments:[],subscribers:[]}}),this.loadBacklinks(A);try{let Q=await this.api.sidecar(A);if(this.state.sidecar?.nodeId!==A)return;this.#A({sidecar:{...Q,loading:!1}})}catch(Q){if(this.state.sidecar?.nodeId!==A)return;this.#A({sidecar:{nodeId:A,loading:!1,error:Q.message,tags:[],comments:[]}})}}async loadBacklinks(A){if(!A)return this.#A({backlinks:null});this.#A({backlinks:{nodeId:A,items:[],loading:!0,error:null}});try{let Q=await this.api.backlinks(A);if(this.state.backlinks?.nodeId!==A)return;this.#A({backlinks:{nodeId:A,items:Q.items||[],loading:!1,error:null}})}catch(Q){if(this.state.backlinks?.nodeId!==A)return;this.#A({backlinks:{nodeId:A,items:[],loading:!1,error:Q.message}})}}async#Q(){if(this.state.sidecar?.nodeId)await this.loadSidecar(this.state.sidecar.nodeId)}setReplyTo(A){this.#A({replyTo:A})}async comment(A){let Q=this.state.sidecar?.nodeId;if(!Q||!A.trim())return;let B=this.state.replyTo?.id||null;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"POST",path:`/api/items/${encodeURIComponent(Q)}/comments`,body:{body:A,parentId:B}}),this.#A({replyTo:null}),this.platform.notifications.info("Offline — your comment will post when you reconnect.");return}this.#A({posting:!0});try{await this.api.addComment(Q,{body:A,parentId:B}),this.#A({replyTo:null}),await this.#Q()}catch(C){this.platform.notifications.error(`Couldn't post comment: ${C.message}`)}finally{this.#A({posting:!1})}}async deleteComment(A){let Q=this.state.sidecar?.nodeId;await this.api.deleteComment(Q,A).catch((B)=>this.platform.notifications.error(B.message)),await this.#Q()}async react(A,Q){let B=this.state.sidecar?.nodeId,E=!(gK(this.state.sidecar?.comments||[],A)?.reactions?.[Q]||[]).includes(this.state.me?.id);try{await this.api.reactComment(B,A,Q,E)}catch(K){this.platform.notifications.error(`Couldn't react: ${K.message}`)}await this.#Q()}async addTag(A,Q){let B=this.state.sidecar?.nodeId;if(!A.trim())return;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"POST",path:`/api/items/${encodeURIComponent(B)}/tags`,body:{name:A.trim(),value:Q}}),this.platform.notifications.info("Offline — tag will sync when you reconnect.");return}await this.api.setTag(B,A.trim(),Q).catch((C)=>this.platform.notifications.error(C.message)),await this.#Q()}async removeTag(A){let Q=this.state.sidecar?.nodeId;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"DELETE",path:`/api/items/${encodeURIComponent(Q)}/tags/${encodeURIComponent(A)}`}),this.platform.notifications.info("Offline — tag removal will sync when you reconnect.");return}try{await this.api.removeTag(Q,A)}catch(B){this.platform.notifications.error(`Couldn't remove tag: ${B.message}`)}await this.#Q()}async#B(){if(!this.state.pushSupported)return;try{let Q=await(await navigator.serviceWorker.getRegistration())?.pushManager?.getSubscription();this.#A({pushEnabled:!!Q})}catch{}}async enablePush(){if(!this.state.pushSupported){this.platform.notifications.warn("Push notifications are not supported in this browser.");return}try{let{publicKey:A}=await this.api.vapidKey();if(!A){this.platform.notifications.warn("This server has no VAPID key configured for web push.");return}let Q=await navigator.serviceWorker.register("/sw.js");if(await navigator.serviceWorker.ready,await Notification.requestPermission()!=="granted")return this.platform.notifications.info("Notifications permission was denied.");let C=await Q.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:SD(A)});await this.api.subscribePush(C.toJSON()),this.#A({pushEnabled:!0}),this.platform.notifications.success("Notifications enabled — you’ll be pinged when someone @mentions you.")}catch(A){this.platform.notifications.error(`Couldn't enable notifications: ${A.message}`)}}}function gK(A,Q){for(let B of A){if(B.id===Q)return B;let C=gK(B.replies||[],Q);if(C)return C}return null}function SD(A){let Q="=".repeat((4-A.length%4)%4),B=(A+Q).replace(/-/g,"+").replace(/_/g,"/"),C=atob(B),E=new Uint8Array(C.length);for(let K=0;K<C.length;K++)E[K]=C.charCodeAt(K);return E}class U0{get dimensions(){return 0}async embed(A){throw P.unsupported("embed not implemented")}async embedOne(A){return(await this.embed([A]))[0]}}var wD=new Set("a an the of to in on for and or is are be as at by with from this that it".split(" "));function TD(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!wD.has(Q))}function _D(A){let Q=2166136261;for(let B=0;B<A.length;B++)Q^=A.charCodeAt(B),Q=Math.imul(Q,16777619);return Q>>>0}class W0 extends U0{constructor({dimensions:A=256}={}){super();this._dim=A}get dimensions(){return this._dim}async embed(A){return A.map((Q)=>this.#A(Q))}#A(A){let Q=new Float64Array(this._dim),B=TD(A),C=[...B];for(let K=0;K<B.length-1;K++)C.push(B[K]+"_"+B[K+1]);for(let K of C){let J=_D(K),Y=J%this._dim,I=J>>31&1?-1:1;Q[Y]+=I}let E=0;for(let K=0;K<Q.length;K++)E+=Q[K]*Q[K];return E=Math.sqrt(E)||1,Array.from(Q,(K)=>K/E)}}class kD extends U0{constructor(A){super();if(!A?.url||!A?.dimensions)throw P.invalid("HttpEmbedding requires url and dimensions");this.cfg=A}get dimensions(){return this.cfg.dimensions}async embed(A){let Q=this.cfg.batchSize??64,B=[];for(let C=0;C<A.length;C+=Q){let E=A.slice(C,C+Q);B.push(...await this.#A(E))}return B}async#A(A){return sQ(async()=>{let Q;try{Q=await fetch(this.cfg.url,{method:"POST",headers:{"content-type":"application/json",...this.cfg.apiKey?{authorization:`Bearer ${this.cfg.apiKey}`}:{}},body:JSON.stringify({model:this.cfg.model,input:A})})}catch(E){throw oQ(E)}if(Q.status===429||Q.status>=500)throw P.transient(`Embedding endpoint ${Q.status}`);if(!Q.ok)throw P.internal(`Embedding endpoint failed: ${Q.status}`);let B=await Q.json();return(B.data??B.embeddings??[]).map((E)=>E.embedding??E)})}}var R0="trove:",xD=255;var gD=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function uB(A){if(typeof A!=="string"||!A.toLowerCase().startsWith(R0))return null;let Q;try{Q=new URL(A)}catch{return null}let B=Q.pathname,C=B.indexOf("/"),E=C<0?B:B.slice(0,C);if(!gD.test(E))return null;let K=Q.searchParams.get("id"),J=Q.searchParams.get("name"),Y="";if(C>=0)try{Y=decodeURIComponent(B.slice(C+1))}catch{return null}if(K!=null&&(J!=null||Y))return null;let I=K!=null?"id":"name",D=K!=null?K:J!=null?J:Y;if(!D||D.length>xD)return null;return{collection:E,by:I,value:D}}function mB(A,Q="name"){let B=A?.collectionId||"default";if(Q==="id"){if(!A?.id)throw P.invalid("trove: link by id needs a node id");return`${R0}${B}?id=${encodeURIComponent(A.id)}`}if(!A?.name)throw P.invalid("trove: link by name needs a node name");return`${R0}${B}?name=${encodeURIComponent(A.name)}`}function yK(A,Q,B){let C=[],E=0;while(E<A.length){let K=Math.min(E+Q,A.length);if(K<A.length){let J=A.slice(E,K),Y=Math.max(J.lastIndexOf(`
|
|
345
|
+
|
|
346
|
+
`),J.lastIndexOf(". "),J.lastIndexOf(`
|
|
347
|
+
`));if(Y>Q*0.75)K=E+Y+1}if(C.push(A.slice(E,K).trim()),K>=A.length)break;E=K-B}return C.filter(Boolean)}var yD=new Set("a an the of to in on for and or is are be as at by with from this that it".split(" "));function F0(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!yD.has(Q))}function BB(A){let Q=(A?.name||"").toLowerCase();return Q.includes(".")?Q.slice(Q.lastIndexOf(".")):""}var hK=[{kind:"audio",icon:"file-audio",mime:["audio/"],ext:[".mp3",".flac",".wav",".opus",".ogg",".m4a",".m4b"]},{kind:"image",icon:"file-image",mime:["image/"],ext:[".png",".jpg",".jpeg",".gif",".webp",".svg",".avif"]},{kind:"video",icon:"file-video",mime:["video/"],ext:[".mp4",".webm",".mkv",".mov"]},{kind:"text",icon:"file-text",mime:["text/","application/json"],ext:[".txt",".md",".markdown",".json",".js",".mjs",".ts",".jsx",".tsx",".css",".html",".xml",".yaml",".yml",".toml",".ini",".log",".csv",".py",".rb",".go",".rs",".sh",".c",".h",".cpp",".java"]}];function hD(A,Q,B){if(A.ext.includes(Q))return!0;return A.mime.some((C)=>C.endsWith("/")?B.startsWith(C):B===C)}function vK(A){let Q=BB(A),B=A?.contentType||"";for(let C of hK)if(hD(C,Q,B))return C.kind;return"file"}var vD={...Object.fromEntries(hK.map((A)=>[A.kind,A.icon])),file:"file"};function dA(A){return vD[vK(A)]||"file"}function bK(A){return vK(A)==="text"}var bD="trove-offline",fK="trove-files-v1",M0=new W0({dimensions:256});class N0{constructor(A){this.platform=A,this.api=A.api,this.db=null,this.state={online:navigator.onLine,pins:[],queued:0,syncing:!1},this.cell=f(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async init(){if(this.db=await fD(),await this.#C(),await this.#E(),window.addEventListener("online",()=>this.#Q()),window.addEventListener("offline",()=>this.#B()),this.state.online&&!await this.api.reachable())this.#A({online:!1});if(this.platform.plugins?.setOnline?.(this.state.online),this.state.online)this.flushQueue()}async#Q(){if(!await this.api.reachable()){this.#A({online:!1}),await this.platform.plugins?.setOnline?.(!1);return}this.#A({online:!0}),await this.platform.plugins?.setOnline?.(!0),await this.flushQueue()}async#B(){this.#A({online:!1}),await this.platform.plugins?.setOnline?.(!1)}isPinned(A){return this.state.pins.some((Q)=>Q.id===A)}async pin(A){if(!A?.id)return;try{if("caches"in window){let E=await caches.open(fK),K=this.platform.mediaUrls,J=K.cacheKey(A.id),{url:Y}=await K.url(A.id,{op:"download"}),I=await fetch(Y);if(!I.ok)throw Error(`Couldn't fetch the file (${I.status})`);await E.put(new Request(J),I)}let Q=[],B="";if(bK(A))try{B=await this.api.readText(A.id);let E=yK(B,1000,150),K=await M0.embed(E.length?E:[A.name]);Q=(E.length?E:[A.name]).map((J,Y)=>({text:J,vector:K[Y]}))}catch{}let C=(await M0.embed([A.name]))[0];await mD(this.db,"pins",A.id,{node:A,text:B,chunks:Q,nameVec:C,pinnedAt:Date.now()}),await this.#C(),this.platform.notifications.success(`“${A.name}” is available offline`)}catch(Q){this.platform.notifications.error(`Couldn't make available offline: ${Q.message}`)}}async unpin(A){if(this.state.pins.find((B)=>B.id===A)&&"caches"in window)await(await caches.open(fK)).delete(this.platform.mediaUrls.cacheKey(A),{ignoreVary:!0}).catch(()=>{});await V0(this.db,"pins",A),await this.#C()}async#C(){let A=await P0(this.db,"pins");this.#A({pins:A.map((Q)=>({id:Q.node.id,name:Q.node.name,contentType:Q.node.contentType,collectionId:Q.node.collectionId,pinnedAt:Q.pinnedAt}))})}async searchOffline(A,{limit:Q=40}={}){let B=await P0(this.db,"pins");if(!B.length)return[];let C=F0(A),E=(await M0.embed([A]))[0],K=[];for(let J of B){let Y=F0(`${J.node.name} ${J.text||""}`),I=lD(C,new Set(Y)),D=uK(E,J.nameVec);for(let G of J.chunks||[])D=Math.max(D,uK(E,G.vector));let L=0.6*D+0.4*I;if(L>0.02)K.push({nodeId:J.node.id,node:J.node,score:L,snippet:dD(J.text,C),indexerId:"offline"})}return K.sort((J,Y)=>Y.score-J.score).slice(0,Q)}async queueOp(A){await pD(this.db,"queue",{...A,at:Date.now()}),await this.#E()}async#E(){let A=await P0(this.db,"queue");this.#A({queued:A.length})}async flushQueue(){if(!this.state.online||this.state.syncing)return;this.#A({syncing:!0});let A=0,Q=0;try{let B=await cD(this.db,"queue");for(let{key:C,value:E}of B)try{await this.api.request(E.method,E.path,{body:E.body}),await V0(this.db,"queue",C),A++}catch(K){if(["transient","timeout","unauthorized","quota"].includes(K.code))break;await V0(this.db,"queue",C),Q++}}finally{if(await this.#E(),this.#A({syncing:!1}),Q)this.platform.notifications.warn(`${Q} offline change${Q>1?"s":""} couldn't be applied and ${Q>1?"were":"was"} discarded.`);if(A&&this.state.queued===0)this.platform.notifications.info(`${A} offline change${A>1?"s":""} synced.`)}}}function fD(){return new Promise((A,Q)=>{let B=indexedDB.open(bD,1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains("pins"))C.createObjectStore("pins");if(!C.objectStoreNames.contains("queue"))C.createObjectStore("queue",{autoIncrement:!0})},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function CB(A,Q,B,C){return new Promise((E,K)=>{let J=A.transaction(Q,B),Y=J.objectStore(Q),I;Promise.resolve(C(Y)).then((D)=>I=D),J.oncomplete=()=>E(I),J.onerror=()=>K(J.error)})}var uD=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),mD=(A,Q,B,C)=>CB(A,Q,"readwrite",(E)=>E.put(C,B)),pD=(A,Q,B)=>CB(A,Q,"readwrite",(C)=>C.add(B)),V0=(A,Q,B)=>CB(A,Q,"readwrite",(C)=>C.delete(B)),P0=(A,Q)=>CB(A,Q,"readonly",(B)=>uD(B.getAll()));function cD(A,Q){return CB(A,Q,"readonly",(B)=>new Promise((C,E)=>{let K=[],J=B.openCursor();J.onsuccess=()=>{let Y=J.result;if(!Y)return C(K);K.push({key:Y.key,value:Y.value}),Y.continue()},J.onerror=()=>E(J.error)}))}function lD(A,Q){if(!A.length||!Q.size)return 0;let B=0;for(let C of A)if(Q.has(C))B++;return B/A.length}function uK(A,Q){if(!A||!Q)return 0;let B=0;for(let C=0;C<A.length;C++)B+=A[C]*Q[C];return B}function dD(A,Q){if(!A)return null;let B=A.toLowerCase(),C=-1;for(let K of Q){let J=B.indexOf(K);if(J>=0){C=J;break}}if(C<0)return A.slice(0,160).trim();let E=Math.max(0,C-60);return(E>0?"…":"")+A.slice(E,E+200).trim()+"…"}var nD=1000,oD=60000;class q0{constructor(A){this.platform=A,this.api=A.api,this.state={tasks:[],issues:[],issuesLoading:!1,tasksError:null,issuesError:null,open:!1},this.cell=f(this.state),this._local=new Map,this._server=[],this._timer=null,this._pollMs=null}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}#Q(){this.#A({tasks:[...this._local.values(),...this._server]})}start(A={}){let Q=A.id||`local_${Math.random().toString(36).slice(2,10)}`,B={id:Q,source:"local",kind:A.kind||"general",title:A.title||"Working",detail:A.detail??null,status:"running",done:0,total:A.total??null,unit:A.unit||null,cancellable:!!A.onCancel,startedAt:Date.now(),endedAt:null,error:null};if(this._local.set(Q,B),this._cancels||=new Map,A.onCancel)this._cancels.set(Q,A.onCancel);this.#Q(),this.#E();let C=(E)=>{let K=this._local.get(Q);if(!K||K.status!=="running")return;this._local.set(Q,{...K,...E}),this.#Q()};return{id:Q,progress:(E={})=>C({done:E.done??this._local.get(Q)?.done??0,total:E.total===void 0?this._local.get(Q)?.total:E.total,unit:E.unit??this._local.get(Q)?.unit,detail:E.detail??this._local.get(Q)?.detail}),succeed:(E)=>{C({status:"done",endedAt:Date.now(),detail:E??this._local.get(Q)?.detail}),this.#B(Q)},fail:(E)=>{C({status:"failed",endedAt:Date.now(),error:E?.message||String(E||"failed")})},cancel:()=>{C({status:"cancelled",endedAt:Date.now()}),this.#B(Q)}}}#B(A,Q=5000){setTimeout(()=>{this._local.delete(A),this._cancels?.delete(A),this.#Q()},Q)}async cancel(A){if(this._local.get(A)){this._cancels?.get(A)?.();return}try{await this.api.cancelTask(A),await this.refreshTasks()}catch(B){this.#A({tasksError:B.message})}}dismiss(A){if(this._local.delete(A)){this.#Q();return}this.api.dismissTask(A).catch(()=>{}),this._server=this._server.filter((Q)=>Q.id!==A),this.#Q()}async init(){await this.refresh(),this.#E(),window.addEventListener("focus",()=>this.refresh())}async refresh(){await Promise.all([this.refreshTasks(),this.refreshIssues()])}async refreshTasks(){let A=this.running.length>0;try{let{tasks:Q}=await this.api.tasks();this._server=(Q||[]).map((B)=>({...B,source:"server"})),this.#A({tasksError:null}),this.#Q()}catch(Q){this._server=[],this.#A({tasksError:Q.message}),this.#Q()}if(A&&!this.running.length)this.refreshIssues();this.#E()}async refreshIssues(){this.#A({issuesLoading:!0});try{let{issues:A}=await this.api.issues();this.#A({issues:A||[],issuesLoading:!1,issuesError:null})}catch(A){this.#A({issuesLoading:!1,issuesError:A.message})}}async retryIssue(A){try{await this.api.retryIssue(A),await this.refreshTasks(),this.#C(),this.platform.notifications?.info?.("Retrying — watch its progress in Activity")}catch(Q){this.platform.notifications?.error?.(`Couldn't retry: ${Q.message}`)}}async dismissIssue(A){let Q=this.state.issues;this.#A({issues:Q.filter((B)=>B.id!==A)});try{await this.api.dismissIssue(A)}catch(B){this.#A({issues:Q}),this.platform.notifications?.error?.(`Couldn't dismiss: ${B.message}`)}}#C(){for(let A of[400,1500])setTimeout(()=>{this.refreshTasks(),this.refreshIssues()},A)?.unref?.()}async rebuildIndex(){try{let A=await this.api.reindex();if(await this.refreshTasks(),this.togglePanel(!0),A.alreadyRunning)this.platform.notifications?.info?.("A rebuild is already running");return A}catch(A){throw this.platform.notifications?.error?.(`Couldn't rebuild the index: ${A.message}`),A}}async scanCollection(A){try{let Q=await this.api.scanCollection(A);if(await this.refreshTasks(),this.togglePanel(!0),Q.alreadyRunning)this.platform.notifications?.info?.("A scan of this collection is already running");return this.#C(),Q}catch(Q){throw this.platform.notifications?.error?.(`Couldn't scan “${A}”: ${Q.message}`),Q}}togglePanel(A){if(this.#A({open:A??!this.state.open}),this.state.open)this.refresh()}get running(){return this.state.tasks.filter((A)=>A.status==="running")}#E(){let A=this.running.length?nD:oD;if(this._timer&&this._pollMs===A)return;clearTimeout(this._timer),this._pollMs=A,this._timer=setTimeout(()=>{this._timer=null,this.refreshTasks().then(()=>{if(!this.running.length)this.refreshIssues()})},A),this._timer?.unref?.()}dispose(){clearTimeout(this._timer),this._timer=null}}function aD(A,Q=null){return{...A?.meta||{},...Q||A?.tags||{}}}function sD(A,Q){if(Q.present)return A!=null&&A!==!1&&A!=="";if(A==null)return!1;let B=Number(A),C=Number(Q.value),E=A!==""&&A!==!0&&A!==!1&&Q.value!==""&&Q.value!=null&&!Number.isNaN(B)&&!Number.isNaN(C),K=E?B:String(A).toLowerCase(),J=E?C:String(Q.value).toLowerCase();switch(Q.op){case"!=":return K!==J;case"<":return K<J;case"<=":return K<=J;case">":return K>J;case">=":return K>=J;default:return K===J}}function mK(A,Q,B=null){let C=aD(A,B);return(Q||[]).every((E)=>sD(C[E.key],E))}var iD=/#([\w.-]+)(?::(<=|>=|!=|=|<|>)?("[^"]*"|[^#\s]+)?)?/g;function pB(A){let Q=[],B=A;for(let C of A.matchAll(iD)){let[,E,K,J]=C,Y=J&&J.startsWith('"')?J.slice(1,-1):J;Q.push(Y==null||Y===""?{key:E,present:!0}:{key:E,op:K||"=",value:Y,present:!1}),B=B.replace(C[0]," ")}return{text:B.replace(/\s+/g," ").trim(),filters:Q}}function pK(A,Q){if(!Q||!Q.length)return!0;return mK(A,Q)}function z0(A){return A.present?`#${A.key}`:`#${A.key}:${A.op}${A.value}`}var cB="openers.associations";function cK(A){return BB(A)||A?.contentType||""}function lK(A){let Q=BB(A);if(Q)return`${Q} files`;let B=A?.contentType||"";return B?`${B} files`:"this file type"}function lB(A,Q){let B=(E)=>A.context.evaluate(E),C=(E)=>A.plugins.isAvailable(E);return A.contributions.openersFor(Q).filter((E)=>(!E.when||B(E.when))&&C(E)).sort((E,K)=>(K.priority??0)-(E.priority??0))}function dK(A,Q){let B=A.settings.get(cB)||{},C=BB(Q),E=Q?.contentType||"",K=E.includes("/")?`${E.slice(0,E.indexOf("/")+1)}*`:"";return C&&B[C]||E&&B[E]||K&&B[K]||null}function dB(A,Q,B){if(!Q)return;let C={...A.settings.get(cB)||{}};if(B)C[Q]=B;else delete C[Q];A.settings.set(cB,C)}function nK(A){let Q=A.settings.get(cB)||{};return Object.entries(Q).map(([B,C])=>{let E=A.contributions.get(C);return{typeKey:B,openerId:C,openerTitle:E?.title||C,missing:!E}})}function oK(A,Q){if(!Q?.pluginId)return"Built-in";return A.plugins.plugins.get(Q.pluginId)?.manifest?.displayName||Q.pluginId}class WA extends QB{static deps=["app"]}class jA extends WA{constructor(A){super();this.collectionId=A}async execute({app:A}){let{explorer:Q,platform:B}=A,C=this.collectionId||Q.state.collectionId||"default",E=C!==Q.state.collectionId;Q.set({loading:!0,error:null,collectionId:C,...E?{trash:null}:{}});try{let K=B.settings.get("explorer.sort"),J=B.settings.get("explorer.sortOrder"),Y=await B.api.list({sort:K,order:J,collection:C});Q.set({items:Y.items,loading:!1,selection:[],sort:K,order:J,collectionId:Y.collectionId||C,stats:Y.stats||null,usage:Y.usage||null,nextCursor:Y.nextCursor||null}),B.settings.set?.("explorer.lastCollection",C)}catch(K){Q.set({loading:!1,error:K.message}),B.notifications.error(`Couldn't load this collection: ${K.message}`)}}}class nB extends WA{async execute({app:A}){try{let Q=await A.platform.api.collections(),B=Q.collections||[];return A.explorer.set({collections:B,canCreateCollection:!!Q.canCreate}),B}catch{return[]}}}class oB extends WA{async execute({app:A}){let Q=[];try{let K=await A.platform.api.collections();Q=K.collections||[],A.explorer.set({collections:Q,canCreateCollection:!!K.canCreate})}catch(K){A.explorer.set({loading:!1,error:`Couldn't load your collections: ${K.message}`});return}let B=Q.map((K)=>K.id),C=A.platform.settings.get("explorer.lastCollection");if(!B.length){A.explorer.set({loading:!1,items:[],collections:[],error:"You do not have access to any collections yet. Ask an administrator to grant you one."});return}let E=B.includes(C)?C:B.includes("default")?"default":B[0];return A.engine.dispatch(new jA(E))}}class O0 extends WA{constructor(A){super();this.record=A}async execute({app:A}){try{let Q=await A.platform.api.createCollection(this.record);A.platform.notifications.success(`Created collection “${Q.collection.name}”`),await A.engine.dispatch(new nB),A.engine.dispatch(new jA(Q.collection.id))}catch(Q){A.platform.notifications.error(`Couldn’t create collection: ${Q.message}`)}}}class j0 extends WA{async execute({app:A}){let{explorer:Q,platform:B}=A,C=Q.state.nextCursor;if(!C||Q.state.loadingMore)return;Q.set({loadingMore:!0});try{let E=await B.api.list({sort:Q.state.sort,order:Q.state.order,collection:Q.state.collectionId,cursor:C});Q.set({items:[...Q.state.items,...E.items],nextCursor:E.nextCursor||null,loadingMore:!1})}catch(E){Q.set({loadingMore:!1}),B.notifications.error(`Couldn't load more: ${E.message}`)}}}class EB extends WA{async execute({app:A}){return A.engine.dispatch(new jA(A.explorer.state.collectionId))}}class ZQ extends WA{constructor(A="list",Q=null){super();this.op=A,this.id=Q}async execute({app:A}){let{explorer:Q,platform:B}=A,C=Q.state.collectionId;if(this.op==="hide"){Q.set({trash:null});return}try{if(this.op==="restore"){let{node:K}=await B.api.restore(this.id);B.notifications.success(`Restored “${K.name}”`)}else if(this.op==="purge")await B.api.purgeTrash({id:this.id});else if(this.op==="empty"){let{purged:K}=await B.api.purgeTrash({collection:C});B.notifications.success(`Deleted ${K} item${K===1?"":"s"} for good`)}let{items:E}=await B.api.trash(C);if(Q.set({trash:E}),this.op!=="list")await A.engine.dispatch(new jA(C))}catch(E){B.notifications.error(`Trash: ${E.message}`)}}}class S0 extends WA{constructor(A){super();this.ids=A}async execute({app:A}){try{for(let Q of this.ids)await A.platform.api.remove(Q);A.platform.notifications.info(`Deleted ${this.ids.length} item${this.ids.length>1?"s":""}`);for(let Q of this.ids)A.platform.workbench.closeTab(Q)}catch(Q){A.platform.notifications.error(`Couldn’t delete: ${Q.message}`)}A.engine.dispatch(new EB)}}class w0 extends WA{constructor(A,Q){super();this.id=A,this.newName=Q}async execute({app:A}){try{let Q=await A.platform.api.rename(this.id,this.newName);A.platform.workbench.updateTabNode(Q.node),A.engine.dispatch(new EB)}catch(Q){A.platform.notifications.error(`Couldn’t rename: ${Q.message}`)}}}class SA extends WA{constructor(A,Q={}){super();this.node=A,this.opts=Q}async execute({app:A}){if(!this.node)return;let{platform:Q}=A,B=(K)=>Q.workbench.openFile(this.node,K,{reset:!!this.opts.reset});if(this.opts.openerId)return B(this.opts.openerId);let C=lB(Q,this.node),E=dK(Q,this.node);if(E&&C.some((K)=>K.id===E))return B(E);if(C.length>1)return Q.workbench.showDialog({kind:"opener-chooser",node:this.node,openers:C,reset:!!this.opts.reset});B(C[0]?.id||"core.fallback")}}class KB extends WA{constructor(A,Q){super();this.files=A,this.collectionId=Q}async execute({app:A}){let Q=this.collectionId||A.explorer.state.collectionId||"default",B=A.platform.settings.get("uploads.concurrency"),C=[...this.files].map((E)=>this.#A(A,E,Q,B));await Promise.allSettled(C),A.engine.dispatch(new jA(Q))}async#A(A,Q,B,C){let{transfers:E,platform:K}=A,J=WE("xfer"),Y=new AbortController;E.start(J,Q.name,Q.size,Y);let I=null;try{let D=await K.api.upload(Q,{collection:B,concurrency:C,signal:Y.signal,onStart:(L)=>{I=L},onProgress:(L)=>E.progress(J,L)});if(E.finish(J,"done"),D?.name&&D.name!==Q.name)K.notifications.info(`"${Q.name}" already existed — saved as "${D.name}".`)}catch(D){if(I)K.api.abortUpload(I).catch(()=>{});if(D.code==="aborted")E.finish(J,"cancelled");else E.finish(J,"error",D.message),K.notifications.error(`Upload failed: ${Q.name} — ${D.message}`)}}}class JB extends WA{constructor(A,Q){super();this.filters=A||[],this.text=Q||""}async execute({app:A}){let{search:Q,platform:B}=A;if(!this.filters.length){Q.set({results:[],ran:!1,filtered:!1});return}if(Q.set({query:this.text,loading:!0,error:null,filtered:!0}),A.offline&&!A.offline.state.online){let C=(A.explorer.state.items||[]).filter((E)=>pK(E,this.filters));Q.set({results:C.map((E)=>({node:E})),loading:!1,ran:!0,filtered:!0,offline:!0});return}try{let C=await B.api.tagSearch(this.filters,this.text.trim()||void 0,{limit:100});Q.set({results:(C.items||[]).map((E)=>({node:E})),loading:!1,ran:!0,filtered:!0,offline:!1})}catch(C){Q.set({loading:!1,error:C.message,ran:!0,filtered:!0})}}}class T0 extends WA{constructor(A){super();this.query=A}async execute({app:A}){let{search:Q,platform:B}=A,C=(this.query||"").trim();if(!C){Q.set({paletteFiles:[],paletteQuery:"",paletteError:null,paletteLoading:!1});return}Q.set({paletteQuery:C,paletteLoading:!0,paletteError:null});try{let E=await B.api.search(C,{mode:"keyword",limit:30});if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:E.results||[],paletteLoading:!1})}catch(E){if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:[],paletteLoading:!1,paletteError:E?.message||"Search failed"})}}}class KQ extends WA{constructor(A,Q){super();this.query=A,this.mode=Q}async execute({app:A}){let{search:Q,platform:B}=A,C=this.query.trim();if(!C){Q.set({query:"",results:[],ran:!1,error:null,resolved:null});return}let E=this.mode||B.settings.get("search.mode");Q.set({query:this.query,mode:E,loading:!0,error:null,resolved:null});let K=A.offline;if(K&&!K.state.online){try{let J=await K.searchOffline(C,{limit:40});Q.set({results:J,loading:!1,ran:!0,offline:!0,resolved:null})}catch(J){Q.set({results:[],loading:!1,ran:!0,offline:!0,error:J.message})}return}try{let J=B.contributions.ofType("view").map((I)=>({id:I.id,title:I.title||I.id})),Y=await B.api.query(C,{mode:E,limit:40,views:J});Q.set({results:Y.results,resolved:Y.resolved||null,loading:!1,ran:!0,offline:!1})}catch(J){if(K){let Y=await K.searchOffline(C,{limit:40});Q.set({results:Y,loading:!1,ran:!0,offline:!0,error:Y.length?null:J.message})}else Q.set({loading:!1,error:J.message,ran:!0})}}}async function aK(A,Q){try{let B=new Uint8Array(await Q.arrayBuffer());await iK(A,$Q(B))}catch(B){A.platform.notifications.error(`Couldn't read the plugin: ${B.message}`)}}async function sK(A,Q){try{let B=await KK(Q,(C,E)=>fetch(C,E));await iK(A,B)}catch(B){A.platform.notifications.error(`Couldn't fetch the plugin: ${B.message}`)}}async function iK(A,Q){let B=OA(Q.manifest);if(A.platform.plugins.plugins.has(yA(Q.manifest))){A.platform.notifications.warn(`“${B}” is already installed.`);return}let C={status:"unverified"};try{C=await A.platform.plugins.assessTrust(Q)}catch{}let E=JK(Q,C);A.platform.workbench.showDialog({kind:"plugin-review",summary:E,isAdmin:!!A.social.state.admin,onInstall:async(K)=>{A.platform.workbench.closeDialog(),A.platform.workbench.setActivity("plugins");let J=A.platform.notifications.info(`Installing “${B}”…`,{sticky:!0});try{await A.platform.plugins.install(Q,{grants:K,trust:C}),A.platform.notifications.dismiss(J),A.platform.notifications.success(`Installed “${B}”`)}catch(Y){A.platform.notifications.dismiss(J),A.platform.notifications.error(`Install failed: ${Y.message}`)}}})}function rK(A){let{platform:Q,engine:B,explorer:C}=A,{commands:E,workbench:K}=Q,J=(L)=>B.dispatch(L),Y=(L,G,X,Z={})=>E.register({id:L,title:G,handler:X,...Z});Y("workbench.showCommandPalette","Show All Commands",()=>K.openPalette("commands"),{category:"View",icon:"command"}),Y("workbench.quickOpen","Go to File…",()=>K.openPalette("files"),{category:"File",icon:"search"}),Y("workbench.view.home","Go Home (search & browse)",()=>K.showHome(),{category:"View",icon:"search"}),Y("workbench.view.plugins","Show Plugins",()=>K.setActivity("plugins"),{category:"View"}),Y("workbench.openSettings","Open Settings",()=>K.setActivity("settings"),{category:"Preferences",icon:"gear"}),Y("workbench.closeOverlays","Close",()=>K.closeOverlays(),{palette:!1}),Y("search.voice","Search by Voice",async()=>{await Q.voice.run({onText:(L,{final:G})=>{if(!L)return;if(K.setLaunchQuery(L),G)J(new KQ(L))}})},{category:"View",icon:"search"}),Y("workbench.showActivity","Show Activity (running work & problems)",()=>A.activity.togglePanel(!0),{category:"View",icon:"refresh"}),Y("workbench.rebuildIndex","Rebuild Search Index",()=>A.activity.rebuildIndex().catch(()=>{}),{category:"View",icon:"refresh"}),Y("workbench.scanCollection","Scan Collection for Outside Changes",()=>A.activity.scanCollection(C.state.collectionId||"default").catch(()=>{}),{category:"Explorer",icon:"refresh"}),Y("explorer.refresh","Refresh",()=>J(new EB),{category:"Explorer",icon:"refresh"}),Y("explorer.loadMore","Show More Items",()=>J(new j0),{palette:!1}),Y("explorer.upload","Upload Files…",()=>{rD((L)=>L.length&&J(new KB(L,C.state.collectionId)))},{category:"Explorer",icon:"upload"});let I=(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(!G)Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return G};Y("explorer.copyLink","Copy Link to Item",async()=>{let L=I();if(!L)return;let G=mB(L);try{await navigator.clipboard.writeText(G),Q.notifications.success(`Copied ${G}`)}catch{Q.notifications.info(G,{sticky:!0})}},{category:"Explorer",icon:"link"}),Y("explorer.rename","Rename",()=>{let L=I();if(!L)return;K.showDialog({kind:"prompt",title:"Rename",label:"New name",value:L.name,confirmLabel:"Rename",onSubmit:(G)=>{if(K.closeDialog(),G?.trim()&&G!==L.name)J(new w0(L.id,G.trim()))}})},{category:"Explorer"}),Y("explorer.delete","Delete",()=>{let L=C.selectedNodes(),G=L.length?null:K.activeTab()?.node;if(G)L.push(G);if(!L.length){Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return}let X=()=>J(new S0(L.map((Z)=>Z.id)));if(Q.settings.get("explorer.confirmDelete"))K.showDialog({kind:"confirm",title:`Move ${L.length} item${L.length>1?"s":""} to the trash?`,body:L.length===1?`"${L[0].name}" leaves the drive but is kept, and can be restored from the trash.`:"They leave the drive but are kept, and can be restored from the trash.",confirmLabel:"Move to trash",onConfirm:()=>{K.closeDialog(),X()}});else X()},{category:"Explorer",icon:"trash"}),Y("explorer.showTrash","Show Trash",()=>{J(new ZQ("list")),K.showHome()},{category:"Explorer",icon:"trash"}),Y("explorer.hideTrash","Hide Trash",()=>J(new ZQ("hide")),{palette:!1}),Y("explorer.restore","Restore from Trash",(L)=>L&&J(new ZQ("restore",L)),{palette:!1}),Y("explorer.purgeOne","Delete Forever",(L)=>L&&J(new ZQ("purge",L)),{palette:!1}),Y("explorer.emptyTrash","Empty Trash",()=>{K.showDialog({kind:"confirm",title:"Empty the trash?",body:"Everything in the trash will be destroyed. This cannot be undone.",danger:!0,confirmLabel:"Delete forever",onConfirm:()=>{K.closeDialog(),J(new ZQ("empty"))}})},{category:"Explorer",icon:"trash"}),Y("explorer.open","Open",(L)=>J(new SA(L||C.selectedNodes()[0])),{palette:!1}),Y("explorer.download","Download",async(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(!G?.id)return;try{let{url:X,revoke:Z}=await Q.api.download(G.id,G.name);if(eD(X,G.name),Z)setTimeout(()=>URL.revokeObjectURL(X),60000)}catch(X){Q.notifications.error(`Couldn't download ${G.name}: ${X.message}`)}},{category:"Explorer",icon:"download"}),Y("offline.pin","Make Available Offline",(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(G?.id)A.offline.pin(G)},{category:"Offline",icon:"download"}),Y("offline.unpin","Remove from Offline",(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(G)A.offline.unpin(G.id)},{palette:!1});let D=()=>{let L=C.state.collectionId||"default",G=(C.state.collections||[]).map((X)=>({label:X.name||X.id,icon:X.id===L?"check":"files",run:()=>E.execute("collections.switch",X.id)}));if(C.state.canCreateCollection){if(G.length)G.push({sep:!0});G.push({label:"New collection…",icon:"plus",run:()=>E.execute("collections.create")})}return G};A.collectionMenu=D,Y("collections.switch","Switch Collection…",(L)=>{if(L){J(new jA(L)),K.showHome();return}let G=D();if(!G.length)return Q.notifications.info("This drive has one collection.");let X=typeof window>"u"?800:window.innerWidth;K.showContextMenu(Math.max(12,Math.round(X/2)-110),120,G)},{category:"Collections",icon:"files"}),Y("collections.create","New Collection…",()=>{K.showDialog({kind:"collection",title:"New collection",onSubmit:(L)=>{if(K.closeDialog(),L)J(new O0(L))}})},{category:"Collections",icon:"files"}),Y("workbench.toggleInfoPanel","Toggle Details & Conversation",()=>{if(!K.activeTab()){Q.notifications.info("Open a file to see its details and conversation.");return}K.toggleInfoPanel()},{category:"View",icon:"info"}),Y("notifications.show","Show Notifications",()=>A.social.toggleInbox(!0),{category:"View"}),Y("notifications.enablePush","Enable Push Notifications",()=>A.social.enablePush(),{category:"Notifications"}),Y("plugins.installFromUrl","Install Plugin from URL…",()=>{K.showDialog({kind:"prompt",title:"Install plugin from URL",label:"Plugin package (.zip) URL",placeholder:"https://example.com/plugin.zip",confirmLabel:"Fetch",onSubmit:(L)=>{if(K.closeDialog(),L?.trim())sK(A,L.trim())}})},{category:"Plugins",icon:"plug"}),Y("plugins.installFromFile","Install Plugin from File…",()=>{tD((L)=>L&&aK(A,L))},{category:"Plugins",icon:"plug"})}function tK(A,Q){let B=document.createElement("input");B.type="file",Q(B),B.style.display="none",document.body.appendChild(B);let C=()=>{B.remove(),window.removeEventListener("focus",E)},E=()=>setTimeout(()=>{if(!B.files.length)C()},300);B.addEventListener("change",()=>{A(B.files),C()},{once:!0}),window.addEventListener("focus",E),B.click()}function rD(A){tK((Q)=>A(Q),(Q)=>{Q.multiple=!0})}function tD(A){tK((Q)=>A(Q[0]),(Q)=>{Q.accept=".zip,application/zip"})}function eD(A,Q){let B=document.createElement("a");B.href=A,B.download=Q||"",document.body.appendChild(B),B.click(),B.remove()}function eK(A){let Q=new X0(A.settings),B=new H0,C=new q0(A),E=new $0(C),K=new Z0(A),J=new N0(A);K.offline=J;let Y={platform:A,explorer:Q,search:B,transfers:E,social:K,offline:J,activity:C,engine:null},I=new fB({providers:{app:CQ.fromSingleton(Y)}});Y.engine=I,rK(Y),A.openPluginPanel=(L)=>A.workbench.openPluginPanel(L),A.context.setMany({"explorer.collectionId":"default","explorer.hasSelection":!1}),_A(Q.observe(),(L)=>{A.context.setMany({"explorer.collectionId":L.collectionId||"default","explorer.hasSelection":(L.selection?.length||0)>0})});let D=null;return _A(A.workbench.observeNav(),(L)=>{if(L.activeTabId!==D)D=L.activeTabId,K.loadSidecar(L.activeFile?L.activeFile.id:null)}),K.init(),J.init(),C.init(),I.dispatch(new nB),{engine:I,app:Y}}var{svg:AG,h:QG}=w,_0={link:[{d:"M10 13a5 5 0 0 0 7.07 0l3-3A5 5 0 0 0 13 3l-1.5 1.5"},{d:"M14 11a5 5 0 0 0-7.07 0l-3 3A5 5 0 0 0 11 21l1.5-1.5"}],file:[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5"}],"file-text":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M9 13h6M9 17h6M9 9h2"}],"file-image":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5"},{d:"M8.5 15l2-2 3 3 2-1.5"},{d:"M10 12a1 1 0 1 0 0-.01"}],"file-audio":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M10 12v5M13 10v9"}],"file-video":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M10 12l4 2.5-4 2.5z"}],book:[{d:"M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"},{d:"M4 19a2 2 0 0 1 2-2h13"}],search:[{d:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-3.5-3.5"}],mic:[{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},{d:"M5 11a7 7 0 0 0 14 0M12 18v3M9 21h6"}],command:[{d:"M8 6a2 2 0 1 0-2 2h12a2 2 0 1 0-2-2v12a2 2 0 1 0 2-2H6a2 2 0 1 0 2 2z"}],gear:[{d:"M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"},{d:"M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 2h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 22h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6A7 7 0 0 0 19 12z"}],upload:[{d:"M12 16V4M7 9l5-5 5 5M4 20h16"}],download:[{d:"M12 4v12M7 11l5 5 5-5M4 20h16"}],trash:[{d:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"}],refresh:[{d:"M20 11a8 8 0 1 0-.5 4M20 5v6h-6"}],"chevron-right":[{d:"M9 6l6 6-6 6"}],"chevron-left":[{d:"M15 6l-6 6 6 6"}],"chevron-down":[{d:"M6 9l6 6 6-6"}],close:[{d:"M6 6l12 12M18 6L6 18"}],tag:[{d:"M4 4h6.5a1 1 0 0 1 .7.3l8.5 8.5a1 1 0 0 1 0 1.4l-5.5 5.5a1 1 0 0 1-1.4 0L4.3 11.2a1 1 0 0 1-.3-.7V4z"},{d:"M8 8a0.6 0.6 0 1 0 0-.01"}],play:[{d:"M8 5v14l11-7z",fill:"currentColor",stroke:"none"}],pause:[{d:"M8 5h3v14H8zM13 5h3v14h-3z",fill:"currentColor",stroke:"none"}],"skip-back":[{d:"M11 6v12L3 12zM13 6l8 6-8 6zM21 6v12",fill:"none"}],"skip-forward":[{d:"M13 6v12l8-6zM3 6l8 6-8 6zM3 6v12"}],"back-30":[{d:"M11 8a7 7 0 1 0 7 7"},{d:"M11 4l-3 4 4 1"}],"fwd-30":[{d:"M13 8a7 7 0 1 1-7 7"},{d:"M13 4l3 4-4 1"}],plug:[{d:"M9 3v6M15 3v6M6 9h12v3a6 6 0 0 1-12 0zM12 18v3"}],bell:[{d:"M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9z"},{d:"M13.73 21a2 2 0 0 1-3.46 0"}],files:[{d:"M4 4h9l3 3v3M8 8h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2z"}],dots:[{d:"M5 12h.01M12 12h.01M19 12h.01"}],check:[{d:"M5 12l5 5L20 6"}],plus:[{d:"M12 5v14M5 12h14"}],"arrow-up":[{d:"M12 19V5M6 11l6-6 6 6"}],star:[{d:"M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z"}],info:[{d:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01"}],warn:[{d:"M12 3l9 16H3zM12 10v4M12 17h.01"}],x:[{d:"M6 6l12 12M18 6L6 18"}],list:[{d:"M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01"}],grid:[{d:"M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z"}]};function W(A,{size:Q=18,strokeWidth:B=1.6,className:C}={}){let E=Object.hasOwn(_0,A)?_0[A]:_0.file;return AG({$attrs:{viewBox:"0 0 24 24",width:Q,height:Q,fill:"none",stroke:"currentColor","stroke-width":B,"stroke-linecap":"round","stroke-linejoin":"round",...C?{class:C}:{}}},...E.map((K)=>QG("path",{$attrs:BG(K)})))}function BG(A){let Q={d:A.d};if(A.fill)Q.fill=A.fill;if(A.stroke)Q.stroke=A.stroke;return Q}function QA(A){if(A==null||Number.isNaN(A))return"—";let Q=["B","KB","MB","GB","TB"],B=0,C=A;while(C>=1024&&B<Q.length-1)C/=1024,B++;return`${C>=100||B===0?Math.round(C):C.toFixed(1)} ${Q[B]}`}function k0(A){if(!A)return"";let Q=Date.now()-A,B=86400000;if(Q<60000)return"just now";if(Q<3600000)return`${Math.floor(Q/60000)}m ago`;if(Q<B)return`${Math.floor(Q/3600000)}h ago`;if(Q<7*B)return`${Math.floor(Q/B)}d ago`;return new Date(A).toLocaleDateString(void 0,{month:"short",day:"numeric",year:Q>330*B?"numeric":void 0})}var{div:T,span:CA,button:VA,textarea:CG,input:EG,p:VZ}=w,KG=["\uD83D\uDC4D","❤️","\uD83C\uDF89","\uD83D\uDC40","\uD83D\uDE80"];function AJ(A){let Q=A.so.me;if(!Q||Q.anonymous)return null;let B=(Q.name||Q.id||"?")[0].toUpperCase();return T({className:"principal",title:Q.email||Q.name||Q.id},Q.picture?w.img({src:Q.picture,alt:"",className:"avatar-img"}):CA({className:"avatar-txt"},B))}function QJ(A,Q){let B=A.so.notifications,C=Q.app.social;return T({className:"bell-wrap"},VA({className:"iconbtn bell",title:"Notifications"},W("bell",{size:19}),B.unread?CA({className:"bell-badge"},String(B.unread>9?"9+":B.unread)):null).on({click:()=>C.toggleInbox()}),A.so.inboxOpen?JG(A,Q):null)}function JG(A,Q){let B=A.so.notifications.items,C=Q.app.social;return T({},T({className:"scrim",$styling:{background:"transparent","z-index":"54"}}).on({click:()=>C.toggleInbox(!1)}),T({className:"inbox"},T({className:"inbox-head"},CA("Notifications"),A.so.pushSupported&&!A.so.pushEnabled?VA({className:"link"},"Enable push").on({click:()=>C.enablePush()}):A.so.pushEnabled?CA({className:"muted"},W("check",{size:13})):null),B.length?T({className:"inbox-items"},...B.slice(0,30).map((E)=>YG(E,Q))):T({className:"inbox-empty"},W("info",{size:24}),CA("You’re all caught up."))))}function YG(A,Q){let B=A.items?.[0];return T({className:`inbox-item ${A.read?"":"unread"}`},T({className:"ii-title"},A.title),B?.excerpt?T({className:"ii-excerpt"},"“"+B.excerpt+"”"):null,T({className:"ii-time"},k0(A.createdAt))).on({click:()=>{if(B?.nodeId)Q.platform.api.stat(B.nodeId).then((C)=>{Q.go(new SA(C.node)),Q.platform.workbench.toggleInfoPanel(!0)}).catch((C)=>{Q.platform.notifications.warn(C?.status===403||C?.code==="forbidden"?"You no longer have access to that item.":"That item no longer exists.")});Q.app.social.toggleInbox(!1)}})}function x0(A,Q){let B=A.nav,C=B.activeFile?{id:B.activeTabId,node:B.activeFile}:null,E=A.so.sidecar;return T({className:"infopanel"},T({className:"ip-head"},W("info",{size:15}),CA("Details"),VA({className:"iconbtn",title:"Close"},W("close",{size:14})).on({click:()=>Q.platform.workbench.toggleInfoPanel(!1)})),!C?T({className:"ip-empty"},CA("Open a file to see its tags and conversation.")):T({className:"ip-body"},IG(C.node,A,Q),LG(C.node,A,Q),GG(E,Q),XG(A,E,Q)))}function IG(A,Q,B){let C=B.app.offline.isPinned(A.id);return T({className:"ip-file"},T({className:"ip-name"},A.name),T({className:"ip-path"},A.contentType||""),VA({className:`btn small ${C?"on":""}`,$styling:{"margin-top":"10px"}},W(C?"check":"download",{size:14}),C?"Available offline":"Make available offline").on({click:()=>C?B.exec("offline.unpin",A):B.exec("offline.pin",A)}))}function LG(A,Q,B){let C=Q.so.backlinks,E=A.collectionId?mB(A):null,K=C&&C.nodeId===A.id?C:null;return T({className:"ip-section"},T({className:"ip-label"},"Links"),E?VA({className:"ip-uri",title:"Copy this item’s link"},W("link",{size:12}),CA(E)).on({click:()=>DG(B,E)}):null,T({className:"ip-label",$styling:{"margin-top":"10px"}},"Linked from"),K?.loading?T({className:"ip-muted"},"Loading…"):K?.error?T({className:"ip-muted error"},`Couldn’t load links: ${K.error}`):K?.items?.length?T({className:"ip-backlinks"},...K.items.map((J)=>VA({className:"ip-backlink",title:J.name},W("file-text",{size:12}),CA(J.name)).on({click:()=>B.go(new SA(J))}))):T({className:"ip-muted"},"Nothing links here yet."))}async function DG(A,Q){try{await navigator.clipboard.writeText(Q),A.platform.notifications.success(`Copied ${Q}`)}catch{A.platform.notifications.info(Q,{sticky:!0})}}function GG(A,Q){let B=A?.tags||[];return T({className:"ip-section"},T({className:"ip-label"},"Tags"),T({className:"tags"},...B.map((C)=>CA({className:"tag"},C.value?`${C.name}: ${C.value}`:C.name,VA({className:"tag-x"},W("close",{size:11})).on({click:()=>Q.app.social.removeTag(C.name)}))),EG({className:"tag-input",placeholder:"+ tag",value:""}).on({keydown:(C)=>{if(C.key==="Enter"&&C.target.value.trim()){let E=C.target.value.trim(),[K,...J]=E.split(":");Q.app.social.addTag(K.trim(),J.join(":").trim()||void 0),C.target.value=""}}})))}function XG(A,Q,B){if(Q?.loading)return T({className:"ip-section"},T({className:"spinner"}));let C=Q?.comments||[],E=Q?.error?T({className:"conv-empty"},CA(`Couldn't load the conversation: ${Q.error}`),VA({className:"btn",$styling:{"margin-top":"8px"}},"Retry").on({click:()=>B.app.social.loadSidecar(Q.nodeId)})):C.length?T({className:"thread"},...C.map((K)=>BJ(K,A,B,0))):T({className:"conv-empty"},"No comments yet. Start the discussion — use @ to mention someone.");return T({className:"ip-section conv"},T({className:"ip-label"},`Conversation${Q?.commentCount?` · ${Q.commentCount}`:""}`),E,Q?.error?null:HG(A,B))}function BJ(A,Q,B,C){let E=Q.so.me,K=B.app.social,J=E&&A.author?.id===E.id;return T({className:"comment",$styling:C?{marginLeft:"18px"}:{}},T({className:"c-head"},CA({className:"c-avatar"},(A.author?.name||"?")[0].toUpperCase()),CA({className:"c-author"},A.author?.name||A.author?.id||"Someone"),CA({className:"c-time"},k0(A.createdAt),A.edited?" · edited":"")),A.deleted?T({className:"c-body deleted"},"comment deleted"):T({className:"c-body"},$G(A.body)),!A.deleted?T({className:"c-actions"},...KG.map((Y)=>{let I=A.reactions?.[Y]||[];return VA({className:`react ${I.includes(E?.id)?"on":""}`},Y,I.length?CA({className:"rc"},String(I.length)):null).on({click:()=>K.react(A.id,Y)})}),VA({className:"c-link"},"Reply").on({click:()=>K.setReplyTo({id:A.id,author:A.author})}),J?VA({className:"c-link danger"},"Delete").on({click:()=>K.deleteComment(A.id)}):null):null,(A.replies||[]).length?T({className:"replies"},...A.replies.map((Y)=>BJ(Y,Q,B,C+1))):null).key(A.id)}function HG(A,Q){let B=Q.app.social,C=A.so.me,E=A.so.replyTo;if(!C){if(!A.off?.online)return T({className:"conv-signin"},"You’re offline. Conversations come back when you reconnect.");return T({className:"conv-signin"},CA("You’re signed out, so you can read this conversation but not add to it."),VA({className:"c-link"},"Reload to sign in").on({click:()=>window.location.reload()}))}return T({className:"composer"},E?T({className:"replying"},`Replying to ${E.author?.name||"comment"}`,VA({className:"c-link"},"cancel").on({click:()=>B.setReplyTo(null)})):null,CG({className:"composer-input",placeholder:"Write a comment… @mention someone",rows:2,value:""}).on({keydown:(K)=>{if(K.key==="Enter"&&(K.metaKey||K.ctrlKey))B.comment(K.target.value),K.target.value=""}}),T({className:"composer-actions"},CA({className:"muted"},"⌘/Ctrl + Enter"),VA({className:"btn primary",disabled:A.so.posting},"Comment").on({click:(K)=>{let J=K.target.closest(".composer").querySelector(".composer-input");B.comment(J.value),J.value=""}})))}function $G(A){let Q=[],B=/@\[([^\]]+)\]\(([^)]+)\)|(?:^|\s)@([a-zA-Z0-9._@-]{2,})/g,C=0,E;while(E=B.exec(A)){if(E.index>C)Q.push(A.slice(C,E.index+(E[3]?E[0].startsWith(" ")?1:0:0)));Q.push(CA({className:"mention"},"@"+(E[1]||E[3]))),C=B.lastIndex}if(C<A.length)Q.push(A.slice(C));return Q}var{div:CJ,button:g0,span:ZG,img:UG}=w,WG=[{id:"home",icon:"search",title:"Search & files",command:"workbench.view.home"},{id:"plugins",icon:"plug",title:"Plugins",command:"workbench.view.plugins"}];function y0(A,Q){let B=A.wb.activity,C=A.plugins?.filter((E)=>E.status==="active").length||0;return CJ({className:"activitybar"},g0({className:"brand-mark",title:"Trove — home"},UG({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),...WG.map((E)=>g0({className:`item ${B===E.id?"active":""}`,title:E.title},W(E.icon,{size:22}),E.id==="plugins"&&C?ZG({className:"badge"},String(C)):null).on({click:()=>Q.exec(E.command)})),CJ({className:"spacer"}),QJ(A,Q),g0({className:`item ${B==="settings"?"active":""}`,title:"Settings"},W("gear",{size:21})).on({click:()=>Q.exec("workbench.openSettings")}),AJ(A))}var RG=new Set(["SPAN","B","STRONG","I","EM","CODE","SMALL","BR","S","U"]),FG=new Set(["class","title"]);function EJ(A){let Q=document.createDocumentFragment();if(typeof A!=="string"||!A)return Q;let B=document.createElement("template");B.innerHTML=A.slice(0,4096);let C={nodes:200};for(let E of B.content.childNodes){let K=IJ(E,C);if(K)Q.appendChild(K)}return Q}function KJ(A){return(EJ(A).textContent||"").trim()}function JJ(A,Q){return[...EJ(A).childNodes].map((B)=>YJ(B,Q)).filter((B)=>B!=null)}function YJ(A,Q){if(A.nodeType===Node.TEXT_NODE)return A.nodeValue;let B=Q[A.tagName.toLowerCase()];if(!B)return A.textContent;let C={};if(A.className)C.className=A.className;if(A.title)C.title=A.title;return B(C,...[...A.childNodes].map((E)=>YJ(E,Q)).filter((E)=>E!=null))}function IJ(A,Q){if(Q.nodes--<=0)return null;if(A.nodeType===Node.TEXT_NODE)return document.createTextNode(A.nodeValue);if(A.nodeType!==Node.ELEMENT_NODE)return null;if(!RG.has(A.tagName))return null;let B=document.createElement(A.tagName.toLowerCase());for(let C of A.attributes){let E=C.name.toLowerCase();if(!FG.has(E))continue;B.setAttribute(E,C.value.slice(0,200))}for(let C of A.childNodes){let E=IJ(C,Q);if(E)B.appendChild(E)}return B}var{div:UQ,button:WQ,span:EA}=w;function LJ(A,Q){if(A.visible===!1||!A.html)return null;if(A.when&&!Q.platform.context.evaluate(A.when))return null;if(!Q.platform.plugins.isAvailable(A))return null;let B=JJ(A.html,w);if(!B.length)return null;let C=A.tooltip?KJ(A.tooltip):"";return A.command?WQ({className:"seg",title:C},...B).on({click:()=>Q.exec(A.command)}):EA({className:"seg",title:C},...B)}function MG(A,Q){let B=A.act||{tasks:[],issues:[]},C=B.tasks.filter((J)=>J.status==="running"),E=()=>Q.app.activity.togglePanel(!0),K=[];if(C.length){let J=C[0],I=J.total!=null&&J.total>0?Math.round((J.done||0)/J.total*100):null;K.push(WQ({className:"seg sb-activity",title:C.map((D)=>D.title).join(`
|
|
348
|
+
`)},UQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),EA(C.length>1?`${C.length} running`:`${J.title}${I==null?"":` ${I}%`}`)).on({click:E}))}if(B.issues.length)K.push(WQ({className:"seg sb-attention",title:B.issues.map((J)=>J.title).join(`
|
|
349
|
+
`)},W("info",{size:12}),EA(`${B.issues.length} need${B.issues.length===1?"s":""} attention`)).on({click:E}));return K}function h0(A){let Q=A.usage;if(!Q?.total)return null;let B=Q.available/Q.total,C=Math.min(100,Math.round(Q.used/Q.total*100)),E=B<0.05?"critical":B<0.1?"low":"";return EA({className:`seg sb-usage ${E}`,title:`${QA(Q.used)} used of ${QA(Q.total)} — ${QA(Q.available)} free on this volume`},UQ({className:"usage-bar"},UQ({className:"usage-fill",$styling:{width:`${C}%`}})),EA(`${QA(Q.available)} free`))}function aB(A,Q){let B=A.ex,C=B.items||[],E=A.act||{tasks:[],issues:[]};return{collectionId:B.collectionId||"default",totalItems:B.stats?.items??C.length,totalKnown:B.stats?.items!=null,totalBytes:B.stats?.bytes??C.reduce((K,J)=>K+(J.size||0),0),shown:C.length,partial:!!B.nextCursor,usage:B.usage,uploading:A.tr.items.filter((K)=>K.status==="active"),running:E.tasks.filter((K)=>K.status==="running"),issues:E.issues,off:A.off||{online:!0,pins:[],queued:0,syncing:!1},caps:Q.platform.capabilities}}function v0(A,Q){let B=A.ex,C=B.items||[],E=aB(A,Q),{totalItems:K,totalBytes:J,caps:Y}=E,I=E.uploading,D=[...A.statusItems||[]].sort((Z,R)=>(Z.order??0)-(R.order??0)||Z.name.localeCompare(R.name)),L=D.filter((Z)=>Z.slot==="left").map((Z)=>LJ(Z,Q)),G=D.filter((Z)=>Z.slot!=="left").map((Z)=>LJ(Z,Q)),X=E.off;return UQ({className:"statusbar"},!X.online?EA({className:"seg offline-badge",title:"You are offline — pinned files and cached data are available"},W("info",{size:12}),EA("Offline")):X.syncing?EA({className:"seg",title:"Syncing offline changes"},UQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),EA("Syncing…")):null,X.queued?EA({className:"seg",title:"Changes waiting to sync"},`${X.queued} queued`):null,X.pins.length?WQ({className:"seg",title:`${X.pins.length} file(s) available offline`},W("download",{size:12}),EA(`${X.pins.length} offline`),W("chevron-down",{size:11})).on({click:(Z)=>{let R=X.pins.slice(0,12).flatMap((V)=>[{label:V.name,icon:"file-text",run:()=>Q.exec("explorer.open",V)},{label:`Remove “${V.name}” from offline`,icon:"close",run:()=>Q.exec("offline.unpin",V)},{sep:!0}]);if(X.pins.length>12)R.push({label:`…and ${X.pins.length-12} more`,run:()=>{}});let F=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(F.left,F.top-8-R.length*34,R)}}):null,WQ({className:"seg",title:"Switch collection"},W("files",{size:13}),EA(B.collectionId||"default"),(B.collections||[]).length>1||B.canCreateCollection?W("chevron-down",{size:11}):null).on({click:(Z)=>{let R=Q.app.collectionMenu?.()||[];if(R.length>1||B.canCreateCollection){let F=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(F.left,F.top-8-R.length*34,R)}else Q.exec("workbench.view.home")}}),I.length?WQ({className:"seg",title:"Active uploads — click to cancel"},UQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),EA(`${I.length} uploading`)).on({click:(Z)=>Q.platform.workbench.showContextMenu(Z.clientX,Z.clientY,I.map((R)=>({label:`Cancel ${R.name} (${Math.round((R.ratio||0)*100)}%)`,icon:"close",danger:!0,run:()=>Q.app.transfers.cancel(R.id)})))}):EA({className:"seg",title:B.nextCursor?`Showing ${C.length} of ${E.totalKnown?K:"more"}`:""},`${K.toLocaleString()}${E.totalKnown||!E.partial?"":"+"} item${K===1?"":"s"}`),...L,UQ({className:"spacer"}),...MG(A,Q),...G,EA({className:"seg",title:E.totalKnown||!E.partial?"Total size of this collection":`Size of the ${E.shown.toLocaleString()} items loaded so far — this server doesn’t report a collection total`},`${QA(J)}${E.totalKnown||!E.partial?"":"+"}`),h0(B),Y?EA({className:"seg",title:"Storage backend capabilities"},W(Y.storage?.presignDownload?"download":"files",{size:12}),EA(Y.storage?.presignDownload?"S3 direct":"proxied")):null,Y?.features?.semanticSearch?WQ({className:"seg",title:"Semantic search enabled"},W("star",{size:12}),EA("semantic")).on({click:()=>Q.exec("workbench.view.home")}):null)}var{div:DJ,span:GJ,button:VG}=w;function sB(A){return DJ({className:"launch-h"},DJ({className:"lh-title"},GJ(A.title),A.verbatim?GJ({className:"lh-verbatim"},A.verbatim):null),A.action||null)}function iB(A,Q,B){if(!A.menu)return null;return VG({className:"launch-more",title:`Actions for ${A.title}`,$attrs:{"aria-label":`Actions for ${A.title}`}},W("dots",{size:14})).on({click:(C)=>{C.stopPropagation(),RQ(C.currentTarget,A,Q,null,B)}})}function RQ(A,Q,B,C,E){let K=A?.getBoundingClientRect?.(),J=C?.clientX??(K?K.right-8:0),Y=C?.clientY??(K?K.bottom:0),I=Q.menu(B);E?.(),B.platform.workbench.showContextMenu(J,Y,I)}var{div:YB,span:b0}=w;function rB({groups:A,index:Q,handlers:B,ui:C}){let E=-1;return YB({className:"launch-view view-list"},...A.map((K)=>YB({className:"launch-group"},sB(K),K.items.length?YB({className:"launch-list"},...K.items.map((J)=>{let Y=++E;return PG(J,Y===Q,{hover:()=>B.hover(Y),select:()=>B.select(Y)},C)})):YB({className:"launch-empty"},K.empty||"Nothing here."))))}function PG(A,Q,{hover:B,select:C},E){return YB({className:`launch-item ${Q?"active":""}`},W(A.icon,{size:15}),b0({className:"name"},A.title),A.detail?b0({className:"launch-detail"},A.detail):null,A.badge?b0({className:"launch-kind"},A.badge):null,iB(A,E,C)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(K)=>{K.preventDefault(),RQ(K.currentTarget,A,E,K,C)}}:{}})}function vQ(A,Q,B,{op:C="media",onError:E}={}){let K=B.platform.mediaUrls,J=null,Y=!1,I=!1,D=()=>{clearTimeout(J),J=null},L=(R)=>{if(D(),!Number.isFinite(R))return;let F=Math.max(1000,(R-Date.now())*0.8);J=setTimeout(()=>G({resume:!0}),Math.min(F,2147483647))};async function G({resume:R}){if(Y)return;let F=NG(A),V=F&&R?A.currentTime:0,g=F&&R?!A.paused&&!A.ended:!1,b;try{b=await K.url(Q.id,{op:C})}catch(M){if(!Y)E?.(M.message);return}if(Y)return;if(A.src=b.url,F){if(A.load(),V>0||g){let M=()=>{if(A.removeEventListener("loadedmetadata",M),V>0&&Number.isFinite(A.duration)&&A.duration>V)A.currentTime=V;if(g)A.play().catch(()=>{})};A.addEventListener("loadedmetadata",M)}}L(b.expiresAt)}let X=()=>{I=!1};A.addEventListener("load",X),A.addEventListener("loadeddata",X);let Z=()=>{if(Y)return;if(I){E?.(null);return}I=!0,K.invalidate(Q.id,C),G({resume:!0})};return A.addEventListener("error",Z),G({resume:!1}),()=>{Y=!0,D(),A.removeEventListener("error",Z),A.removeEventListener("load",X),A.removeEventListener("loadeddata",X)}}function NG(A){return typeof A?.play==="function"&&typeof A?.load==="function"}var{div:FQ,span:qG,img:zG}=w;function XJ({groups:A,index:Q,handlers:B,ui:C}){let E=-1;return FQ({className:"launch-view view-grid"},...A.map((K)=>FQ({className:"launch-group"},sB(K),K.items.length?FQ({className:"grid-list"},...K.items.map((J)=>{let Y=++E;return jG(J,Y===Q,{hover:()=>B.hover(Y),select:()=>B.select(Y)},C)})):FQ({className:"launch-empty"},K.empty||"Nothing here."))))}function HJ({key:A,textual:Q}){if(A==="ArrowLeft")return Q?null:-1;if(A==="ArrowRight")return Q?null:1;let B=OG();if(A==="ArrowUp")return-B;if(A==="ArrowDown")return B;return null}function OG(){let A=document.querySelectorAll(".grid-list .grid-tile");if(A.length<2)return 1;let Q=A[0].offsetTop,B=0;for(let C of A){if(C.offsetTop!==Q)break;B++}return B||1}function jG(A,Q,{hover:B,select:C},E){let K=A.node,J=(K?.contentType||"").startsWith("image/");return FQ({className:`grid-tile ${Q?"active":""}`,title:A.detail?`${A.title} — ${A.detail}`:A.title},FQ({className:"gt-media"},W(K?dA(K):A.icon,{size:26}),J?zG({className:"gt-img",alt:"",loading:"lazy",decoding:"async"}).on({$attach:(Y)=>{Y._detachMedia=vQ(Y,K,E,{onError:()=>{Y.style.display="none"}})},$detach:(Y)=>{Y._detachMedia?.(),Y._detachMedia=null}}).opaque():null,A.badge?qG({className:"gt-badge"},A.badge):null,iB(A,E,C)),FQ({className:"gt-name"},A.title)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(Y)=>{Y.preventDefault(),RQ(Y.currentTarget,A,E,Y,C)}}:{}})}var{div:f0,button:SG,span:wG}=w,TG={"core.view.list":{title:"List",icon:"list",priority:50,render:rB},"core.view.grid":{title:"Grid",icon:"grid",priority:40,match:{mime:["image/*","video/*"]},render:XJ,move:HJ}};function $J(A){for(let[Q,B]of Object.entries(TG))A.contributions.register(Q,{type:"view",...B})}var ZJ="explorer.view";function UJ(A){return A.contributions.ofType("view").filter((Q)=>!Q.when||A.context.evaluate(Q.when)).sort((Q,B)=>(B.priority??0)-(Q.priority??0))}function WJ(A,Q=[],B=null){let C=UJ(A);if(!C.length)return null;let E=A.settings.get(ZJ),K=E&&C.find((I)=>I.id===E);if(K)return K;let J=B&&C.find((I)=>I.id===B);if(J)return J;let Y=Q.map((I)=>I.node).filter(Boolean);if(Y.length>=3){let I=(L)=>L.match&&Object.keys(L.match).length&&Y.filter((G)=>_G(L,G)).length/Y.length>0.6,D=C.find(I);if(D)return D}return C[0]}function _G(A,Q){let B=Q.contentType||"",C=(Q.name||"").toLowerCase(),E=C.includes(".")?C.slice(C.lastIndexOf(".")):"";if((A.match.ext||[]).includes(E))return!0;return(A.match.mime||[]).some((K)=>K.endsWith("/*")?B.startsWith(K.slice(0,-1)):B===K)}function kG(A,Q){A.settings.set(ZJ,Q||void 0)}function RJ(A,Q){let B=UJ(A);if(B.length<2)return null;return f0({className:"view-switch"},...B.map((C)=>SG({className:`vs-btn ${C.id===Q?.id?"on":""}`,title:`${C.title||C.name} view`,"aria-pressed":C.id===Q?.id?"true":"false"},W(C.icon||"list",{size:14})).on({click:()=>kG(A,C.id)})))}function FJ(A,Q,B){try{let C=A?.move?.({key:Q,...B});return Number.isFinite(C)&&C!==0?C:null}catch{return null}}function MJ(A,Q){try{if(typeof A?.render==="function")return A.render(Q)}catch(B){return console.error(`view "${A?.id}" failed`,B),f0({},f0({className:"view-error"},W("warn",{size:13}),wG(`The “${A?.title||A?.id}” view could not be drawn — showing the list instead.`)),rB(Q))}return rB(Q)}var{div:nA,span:bQ,input:xG,button:MQ}=w,gG=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]);function yG(A,{compact:Q=!1,modal:B=!1}={}){let C=A.platform.capabilities?.searchPrompt,E=(Q?C?.short||C?.placeholder:C?.placeholder)||(Q?"Search files":"Search files · # filter by tag");return Q||B?E:`${E} · ! run a command`}var eB=null;function hG(A,Q){clearTimeout(eB),eB=setTimeout(()=>A.go(new KQ(Q)),240)}function VJ(A){A.platform.workbench.setLaunchQuery(""),A.go(new KQ(""))}function vG(A,Q,B){clearTimeout(eB),eB=setTimeout(()=>A.go(new JB(Q,B)),200)}function AC(A,Q,B={}){let C=Q.platform.workbench,E=!!B.modal,K=A.wb.launch.query,J=K.startsWith("!")?"command":K.includes("#")?"filter":"search",Y=uG(A,Q,K,J,E),I=Y.flatMap((M)=>M.items),D=I.length?Math.min(A.wb.launch.index,I.length-1):0,L=(M)=>{let j=M.target.value;if(C.setLaunchQuery(j),j.startsWith("!"))return;let{text:z,filters:y}=pB(j);if(y.length)vG(Q,y,z);else hG(Q,z)},G=(M)=>C.setLaunchIndex(M),X=(M)=>{C.setLaunchIndex(M),PJ(Q,I[M])},Z=(M)=>{C.moveLaunch(M,I.length),PJ(Q,I[C.state.launch.index])},R=WJ(Q.platform,I,J==="search"?A.se.resolved?.view:null),F=(M)=>{let j=gG.has(M.key)?FJ(R,M.key,{index:D,count:I.length,textual:K.length>0}):null;if(j!==null)M.preventDefault(),Z(j);else if(M.key==="ArrowDown")M.preventDefault(),Z(1);else if(M.key==="ArrowUp")M.preventDefault(),Z(-1);else if(M.key==="Enter")M.preventDefault(),I[D]?.run();else if(M.key==="Escape"&&K)M.preventDefault(),VJ(Q);else if(M.key==="ContextMenu"||M.shiftKey&&M.key==="F10"){let z=I[D];if(z?.menu)M.preventDefault(),RQ(document.querySelector(".launch-item.active, .grid-tile.active"),z,Q)}},V=J==="search"?A.se.resolved:null,g=V&&(V.source==="llm"||V.tagFilters&&V.tagFilters.length||(V.semanticText||"").trim()!==K.trim()),b=nA({className:"launcher"},nA({className:"launch-box"},W(J==="command"?"command":J==="filter"?"tag":"search",{size:18}),xG({className:"launch-input",value:K,autofocus:!0,spellcheck:!1,placeholder:yG(Q,{compact:A.vp?.mode==="phone",modal:E})}).on({input:L,keydown:F}),K?MQ({className:"launch-clear",title:"Clear"},W("close",{size:14})).on({click:()=>VJ(Q)}):null,Q.platform.voice?.canListen()?MQ({className:`launch-mic ${A.voice?.listening?"on":""}`,title:A.voice?.listening?"Stop listening":"Search by voice","aria-pressed":A.voice?.listening?"true":"false"},W("mic",{size:15})).on({click:()=>Q.exec("search.voice")}):null,E?null:RJ(Q.platform,R)),g?bG(V):null,nA({className:"launch-body"},MJ(R,{groups:Y,index:D,handlers:{hover:G,select:X},state:A,ui:Q}),fG(A,Q,J)));return E?b:nA({className:"editor"},b)}function bG(A){return nA({className:"launch-resolved"},bQ({className:"rq-label"},A.source==="llm"?"Interpreted as":"Searching"),(A.semanticText||"").trim()?bQ({className:"rq-text"},`“${A.semanticText.trim()}”`):null,...(A.tagFilters||[]).map((Q)=>bQ({className:"rq-chip"},W("tag",{size:11}),z0(Q))))}function PJ(A,Q){let B=Q?.node;A.app.explorer.select(B?.id?[B.id]:[],{nodes:B?[B]:null})}function fG(A,Q,B){if(B==="command")return null;let C=A.se;if(!C.ran||C.loading||C.error||(C.results||[]).length)return null;let E=Q.platform.capabilities?.searchPrompt;if(!E?.hint&&!E?.examples?.length)return null;let K=Q.platform.workbench,J=(Y)=>()=>{K.setLaunchQuery(Y);let{text:I,filters:D}=pB(Y);if(D.length)Q.go(new JB(D,I));else Q.go(new KQ(I))};return nA({className:"launch-help"},E.hint?nA({className:"lh-hint"},W("info",{size:13}),bQ(E.hint)):null,E.examples?.length?nA({className:"lh-examples"},...E.examples.map((Y)=>MQ({className:"lh-example",title:Y.label||"Try this search"},bQ({className:"lh-q"},Y.query),Y.label?bQ({className:"lh-label"},Y.label):null).on({click:J(Y.query)}))):null)}function uG(A,Q,B,C,E){let K=()=>{if(E)Q.platform.workbench.closeSearchModal()};if(C==="command"){let M=B.slice(1).trim().toLowerCase();return[{title:"Commands",items:Q.platform.commands.paletteCommands().map((z)=>({hay:`${z.category||""} ${z.title}`.toLowerCase(),c:z})).map(({hay:z,c:y})=>({s:lG(z,M),c:y})).filter((z)=>M===""||z.s>0).sort((z,y)=>y.s-z.s).slice(0,40).map(({c:z})=>({icon:"command",title:z.title,detail:z.category,badge:"command",run:()=>{Q.exec(z.id),K()}})),empty:"No matching commands."}]}let{text:J,filters:Y}=pB(B),I=(A.se.results||[]).map((M)=>M.node),D=A.se.error,L=(M)=>MQ({className:"launch-up",title:"Retry"},W("refresh",{size:13}),"Retry").on({click:()=>Q.go(M)});if(Y.length){let M=Y.map(z0).join(" ")+(J.trim()?` · "${J.trim()}"`:"");return[{title:A.se.loading?"Filtering…":D?"Filter failed":"Filtered",verbatim:A.se.loading||D?null:M,action:D?L(new JB(Y,J)):null,items:I.map((j)=>tB(j,Q,E)),empty:A.se.loading?"Filtering…":D?`Couldn’t filter: ${D}`:"No files match those filters."}]}if(J.trim())return[{title:A.se.loading?"Searching…":D?"Search failed":"Results",action:D?L(new KQ(B)):null,items:I.map((M)=>tB(M,Q,E)),empty:A.se.loading?"Searching…":D?`Couldn’t search: ${D}`:"No files match."}];let G=[],X=(A.nav.recents||[]).map((M)=>tB(M,Q,E));if(X.length)G.push({title:"Recent",items:X});let Z=A.ex,R=(Z.items||[]).length,F=Z.stats?.items??null,V=F??R,g=F!=null?F.toLocaleString():`${R.toLocaleString()}+`,b=(Z.items||[]).map((M)=>tB(M,Q,E));if(Z.nextCursor)b.push({icon:"refresh",title:Z.loadingMore?"Loading…":F!=null?`Show more (${(F-R).toLocaleString()} more)`:"Show more",detail:"or search to jump straight to something",run:()=>Q.exec("explorer.loadMore")});if(Z.trash)G.push({title:Z.trash.length?`Trash · ${Z.trash.length} item${Z.trash.length===1?"":"s"}`:"Trash",action:nA({className:"lh-actions"},Z.trash.length?MQ({className:"launch-up",title:"Destroy everything in the trash"},W("trash",{size:13}),"Empty trash").on({click:()=>Q.exec("explorer.emptyTrash")}):null,MQ({className:"launch-up",title:"Hide the trash"},W("close",{size:13}),"Close").on({click:()=>Q.exec("explorer.hideTrash")})),items:Z.trash.length?Z.trash.map((M)=>({icon:"trash",title:M.name,detail:`deleted ${new Date(M.deletedAt).toLocaleString()} — restore`,run:()=>Q.exec("explorer.restore",M.id),menu:()=>pG(M,Q)})):[],empty:"The trash is empty."});return G.push({title:Z.nextCursor?`All items · showing ${R.toLocaleString()} of ${g}`:"All items",action:E?null:MQ({className:"launch-up",title:"Upload files to this collection"},W("upload",{size:13}),"Upload").on({click:()=>Q.exec("explorer.upload")}),items:b,empty:Z.loading?"Loading…":Z.error?`Couldn’t load this collection: ${Z.error}`:"Nothing here yet — upload a file to get started."}),G}function tB(A,Q,B){return{icon:cG(A),title:A.name,detail:A.contentType||"",node:A,run:()=>{if(Q.go(new SA(A,{reset:!!B})),B)Q.platform.workbench.closeSearchModal()},menu:()=>mG(A,Q)}}function mG(A,Q){let B=(Q.app.offline?.state?.pins||[]).some((E)=>E.id===A.id),C=(E)=>Q.platform.keybindings.labelFor(E)||void 0;return[{label:"Open",icon:"file-text",run:()=>Q.exec("explorer.open",A)},{label:"Download",icon:"download",run:()=>Q.exec("explorer.download",A)},{label:"Copy link",icon:"link",kbd:C("explorer.copyLink"),run:()=>Q.exec("explorer.copyLink")},{sep:!0},{label:"Rename…",run:()=>Q.exec("explorer.rename")},B?{label:"Remove from offline",icon:"close",run:()=>Q.exec("offline.unpin",A)}:{label:"Make available offline",icon:"download",run:()=>Q.exec("offline.pin",A)},{sep:!0},{label:"Move to trash",icon:"trash",danger:!0,kbd:C("explorer.delete"),run:()=>Q.exec("explorer.delete")}]}function pG(A,Q){return[{label:"Restore",icon:"refresh",run:()=>Q.exec("explorer.restore",A.id)},{sep:!0},{label:"Delete forever",icon:"trash",danger:!0,run:()=>Q.exec("explorer.purgeOne",A.id)}]}function cG(A){let Q=A.contentType||"";if(Q.startsWith("image/"))return"file-image";if(Q.startsWith("audio/"))return"file-audio";if(Q.startsWith("video/"))return"file-video";return"file-text"}function lG(A,Q){if(!Q)return 1;let B=A.indexOf(Q);if(B>=0)return 1000-B;let C=0;for(let E=0;E<A.length&&C<Q.length;E++)if(A[E]===Q[C])C++;return C===Q.length?1:0}var{div:k,h2:dG,h3:IB,p:LB,span:oA,select:nG,option:oG,input:u0,label:aG,button:QC}=w;function p0(A,Q){let B=Q.platform.settings.grouped();return k({className:"editor"},k({className:"stage"},k({className:"settings"},dG("Settings"),LB({className:"sub"},"Preferences are stored in this browser. Plugins contribute their own settings here too."),...B.map((C)=>sG(C,Q)),tG(Q),eG(Q),AX(Q))))}function sG(A,Q){return k({className:"group"},IB(A.category),...A.items.map((B)=>iG(B,Q)))}function iG(A,Q){return k({className:"setting"},k({className:"info"},k({className:"t"},A.title||A.key),A.description?k({className:"d"},A.description):null),k({className:"control"},rG(A,Q)))}function rG(A,Q){let B=(C)=>Q.platform.settings.set(A.key,C);if(A.type==="boolean")return aG({className:"switch"},u0({type:"checkbox",checked:!!A.value}).on({change:(C)=>B(C.target.checked)}),oA({className:"track"}));if(A.type==="enum")return nG({className:"input"},...A.enum.map((C,E)=>oG({value:C,selected:A.value===C},A.enumLabels&&A.enumLabels[E]||C))).on({change:(C)=>B(C.target.value)});if(A.type==="number"){let C=(E)=>{let K=Number(E.target.value);if(E.target.value===""||Number.isNaN(K)){E.target.value=A.value;return}if(A.minimum!=null)K=Math.max(A.minimum,K);if(A.maximum!=null)K=Math.min(A.maximum,K);E.target.value=K,B(K)};return u0({className:"input",type:"number",value:A.value,$attrs:{min:A.minimum??"",max:A.maximum??""}}).on({change:C})}return u0({className:"input",value:A.value??""}).on({change:(C)=>B(C.target.value)})}function tG(A){let Q=A.platform.capabilities;if(!Q)return null;let B=Q.mcp,C=Q.auth||{authorizationServers:[],source:"none"};if(!B?.enabled)return k({className:"group"},IB("AI agents (MCP)"),LB({className:"sub"},"MCP is switched off on this server. Set TROVE_MCP=on to enable it."));let E=(Y)=>()=>{navigator.clipboard?.writeText(Y).then(()=>A.platform.notifications.success("Copied")).catch(()=>A.platform.notifications.info(Y,{sticky:!0}))},K=C.authorizationServers||[],J=C.source==="jwt-issuer"?"from TROVE_JWT_ISSUER":C.source==="configured"?"from TROVE_AUTH_SERVER":null;return k({className:"group"},IB("AI agents (MCP)"),LB({className:"sub"},"Point an AI assistant at this drive. It signs in as you and sees exactly the collections you can see."),k({className:"setting"},k({className:"info"},k({className:"t"},"Server URL"),k({className:"d"},"Paste this into your assistant’s MCP settings.")),k({className:"control mcp-url"},oA({className:"mono"},B.endpoint),QC({className:"btn small",title:"Copy"},W("link",{size:13})).on({click:E(B.endpoint)}))),k({className:"setting"},k({className:"info"},k({className:"t"},"Sign-in required"),k({className:"d"},B.requiresAuth?"Agents must present a token, the same one this browser uses.":"This drive is open, so agents connect without a token — exactly like the web app does.")),k({className:"control"},oA({className:"mono"},B.requiresAuth?"Yes":"No"))),B.needsAuthorizationServer?k({className:"mcp-warn"},W("warn",{size:15}),oA("This drive requires a token but no authorization server is set, so an agent has nowhere to sign in. Set TROVE_AUTH_SERVER (or TROVE_JWT_ISSUER) to the issuer URL of your identity provider and restart.")):null,k({className:"setting"},k({className:"info"},k({className:"t"},"Authorization server"),k({className:"d"},"Where clients are sent to sign in — for the whole drive, not just for agents. "+"Set with TROVE_AUTH_SERVER; defaults to TROVE_JWT_ISSUER when that is set.")),k({className:"control"},K.length?oA({className:"mono"},K.join(", ")+(J?` (${J})`:"")):oA({className:"mono muted"},"not set"))),k({className:"setting"},k({className:"info"},k({className:"t"},"Discovery document"),k({className:"d"},"What a client reads to find out how to authenticate (RFC 9728).")),k({className:"control mcp-url"},oA({className:"mono small"},C.metadataUrl))))}function eG(A){let Q=nK(A.platform);return k({className:"group"},IB("Default Openers"),Q.length?k({},...Q.map((B)=>k({className:"setting"},k({className:"info"},k({className:"t"},B.typeKey),k({className:"d"},B.missing?`${B.openerTitle} (no longer installed)`:`Opens with ${B.openerTitle}`)),k({className:"control"},QC({className:"iconbtn",title:"Forget this default"},W("close",{size:14})).on({click:()=>dB(A.platform,B.typeKey,null)}))))):LB({className:"sub",$styling:{margin:0}},"No default openers set yet. When a file type has more than one viewer, you can pick one and check “Always use this”."))}var m0=null;function AX(A){let Q=A.platform.keybindings,B=Q.resolved(),C=A.platform.contributions,E=Q.overrides(),K=()=>{m0=null,A.rerender?.()},J=new Map;for(let Y of B)J.set(Y.key,(J.get(Y.key)||0)+1);return k({className:"group"},IB("Keyboard Shortcuts"),LB({className:"sub"},"Click a shortcut to record a new one. Esc cancels; Backspace clears it."),...B.map((Y)=>{let I=C.get(Y.command),D=m0===Y.bindingId,L=!!E[Y.bindingId],G=J.get(Y.key)>1;return k({className:"setting"},k({className:"info"},k({className:"t"},I?.title||Y.command),k({className:"d"},Y.command)),k({className:"control"},G&&!D?oA({className:"kbd-clash",title:"Another command answers to this shortcut too — the one registered last wins"},W("warn",{size:12})):null,QC({className:`kbd-edit ${D?"listening":""} ${G?"clash":""}`,title:D?"Press the new shortcut":"Click to rebind"},D?oA("Press keys…"):w.h("kbd",aQ(Y.key))).on({click:()=>{m0=D?null:Y.bindingId,A.rerender?.()},blur:()=>{if(D)K()},keydown:(X)=>{if(!D)return;if(X.preventDefault(),X.stopPropagation(),X.key==="Escape")return K();if(X.key==="Backspace")return Q.rebind(Y,null),K();if(["Control","Meta","Alt","Shift"].includes(X.key))return;Q.rebind(Y,RC(X)),K()},$attach:(X)=>{if(D)queueMicrotask(()=>X.focus())}}),L?QC({className:"c-link",title:"Back to the default"},"reset").on({click:()=>{Q.rebind(Y,null),A.rerender?.()}}):null))}))}var{div:l,span:$A,p:QX,button:DB,h2:BX,input:c0,label:CX}=w;function l0(A,Q){let B=A.plugins||[];return l({className:"editor"},l({className:"stage"},l({className:"plugins"},BX("Plugins"),QX({className:"sub",$styling:{color:"var(--text-dim)",margin:"0 0 8px"}},"Plugins are sandboxed packages you install from a file or URL. They run in an isolated iframe and reach Trove only through a message channel, using the capabilities you granted."),l({className:"plugin-install"},DB({className:"btn primary"},W("upload",{size:15}),"Install from file…").on({click:()=>Q.exec("plugins.installFromFile")}),DB({className:"btn"},W("plug",{size:15}),"Install from URL…").on({click:()=>Q.exec("plugins.installFromUrl")})),B.length?l({$styling:{display:"flex","flex-direction":"column",gap:"12px","margin-top":"14px"}},...B.map((C)=>EX(C,A,Q))):l({className:"empty",$styling:{padding:"48px"}},W("plug",{size:30}),$A("No plugins installed yet.")))))}function EX(A,Q,B){let C=!A.responsive?"not responding":A.manifest?.online===!1?"offline":"connected",E=A.features||[];return l({className:"plugin-card"},l({className:"top"},l({className:"avatar"},(A.name||"?")[0].toUpperCase()),l({$styling:{flex:"1"}},l({className:"name"},A.name,A.version?$A({$styling:{color:"var(--text-faint)","font-weight":"400","margin-left":"6px"}},"v"+A.version):null),l({$styling:{"font-size":"11px",color:"var(--text-faint)"}},A.id)),YX(A.trust),$A({className:`status ${A.status}`},A.status)),A.error?l({className:"desc",$styling:{color:"var(--danger)"}},A.error):null,l({className:"caps"},...(A.capabilities||[]).map((K)=>$A({className:"cap"},K))),(A.endpoints||[]).length?l({className:"plugin-endpoints",$styling:{"font-size":"11px",color:"var(--text-faint)","margin-top":"2px"}},W("plug",{size:11})," Network: ",(A.endpoints||[]).map((K)=>K.host).join(", ")):null,A.status==="active"?l({className:"plugin-features"},l({className:"pf-head"},$A(`Features · ${C}`),$A({className:"muted"},`${E.filter((K)=>K.available).length}/${E.length} available`)),E.length?l({className:"pf-list"},...E.map(LX)):l({className:"muted",$styling:{"font-size":"12px"}},A.responsive?"No contributions announced.":"No manifest received — the plugin may not be running.")):null,(A.settingsSchema||[]).length?KX(A,B):null,l({className:"actions"},A.hasUi?DB({className:"btn"},W("command",{size:14}),"Open panel").on({click:()=>B.platform.workbench.openPluginPanel(A.id)}):null,DB({className:"btn"},W("refresh",{size:14}),"Refresh").on({click:()=>B.platform.plugins.refresh(A.id)}),DB({className:"btn danger"},"Uninstall").on({click:()=>B.platform.workbench.showDialog({kind:"confirm",title:`Uninstall ${A.name}?`,danger:!0,confirmLabel:"Uninstall",body:"The plugin and all data it stored will be removed.",onConfirm:()=>{B.platform.workbench.closeDialog(),B.uninstallPlugin(A.id)}})})))}function KX(A,Q){return l({className:"plugin-features"},l({className:"pf-head"},$A("Settings")),l({$styling:{display:"flex","flex-direction":"column",gap:"8px"}},...A.settingsSchema.map((B)=>JX(A,B,Q))))}function JX(A,Q,B){let C=`${A.id}.${Q.key}`,E=Q.secret?"":B.platform.settings.get(C)??Q.default??"";return l({className:"setting",$styling:{padding:"6px 0"}},l({className:"info"},l({className:"t"},Q.title||Q.key),Q.description?l({className:"d"},Q.description):null),l({className:"control"},Q.secret?c0({className:"input",type:"password",placeholder:"Set secret…"}).on({change:(K)=>{if(K.target.value)B.platform.plugins.setSecret(A.id,Q.key,K.target.value),K.target.value="",K.target.placeholder="Saved ✓"}}):Q.type==="boolean"?CX({className:"switch"},c0({type:"checkbox",checked:!!E}).on({change:(K)=>B.platform.settings.set(C,K.target.checked)}),$A({className:"track"})):c0({className:"input",value:E}).on({change:(K)=>B.platform.settings.set(C,K.target.value)})))}function YX(A){if(!A)return null;if(A.status==="verified")return $A({className:"trust verified",title:"Signed by "+A.domain},W("check",{size:12}),A.domain);if(A.status==="signed")return $A({className:"trust signed"},W("info",{size:12}),"signed");if(A.status==="invalid")return $A({className:"trust invalid",title:A.reason||"The signature did not verify — this package may have been altered"},W("warn",{size:12}),"invalid signature");return $A({className:"trust unverified"},W("warn",{size:12}),"unverified")}var IX={command:"command",opener:"file",indexer:"search",statusItem:"info"};function LX(A){return l({className:`pf-row ${A.available?"":"off"}`},W(IX[A.kind]||"command",{size:13}),$A({className:"pf-title"},A.title),$A({className:"pf-kind"},A.kind),A.offline?$A({className:"pf-badge offline-ok",title:"Works offline"},"offline ✓"):null,$A({className:`pf-dot ${A.available?"on":"no"}`,title:A.available?"Available now":"Unavailable now"}))}async function NJ(A,Q,{from:B}={}){let C=uB(Q),E=A.platform.notifications;if(!C)return E.warn(`"${Q}" isn’t a valid Trove link.`),null;try{let K=await A.platform.api.stat(Q);if(!K?.node)throw Error("not found");return A.go(new SA(K.node)),K.node}catch(K){return E.warn(DX(C,K,B)),null}}function DX(A,Q,B){let C=B?.name?` (linked from "${B.name}")`:"";if(Q?.status===403||Q?.code==="forbidden")return`You don’t have access to that item in "${A.collection}"${C}.`;if(A.by==="name")return`Nothing named "${A.value}" in "${A.collection}"${C} — it may have been renamed or deleted.`;return`That item no longer exists in "${A.collection}"${C}.`}var{div:VQ,span:n0,h1:GX,h2:XX,h3:HX,p:wJ,ul:$X,ol:ZX,li:UX,pre:WX,code:TJ,a:qJ,em:RX,strong:FX,blockquote:MX,hr:VX,br:PX}=w;function _J(A,Q){let B=nQ(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:d0,size:A.size}).then((C)=>C.text));return w.alias(()=>Q.platform.reactive.watch(B,(C)=>{try{return VQ({className:"viewer markdown"},VQ({className:"md"},...kJ(C,A,Q)))}catch(E){return console.error("markdown render failed",E),zJ(`This document couldn’t be displayed: ${E.message}`)}},{placeholder:()=>VQ({className:"viewer"},VQ({className:"loading"},VQ({className:"spinner"}),n0("Loading…"))),error:(C)=>zJ(C.message)}))()}function zJ(A){return VQ({className:"viewer"},VQ({className:"fallback"},W("warn",{size:40}),n0(A)))}var d0=524288,NX=5000,qX=2000;function kJ(A,Q,B){let C=String(A??""),E=C.length>d0,K=(E?C.slice(0,d0):C).split(/\r?\n/),J=[],Y=0;while(Y<K.length){if(J.length>=NX)return[...J,OJ()];let I=K[Y],D=/^\s*(```+|~~~+)(.*)$/.exec(I);if(D){let F=D[1][0].repeat(3),V=[];Y++;while(Y<K.length&&!K[Y].trimStart().startsWith(F))V.push(K[Y++]);Y++,J.push(WX({className:"md-code"},TJ(V.join(`
|
|
350
|
+
`))));continue}if(!I.trim()){Y++;continue}let L=/^(#{1,6})\s+(.*)$/.exec(I);if(L){let F=L[1].length,V=F===1?GX:F===2?XX:HX;J.push(V({className:`md-h md-h${F}`},...GB(L[2],Q,B))),Y++;continue}if(/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(I)){J.push(VX({className:"md-hr"})),Y++;continue}if(/^\s*>/.test(I)){let F=[];while(Y<K.length&&/^\s*>/.test(K[Y]))F.push(K[Y++].replace(/^\s*>\s?/,""));J.push(MX({className:"md-quote"},...kJ(F.join(`
|
|
351
|
+
`),Q,B)));continue}let G=/^\s*([-*+]|\d+[.)])\s+/.exec(I);if(G){let F=/\d/.test(G[1]),V=[];while(Y<K.length){let g=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(K[Y]);if(!g||/\d/.test(g[1])!==F)break;V.push(UX({className:"md-li"},...GB(g[2],Q,B))),Y++}J.push((F?ZX:$X)({className:"md-list"},...V));continue}let X=[];while(Y<K.length&&K[Y].trim()&&!zX(K[Y]))X.push(K[Y++]);let Z=X.join(`
|
|
352
|
+
`),R=[];Z.split(`
|
|
353
|
+
`).forEach((F,V)=>{if(V)R.push(PX());R.push(...GB(F,Q,B))}),J.push(wJ({className:"md-p"},...R))}return E?[...J,OJ()]:J}function OJ(){return wJ({className:"md-truncated"},"This document is too large to display in full. Download it to read the rest.")}function zX(A){return/^(#{1,6}\s|\s*>|\s*([-*+]|\d+[.)])\s|\s*(```|~~~))/.test(A)||/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(A)}var OX=[{re:/`([^`]+)`/,node:(A)=>TJ({className:"md-inline-code"},A[1])},{re:/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/,node:(A,Q,B)=>SJ(A[2],A[1]||A[2],Q,B)},{re:/(\*\*|__)(.+?)\1/,node:(A,Q,B,C)=>FX(...GB(A[2],Q,B,C+1))},{re:/(\*|_)(.+?)\1/,node:(A,Q,B,C)=>RX(...GB(A[2],Q,B,C+1))},{re:/(trove:[^\s<>"'`)\]}]+|https?:\/\/[^\s<>"'`)\]}]+)/,node:(A,Q,B)=>SJ(jJ(A[1]),jJ(A[1]),Q,B)}];function GB(A,Q,B,C=0){if(!A)return[];if(C>12)return[A];let E=[],K=A;while(K){if(E.length>=qX){E.push(K);break}let J=null;for(let D of OX){let L=D.re.exec(K);if(L&&(J===null||L.index<J.m.index))J={m:L,rule:D}}if(!J){E.push(K);break}let{m:Y,rule:I}=J;if(Y.index)E.push(K.slice(0,Y.index));E.push(I.node(Y,Q,B,C)),K=K.slice(Y.index+Y[0].length)}return E}function jJ(A){return A.replace(/[.,;:!?]+$/,"")}function SJ(A,Q,B,C){if(uB(A))return qJ({className:"md-link md-trove",href:"#",title:A},Q).on({click:(K)=>{K.preventDefault(),NJ(C,A,{from:B})}});if(/^https?:\/\//i.test(A))return qJ({className:"md-link",href:A,target:"_blank",rel:"noopener noreferrer",title:A},Q);return n0({className:"md-deadlink",title:`Unsupported link: ${A}`},Q)}var{div:RA,pre:jX,img:SX,span:PQ,button:wX,video:TX,audio:_X}=w,kX={"core.audio":{title:"Audio Player",priority:20,match:{mime:["audio/*"],ext:[".mp3",".flac",".wav",".opus",".ogg",".m4a",".m4b"]},component:vX},"core.video":{title:"Video Player",priority:20,match:{mime:["video/*"],ext:[".mp4",".webm",".mkv",".mov"]},component:bX},"core.image":{title:"Image Viewer",priority:20,match:{mime:["image/*"],ext:[".png",".jpg",".jpeg",".gif",".webp",".svg",".avif"]},component:hX},"core.markdown":{title:"Markdown",priority:30,match:{ext:[".md",".markdown"],mime:["text/markdown"]},component:_J},"core.text":{title:"Text Viewer",priority:10,match:{mime:["text/*","application/json"],ext:[".txt",".md",".json",".js",".mjs",".ts",".jsx",".tsx",".css",".html",".xml",".yaml",".yml",".toml",".ini",".log",".csv",".py",".rb",".go",".rs",".sh",".c",".h",".cpp",".java"]},component:gX}};function xJ(A){for(let[Q,B]of Object.entries(kX))A.contributions.register(Q,{type:"opener",...B})}function gJ(A,Q,B){let C=B.platform.contributions.get(Q);if(C?.component)try{return C.component(A,B)}catch(E){return hJ(E.message)}if(C?.pluginId)return fX(C,A,B);return yJ(A,B)}var xX=524288;function gX(A,Q){let B=nQ(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:xX,size:A.size}));return w.alias(()=>Q.platform.reactive.watch(B,({text:C,truncated:E,total:K})=>RA({className:"viewer text"},jX(C),E?RA({className:"md-truncated"},`Showing the first ${Math.round(C.length/1024)} KB${K?` of ${(K/1048576).toFixed(1)} MB`:""}. `,PQ("Download the file to read all of it.")):null),{placeholder:()=>RA({className:"viewer"},RA({className:"loading"},RA({className:"spinner"}),PQ("Loading…"))),error:(C)=>hJ(C.message)}))()}var yX="This file couldn't be loaded — it may be missing or in an unsupported format.";function o0(A,Q,B){let C=f({error:null}),K=B((J)=>C.setValue({error:J||yX}));return w.alias(()=>MB(C,(J)=>J.error?yJ(A,Q,J.error):K))()}var a0=(A,Q,B,C)=>A.on({$attach:(E)=>{E._detachMedia=vQ(E,Q,B,{onError:C})},$detach:(E)=>{E._detachMedia?.(),E._detachMedia=null}}).opaque();function hX(A,Q){return o0(A,Q,(B)=>RA({className:"viewer image"},a0(SX({alt:A.name}),A,Q,B)))}function vX(A,Q){return o0(A,Q,(B)=>RA({className:"viewer",$styling:{display:"grid","place-items":"center",gap:"16px",padding:"40px"}},W("file-audio",{size:48}),PQ({$styling:{color:"var(--text-dim)"}},A.name),a0(_X({controls:!0,$styling:{width:"min(520px, 90%)"}}),A,Q,B)))}function bX(A,Q){return o0(A,Q,(B)=>RA({className:"viewer",$styling:{display:"grid","place-items":"center",background:"#000"}},a0(TX({controls:!0,$styling:{"max-width":"100%","max-height":"100%"}}),A,Q,B)))}function yJ(A,Q,B){return RA({className:"viewer"},RA({className:"fallback"},W(B?"warn":"file",{size:44}),PQ({$styling:{"font-weight":600}},A.name),PQ(`${A.contentType||"Unknown type"} · ${QA(A.size)}`),PQ({$styling:{color:"var(--text-faint)","max-width":"340px"}},B||"No preview available for this file type. Install a plugin that handles it, or download the file."),wX({className:"btn primary"},W("download",{size:15}),"Download").on({click:()=>Q.exec("explorer.download",A)})))}function fX(A,Q,B){return RA({className:"viewer plugin-viewer"},RA({className:"pv-status"}).on({$attach:(C)=>{C.innerHTML='<div class="loading"><div class="spinner"></div><span>Opening…</span></div>',C._ready=()=>{C.style.display="none"},C._error=(E)=>{C.style.display="grid",C.innerHTML="",C.appendChild(uX(E))}}}).opaque(),RA({className:"pv-host"}).on({$attach:(C)=>{let E=C.parentElement?.querySelector(".pv-status");C._detach=B.platform.plugins.mountViewer(A.pluginId,C,Q,A.id,{onReady:()=>E?._ready?.(),onError:(K)=>E?._error?.(K||"This viewer failed to load")})},$detach:(C)=>{C._detach?.(),C._detach=null}}).opaque())}function uX(A){let Q=document.createElement("div");Q.className="fallback";let B=document.createElement("span");return B.textContent=A||"Failed to open",Q.appendChild(B),Q}function hJ(A){return RA({className:"viewer"},RA({className:"fallback"},W("warn",{size:40}),PQ(A||"Failed to open")))}var{div:uQ,span:vJ,button:fQ}=w,BC=new Map;function CC(A,Q){let B=A.wb,C=A.nav.stack.filter((K)=>K.kind==="file");lX(C);let E=C[C.length-1];if(!E)return uQ({className:"editor"});return uQ({className:"editor"},mX(C,E,Q),uQ({className:"stage"},cX(E,Q)))}function mX(A,Q,B){let C=B.platform.workbench;return uQ({className:"viewer-nav"},fQ({className:"vn-back",title:"Back (Esc)"},W("chevron-left",{size:16})).on({click:()=>C.back()}),uQ({className:"vn-trail"},fQ({className:"vn-crumb"},W("search",{size:13}),vJ("Search")).on({click:()=>C.showHome()}),...A.map((E)=>fQ({className:`vn-crumb ${E.id===Q.id?"active":""}`,title:E.node.name},W(dA(E.node),{size:13}),vJ({className:"label"},E.node.name)).on({click:()=>C.openFile(E.node,E.openerId)}))),uQ({className:"vn-actions"},pX(Q,B),fQ({className:"iconbtn",title:"Details & comments"},W("info",{size:15})).on({click:()=>C.toggleInfoPanel()}),fQ({className:"iconbtn",title:"Close (Esc)"},W("close",{size:15})).on({click:()=>C.showHome()})))}function pX(A,Q){let B=lB(Q.platform,A.node);if(B.length<=1)return null;return fQ({className:"iconbtn",title:"Open with…"},W("dots",{size:15})).on({click:()=>Q.platform.workbench.showDialog({kind:"opener-chooser",node:A.node,openers:B,current:A.openerId})})}function cX(A,Q){let B=`${A.id}:${A.openerId}`,C=BC.get(B);if(!C)C=()=>gJ(A.node,A.openerId,Q),BC.set(B,C);return w.alias(C)().key(A.id)}function lX(A){let Q=new Set(A.map((B)=>`${B.id}:${B.openerId}`));for(let B of BC.keys())if(!Q.has(B))BC.delete(B)}var{div:wA,input:dX,span:JQ}=w;function s0(A,Q){let B=A.overlay.palette;if(!B)return null;let C=Q.platform.workbench,E=B.mode==="files"?B.query.trim()?A.se.paletteFiles||[]:[]:iX(A,Q,B.query),K=Math.min(B.index,Math.max(0,E.length-1)),J=(Y)=>{if(!Y)return;if(C.closePalette(),B.mode==="files")Q.go(new SA(Y.node));else Q.exec(Y.id)};return wA({},wA({className:"scrim"}).on({click:()=>C.closePalette()}),wA({className:"palette"},wA({className:"search"},W(B.mode==="files"?"search":"command",{size:18}),dX({type:"text",value:B.query,autofocus:!0,placeholder:B.mode==="files"?"Search files by name…":"Type a command…"}).on({input:(Y)=>eX(Q,Y.target.value),keydown:(Y)=>tX(Y,Q,E,K,J),$attach:(Y)=>{if(queueMicrotask(()=>Y.focus()),Y.value!==B.query)Y.value=B.query}})),wA({className:"results"},E.length?E.map((Y,I)=>{let D=()=>C.setPaletteIndex(I);return B.mode==="files"?sX(Y,I===K,J,D):oX(Y,I===K,Q,J,D)}):nX(B,A))))}function nX(A,Q){if(A.mode!=="files")return wA({className:"none"},"No matching commands");if(Q.se.paletteError)return wA({className:"none error"},W("warn",{size:14}),` ${Q.se.paletteError}`);if(Q.se.paletteLoading)return wA({className:"none"},wA({className:"spinner"})," Searching…");return wA({className:"none"},A.query.trim()?"No files found":"Type to search files by name")}function oX(A,Q,B,C,E){let K=B.platform.keybindings.labelFor(A.id),J=B.platform.commands.isAvailable(A);return wA({className:`opt ${Q?"active":""} ${J?"":"unavailable"}`},JQ({className:"ico"},W(A.icon||"command",{size:16})),A.category?JQ({className:"cat"},A.category+" ›"):null,JQ({className:"title"},A.title),!J?JQ({className:"offline-tag"},"offline"):null,K?JQ({className:"kbd"},w.h("kbd",aQ(aX(B,A.id)))):null).on({click:()=>C(A),mouseenter:E})}function aX(A,Q){let B=A.platform.keybindings.resolved().find((C)=>C.command===Q);return B?B.key:""}function sX(A,Q,B,C){return wA({className:`opt ${Q?"active":""}`},JQ({className:"ico"},W(dA(A.node),{size:16})),JQ({className:"title"},A.node.name),JQ({className:"sub"},A.node.contentType||"")).on({click:()=>B(A),mouseenter:C})}function iX(A,Q,B){let C=Q.platform.commands.paletteCommands(),E=B.trim().toLowerCase();if(!E)return C.slice(0,60);let K=[];for(let J of C){let Y=`${J.category||""} ${J.title}`.toLowerCase(),I=rX(Y,E);if(I>0)K.push([I,J])}return K.sort((J,Y)=>Y[0]-J[0]).slice(0,60).map((J)=>J[1])}function rX(A,Q){let B=0,C=0;for(let E of Q){let K=A.indexOf(E,C);if(K<0)return 0;B+=K===C?3:1,C=K+1}if(A.includes(Q))B+=10;return B}function tX(A,Q,B,C,E){let K=Q.platform.workbench;if(A.key==="ArrowDown")A.preventDefault(),K.movePalette(1,B.length);else if(A.key==="ArrowUp")A.preventDefault(),K.movePalette(-1,B.length);else if(A.key==="Enter")A.preventDefault(),E(B[C]);else if(A.key==="Escape")A.preventDefault(),K.closePalette()}var bJ=null;function eX(A,Q){let B=A.platform.workbench;if(B.setPaletteQuery(Q),clearTimeout(bJ),B.overlay.state.palette?.mode!=="files")return;bJ=setTimeout(()=>A.go(new T0(Q)),200)}var{div:d,span:i,button:fJ,h3:f4,p:AH,label:QH,input:BH}=w,NQ={ref:null,grants:null};function mJ(A,Q){let B=Q.platform.workbench,C=A.summary;if(NQ.ref!==A)NQ={ref:A,grants:new Set(C.capabilities.filter((K)=>!K.adminOnly||A.isAdmin).map((K)=>K.id))};let E=(K)=>{NQ.grants.has(K)?NQ.grants.delete(K):NQ.grants.add(K),Q.rerender?.()};return d({},d({className:"scrim"}).on({click:()=>B.closeDialog()}),d({className:"dialog review",$styling:{width:"min(560px, 96vw)"}},CH(C),d({className:"review-body"},C.description?AH({className:"review-desc"},C.description):null,mQ("Capabilities it requests",C.capabilities.length?d({className:"cap-list"},...C.capabilities.map((K)=>KH(K,A.isAdmin,NQ.grants.has(K.id),()=>E(K.id)))):GH("None — this plugin only runs in its sandbox.")),(C.network||[]).length?mQ("Network access",d({className:"contrib-list"},...C.network.map(IH))):null,(C.commands||[]).length?mQ("Commands it can run",d({className:"contrib-list"},...C.commands.map((K)=>YH(K,Q)))):null,C.storage?mQ("Storage",LH(C.storage)):null,C.contributions.length?mQ("What it adds",d({className:"contrib-list"},...C.contributions.map(JH))):null,C.settings.length?mQ("Settings",d({className:"contrib-list"},...C.settings.map(DH))):null,d({className:"review-meta"},`${C.fileCount} files · ${QA(C.sizeBytes)} · id ${C.id}`)),d({className:"row-actions"},fJ({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),fJ({className:"btn primary"},W("plug",{size:15}),"Install").on({click:()=>A.onInstall([...NQ.grants])}))))}function CH(A){let Q=A.trust||{status:"unverified"};return d({className:"review-head"},d({className:"avatar"},(A.name||"?")[0].toUpperCase()),d({className:"rh-main"},d({className:"rh-name"},A.name,i({className:"rh-ver"},"v"+A.version)),d({className:"rh-author"},"by "+A.author)),EH(Q))}function EH(A){if(A.status==="verified")return i({className:"trust verified",title:`Signed by a key published at ${A.domain}`},W("check",{size:13}),"Verified · "+A.domain);if(A.status==="signed")return i({className:"trust signed",title:A.reason||"Signed, but the domain does not vouch for the key"},W("info",{size:13}),"Signed");if(A.status==="invalid")return i({className:"trust invalid",title:A.reason||"Invalid signature — the package may have been tampered with"},W("warn",{size:13}),"Invalid signature");return i({className:"trust unverified",title:A.reason||"This plugin is not signed"},W("warn",{size:13}),"Unverified")}function KH(A,Q,B,C){let E=A.adminOnly&&!Q;return QH({className:`cap-row ${E?"blocked":""}`},BH({type:"checkbox",checked:B&&!E,disabled:E}).on({change:()=>!E&&C()}),d({className:"cap-info"},d({className:"cap-name"},A.id,A.adminOnly?i({className:"pf-badge",$styling:{color:"var(--warn)","margin-left":"6px"}},"admin only"):null),d({className:"cap-desc"},A.description+(E?" — requires an administrator":""))))}function JH(A){let Q={command:"command",opener:"file",indexer:"search",statusItem:"info",register:"info",keymap:"command"}[A.kind]||"command";return d({className:"contrib-row"},W(Q,{size:13}),i({className:"cr-title"},A.title),A.detail?i({className:"cr-detail"},A.detail):null,A.offline?i({className:"pf-badge offline-ok"},"offline"):null,i({className:"pf-kind"},A.kind))}function YH(A,Q){let B=Q?.platform?.contributions?.get?.(A),C=B?.pluginId?"plugin":B?"built-in":"not installed";return d({className:`contrib-row ${B?"":"blocked"}`},W("command",{size:13}),i({className:"cr-title"},B?.title||A),i({className:"cr-detail"},A),i({className:"pf-kind"},C))}function IH(A){return d({className:"contrib-row"},W("plug",{size:13}),i({className:"cr-title"},A.host),A.path?i({className:"cr-detail"},A.path):null,i({className:"pf-kind"},A.scheme))}function LH(A){let Q=[];if(A.plugin)Q.push(uJ("Private database","A SQLite store just for this plugin (server + this device).",!1));if(A.domain)Q.push(uJ("Shared database","Shared with other plugins from its domain (SQLite).",A.domainBlocked));return d({className:"contrib-list"},...Q)}function uJ(A,Q,B){return d({className:`contrib-row ${B?"blocked":""}`},W("plug",{size:13}),i({className:"cr-title"},A),i({className:"cr-detail"},B?Q+" — needs a verified domain":Q),B?i({className:"pf-badge",$styling:{color:"var(--warn)"}},"unavailable"):null)}function DH(A){return d({className:"contrib-row"},W("gear",{size:13}),i({className:"cr-title"},A.title),A.secret?i({className:"pf-badge",$styling:{color:"var(--warn)"}},"secret"):i({className:"pf-kind"},A.type))}function mQ(A,Q){return d({className:"review-section"},d({className:"rs-title"},A),Q)}function GH(A){return d({className:"muted",$styling:{"font-size":"12.5px"}},A)}var{div:x,span:fA,button:xA,input:XB,h3:t0,p:n4,select:XH,option:i0,label:HB,textarea:o4}=w;function pJ(A,Q){let B=A.overlay.dialog;if(!B)return null;if(B.kind==="collection")return $H(B,Q);if(B.kind==="plugin-review")return mJ(B,Q);if(B.kind==="opener-chooser")return HH(B,Q);let C=Q.platform.workbench,E=B.value??"",K=()=>B.kind==="confirm"?B.onConfirm?.():B.onSubmit?.(E);return x({},x({className:"scrim"}).on({click:()=>C.closeDialog()}),x({className:"dialog"},t0(B.title),B.body?x({className:"body"},B.body):null,B.kind==="prompt"?x({className:"field"},B.label?fA({$styling:{"font-size":"12px",color:"var(--text-dim)"}},B.label):null,XB({className:"input",value:B.value??"",placeholder:B.placeholder||"",autofocus:!0}).on({input:(J)=>{E=J.target.value},keydown:(J)=>{if(J.key==="Enter")K();if(J.key==="Escape")C.closeDialog()},$attach:(J)=>queueMicrotask(()=>{J.focus(),J.select()})})):null,x({className:"row-actions"},xA({className:"btn"},"Cancel").on({click:()=>C.closeDialog()}),xA({className:`btn ${B.danger?"danger":"primary"}`},B.confirmLabel||"OK").on({click:K}))))}function HH(A,Q){let B=Q.platform.workbench,C=Q.platform,E=A.openerId||A.current||A.openers[0]?.id,K=!!A.remember,J=()=>{if(K&&E)dB(C,cK(A.node),E);B.closeDialog(),B.openFile(A.node,E,{reset:!!A.reset})};return x({},x({className:"scrim"}).on({click:()=>B.closeDialog()}),x({className:"dialog opener-chooser"},t0(`Open “${A.node.name}” with…`),x({className:"opener-list"},...A.openers.map((Y)=>HB({className:`opener-opt ${Y.id===E?"sel":""}`},XB({type:"radio",name:"opener-choice",checked:Y.id===E}).on({change:()=>B.updateDialog({openerId:Y.id})}),W(Y.icon||dA(A.node),{size:18}),x({className:"oo-main"},fA({className:"oo-title"},Y.title||Y.id),fA({className:"oo-src"},oK(C,Y)))).on({click:()=>B.updateDialog({openerId:Y.id})}))),HB({className:"opener-remember"},XB({type:"checkbox",checked:K}).on({change:(Y)=>B.updateDialog({remember:Y.target.checked})}),fA(`Always use this for ${lK(A.node)}`)),x({className:"row-actions"},xA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),xA({className:"btn primary"},"Open").on({click:J}))))}var r0={ref:null,form:null};function $H(A,Q){let B=Q.platform.workbench;if(r0.ref!==A)r0={ref:A,form:{name:"",description:"",driver:"filesystem",root:"",bucket:"",prefix:"",region:"auto",endpoint:"",accessKeyId:"",secretAccessKey:""}};let C=r0.form,E=(Y)=>(I)=>{if(C[Y]=I.target.value,Y==="driver")Q.rerender?.()},K=()=>{let Y={driver:C.driver};if(C.driver==="filesystem")Y.root=C.root;if(C.driver==="s3"){if(Y.s3={bucket:C.bucket,region:C.region,endpoint:C.endpoint||void 0,accessKeyId:C.accessKeyId,secretAccessKey:C.secretAccessKey,forcePathStyle:!!C.endpoint},C.prefix)Y.prefix=C.prefix}if(C.driver==="filesystem"&&C.prefix)Y.prefix=C.prefix;A.onSubmit?.({name:C.name,description:C.description,store:Y})},J=(Y,I,D="")=>x({className:"field",$styling:{"margin-bottom":"10px"}},HB(Y),XB({className:"input",placeholder:D}).on({input:E(I)}));return x({},x({className:"scrim"}).on({click:()=>B.closeDialog()}),x({className:"dialog",$styling:{width:"min(480px, 94vw)"}},t0("New collection"),x({className:"body"},"A collection is a backing store you own. Configure where its files live."),J("Name","name","Team Vault"),x({className:"field",$styling:{"margin-bottom":"10px"}},HB("Backing store"),XH({className:"input"},i0({value:"filesystem",selected:C.driver==="filesystem"},"Filesystem / NAS"),i0({value:"s3",selected:C.driver==="s3"},"S3-compatible (S3 · R2 · MinIO)"),i0({value:"memory",selected:C.driver==="memory"},"Memory (ephemeral)")).on({change:E("driver")})),ZH(C,E),x({className:"row-actions"},xA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),xA({className:"btn primary"},"Create collection").on({click:K}))))}function ZH(A,Q){let B=(C,E,K="",J="text")=>x({className:"field",$styling:{"margin-bottom":"10px"}},HB(C),XB({className:"input",placeholder:K,type:J,autocomplete:"off"}).on({input:Q(E)}));if(A.driver==="filesystem")return x({},B("Root directory","root","./data/team"),B("Prefix (optional)","prefix"));if(A.driver==="s3")return x({},B("Bucket","bucket","my-bucket"),B("Prefix (optional)","prefix","team-a/"),B("Region","region","auto"),B("Endpoint (R2/MinIO; blank for AWS)","endpoint","https://<acct>.r2.cloudflarestorage.com"),B("Access key id","accessKeyId"),B("Secret access key","secretAccessKey","","password"));return x({className:"body",$styling:{"font-size":"12px"}},"Ephemeral — data is lost on restart. Good for testing.")}function cJ(A,Q){let B=A.overlay.contextMenu;if(!B||!B.items?.length)return null;let C=Q.platform.workbench,E=Math.min(B.items.length*34+20,window.innerHeight-24),K=Math.max(8,Math.min(B.x,window.innerWidth-220)),J=Math.max(8,Math.min(B.y,window.innerHeight-E));return x({},x({className:"scrim",$styling:{background:"transparent"}}).on({click:()=>C.closeContextMenu(),contextmenu:(Y)=>{Y.preventDefault(),C.closeContextMenu()}}),x({className:"menu",$styling:{left:K+"px",top:J+"px"}},...B.items.map((Y,I)=>Y.sep?x({className:"sep"}):xA({className:`mi ${Y.danger?"danger":""}`,autofocus:I===0},Y.icon?W(Y.icon,{size:15}):null,fA(Y.label),Y.kbd?fA({className:"kbd"},Y.kbd):null).on({click:()=>{C.closeContextMenu(),Y.run?.()},keydown:(D)=>{if(D.key==="Escape")D.preventDefault(),C.closeContextMenu()},$attach:(D)=>{if(I===0)queueMicrotask(()=>D.focus())}}))))}function lJ(A,Q){let B=A.notif||[];if(!B.length)return null;return x({className:"toasts"},...B.slice(-5).map((C)=>x({className:`toast ${C.level}`},x({className:"bar"}),x({className:"msg"},C.message),xA({className:"x"},W("close",{size:14})).on({click:()=>Q.platform.notifications.dismiss(C.id)})).key(C.id)))}function dJ(A,Q){let B=A.tr.items;if(!B.length)return null;return x({className:"tray"},x({className:"head"},W("upload",{size:14}),fA({$styling:{"margin-left":"6px"}},"Transfers"),x({className:"actions"},xA({className:"iconbtn",title:"Clear finished"},W("check",{size:14})).on({click:()=>Q.app.transfers.clearDone()}))),x({className:"items"},...B.map((C)=>x({className:`xfer ${C.status}`},x({className:"top"},W(C.status==="error"?"warn":C.status==="done"?"check":"upload",{size:14}),fA({className:"name"},C.name),C.status==="active"?xA({className:"iconbtn",title:"Cancel"},W("close",{size:13})).on({click:()=>Q.app.transfers.cancel(C.id)}):fA({className:"pct"},C.status==="done"?QA(C.total):C.status)),C.status==="active"?x({className:"progress"},x({$styling:{width:`${Math.round(C.ratio*100)}%`}})):C.error?x({$styling:{"font-size":"11px",color:"var(--danger)","margin-top":"4px"}},C.error):null,C.status==="active"?x({className:"pct",$styling:{"margin-top":"4px"}},`${QA(C.loaded)} / ${QA(C.total)}`):null).key(C.id))))}function nJ(A,Q){let B=A.overlay.pluginPanel;if(!B)return null;let C=(A.plugins||[]).find((E)=>E.id===B);return x({className:"plugin-panel",$styling:{width:"380px"}},x({className:"head"},W("plug",{size:14}),fA(C?.name||B),xA({className:"iconbtn x"},W("close",{size:14})).on({click:()=>Q.platform.workbench.closePluginPanel()})),x({className:"host"}).on({$attach:(E)=>{E._detach=Q.platform.plugins.mountPanel(B,E,{width:380,height:460})},$detach:(E)=>E._detach?.()}))}var{div:u,button:qQ,span:EC,h3:UH,p:oJ}=w,WH={running:"refresh",done:"check",failed:"close",cancelled:"close"};function aJ(A){if(A.total==null)return null;return A.unit==="bytes"?`${QA(A.done||0)} of ${QA(A.total)}`:`${A.done||0} of ${A.total}${A.unit?` ${A.unit}`:""}`}function sJ(A,Q){let B=A.status==="running",C=B&&A.total!=null&&A.total>0,E=C?Math.min(100,Math.round((A.done||0)/A.total*100)):0;return u({className:`act-task act-${A.status}`,"data-task-id":A.id},u({className:"act-row"},B?u({className:"spinner",$styling:{width:"12px",height:"12px"}}):W(WH[A.status]||"info",{size:13}),u({className:"act-body"},u({className:"act-title"},A.title),A.detail?u({className:"act-detail"},A.detail):null,A.error?u({className:"act-error"},A.error):null),B&&A.cancellable?qQ({className:"act-action",title:"Cancel"},W("close",{size:12})).on({click:()=>Q.app.activity.cancel(A.id)}):!B?qQ({className:"act-action",title:"Dismiss"},W("close",{size:12})).on({click:()=>Q.app.activity.dismiss(A.id)}):null),B?u({className:`act-bar ${C?"":"indeterminate"}`},u({className:"act-fill",$styling:C?{width:`${E}%`}:{}})):null,B&&aJ(A)?u({className:"act-amount"},aJ(A)):null)}function RH(A,Q){let B=new Date(A.firstAt||A.lastAt).toLocaleString();return u({className:`act-issue act-sev-${A.severity||"error"}`,"data-issue-id":A.id},u({className:"act-row"},W(A.severity==="warning"?"info":"close",{size:13}),u({className:"act-body"},u({className:"act-title"},A.title),A.detail?u({className:"act-detail"},A.detail):null,u({className:"act-meta"},A.count>1?`${A.count} times, since ${B}`:`since ${B}`))),u({className:"act-actions"},A.retryable?qQ({className:"btn small act-retry"},W("refresh",{size:12}),EC("Retry")).on({click:()=>Q.app.activity.retryIssue(A.id)}):null,qQ({className:"btn small ghost act-dismiss"},"Dismiss").on({click:()=>Q.app.activity.dismissIssue(A.id)})))}function e0(A,Q){let B=A.act||{tasks:[],issues:[]};if(!B.open)return null;let C=B.tasks.filter((K)=>K.status==="running"),E=B.tasks.filter((K)=>K.status!=="running");return u({className:"activity-panel"},u({className:"act-head"},UH("Activity"),qQ({className:"act-action",title:"Close"},W("close",{size:13})).on({click:()=>Q.app.activity.togglePanel(!1)})),B.tasksError||B.issuesError?u({className:"act-offline"},W("info",{size:12}),EC(`Couldn't reach the server — this list may be out of date (${B.issuesError||B.tasksError})`)):null,u({className:"act-section"},u({className:"act-section-title"},"Running"),C.length?u(...C.map((K)=>sJ(K,Q))):oJ({className:"act-empty"},"Nothing running.")),B.issues.length?u({className:"act-section"},u({className:"act-section-title"},`Needs attention (${B.issues.length})`),u(...B.issues.map((K)=>RH(K,Q)))):u({className:"act-section"},u({className:"act-section-title"},"Needs attention"),oJ({className:"act-empty"},B.issuesError?"Could not load the list of problems.":B.issuesLoading?"Checking…":"No standing problems.")),E.length?u({className:"act-section"},u({className:"act-section-title"},"Recently finished"),u(...E.map((K)=>sJ(K,Q)))):null,u({className:"act-foot act-actions"},qQ({className:"btn small ghost act-rebuild"},W("refresh",{size:12}),EC("Rebuild search index")).on({click:()=>Q.exec("workbench.rebuildIndex")}),qQ({className:"btn small ghost act-scan"},W("refresh",{size:12}),EC("Scan for outside changes")).on({click:()=>Q.exec("workbench.scanCollection")})))}var{div:KA,button:zQ,span:uA,img:rJ}=w,iJ=[{id:"home",icon:"search",label:"Files",command:"workbench.view.home"},{id:"upload",icon:"upload",label:"Upload",command:"explorer.upload"},{id:"plugins",icon:"plug",label:"Plugins",command:"workbench.view.plugins"}];function FH(A){if(!A.off.online)return{icon:"info",tone:"warn",label:"Offline"};if(A.issues.length)return{icon:"warn",tone:"danger",label:`${A.issues.length} need attention`,badge:A.issues.length};if(A.running.length||A.uploading.length||A.off.syncing)return{spinner:!0,tone:"",label:"Working…"};if(A.usage?.total&&A.usage.available/A.usage.total<0.1)return{icon:"info",tone:"warn",label:"Low on space"};return{icon:"info",tone:"",label:"Status"}}function tJ(A,Q){let B=aB(A,Q),C=FH(B),E=A.wb.activity==="settings"?"Settings":A.wb.activity==="plugins"?"Plugins":B.collectionId;return KA({className:"phonebar top"},zQ({className:"pb-brand",title:"Trove — home"},rJ({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),KA({className:"pb-title"},E),zQ({className:`pb-status ${C.tone}`,title:C.label,$attrs:{"aria-label":C.label}},C.spinner?KA({className:"spinner",$styling:{width:"15px",height:"15px"}}):W(C.icon,{size:18}),C.badge?uA({className:"pb-badge"},String(C.badge>9?"9+":C.badge)):null).on({click:()=>Q.platform.workbench.openSheet("status")}))}function eJ(A,Q){let B=A.wb.activity,C=A.wb.sheet,E=A.so.notifications.unread;return KA({className:"phonebar bottom"},...iJ.map((K)=>zQ({className:`pb-tab ${!C&&B===K.id?"active":""}`,$attrs:{"aria-label":K.label}},W(K.icon,{size:21}),uA({className:"pb-label"},K.label)).on({click:()=>{Q.platform.workbench.closeSheet(),Q.exec(K.command)}})),zQ({className:`pb-tab ${C==="more"||!C&&!iJ.some((K)=>K.id===B)?"active":""}`,$attrs:{"aria-label":"More"}},W("dots",{size:21}),E?uA({className:"pb-badge"},String(E>9?"9+":E)):null,uA({className:"pb-label"},"More")).on({click:()=>Q.platform.workbench.openSheet("more")}))}function FA({icon:A,label:Q,value:B,danger:C,onClick:E}){let K=[W(A,{size:18}),uA({className:"sr-label"},Q),B!=null?uA({className:"sr-value"},B):null,E?W("chevron-right",{size:16,className:"sr-go"}):null];return E?zQ({className:`sheet-row ${C?"danger":""}`},...K).on({click:E}):KA({className:"sheet-row static"},...K)}function AY(A,Q){let B=A.wb.sheet;if(!B)return null;let C=Q.platform.workbench;return KA({className:"sheet-wrap"},KA({className:"scrim"}).on({click:()=>C.closeSheet()}),KA({className:"sheet"},KA({className:"sheet-grip"}).on({click:()=>C.closeSheet()}),B==="status"?MH(A,Q):VH(A,Q)))}function MH(A,Q){let B=aB(A,Q),C=Q.platform.workbench,E=(K)=>()=>{C.closeSheet(),Q.exec(K)};return KA({className:"sheet-body"},KA({className:"sheet-title"},B.collectionId),B.issues.length?FA({icon:"warn",danger:!0,label:`${B.issues.length} need${B.issues.length===1?"s":""} attention`,onClick:()=>{C.closeSheet(),Q.app.activity.togglePanel(!0)}}):null,B.running.length||B.uploading.length?FA({icon:"refresh",label:`${B.running.length+B.uploading.length} running`,onClick:()=>{C.closeSheet(),Q.app.activity.togglePanel(!0)}}):null,!B.off.online?FA({icon:"info",label:"Offline",value:`${B.off.pins.length} pinned`}):null,B.off.queued?FA({icon:"upload",label:"Waiting to sync",value:String(B.off.queued)}):null,FA({icon:"files",label:"Items",value:B.partial?`${B.shown.toLocaleString()} of ${B.totalKnown?B.totalItems.toLocaleString():"more"}`:B.totalItems.toLocaleString()}),FA({icon:"file",label:"Size",value:`${QA(B.totalBytes)}${B.totalKnown||!B.partial?"":"+"}`}),B.usage?.total?KA({className:"sheet-row static usage"},W("download",{size:18}),uA({className:"sr-label"},"Free space"),h0({usage:B.usage})):null,B.caps?FA({icon:B.caps.storage?.presignDownload?"download":"files",label:"Transfers",value:B.caps.storage?.presignDownload?"Direct to storage":"Through the server"}):null,B.caps?.features?.semanticSearch?FA({icon:"star",label:"Search",value:"Semantic + keyword"}):null,KA({className:"sheet-actions"},zQ({className:"btn small ghost"},W("refresh",{size:13}),uA("Scan for changes")).on({click:E("workbench.scanCollection")}),zQ({className:"btn small ghost"},W("refresh",{size:13}),uA("Activity")).on({click:()=>{Q.platform.workbench.closeSheet(),Q.app.activity.togglePanel(!0)}})))}function VH(A,Q){let B=Q.platform.workbench,C=(J)=>()=>{B.closeSheet(),Q.exec(J)},E=A.so.me,K=A.so.notifications.unread;return KA({className:"sheet-body"},E&&!E.anonymous?KA({className:"sheet-me"},E.picture?rJ({src:E.picture,alt:"",className:"avatar-img"}):uA({className:"avatar-txt"},(E.name||E.id||"?")[0].toUpperCase()),KA({},KA({className:"sm-name"},E.name||E.id),E.email?KA({className:"sm-sub"},E.email):null)):null,FA({icon:"bell",label:K?`Notifications (${K})`:"Notifications",onClick:()=>{B.closeSheet(),Q.app.social.toggleInbox(!0)}}),FA({icon:"refresh",label:"Activity & problems",onClick:()=>{B.closeSheet(),Q.app.activity.togglePanel(!0)}}),FA({icon:"info",label:"Details & conversation",onClick:C("workbench.toggleInfoPanel")}),FA({icon:"trash",label:"Trash",onClick:C("explorer.showTrash")}),FA({icon:"refresh",label:"Refresh",onClick:C("explorer.refresh")}),FA({icon:"command",label:"All commands",onClick:C("workbench.showCommandPalette")}),FA({icon:"gear",label:"Settings",onClick:C("workbench.openSettings")}))}var{alias:PH,div:OQ}=w;function AE({engine:A,app:Q,platform:B,plugins:C}){let E=f(0),K={engine:A,app:Q,platform:B,go:(I)=>A.dispatch(I),exec:(I,...D)=>B.commands.execute(I,...D),rerender:()=>E.update((I)=>I+1),uninstallPlugin:(I)=>C?.uninstall(I)},{watch:J}=B.reactive,Y=XQ([B.workbench.observe(),B.workbench.observeOverlay(),B.workbench.observeNav(),Q.explorer.observe(),Q.search.observe(),Q.transfers.observe(),B.notifications.observe(),B.context.observe(),B.settings.observe(),B.plugins.observe()??RB([]),B.contributions.observeType("statusItem"),Q.social.observe(),Q.offline.observe(),Q.activity.observe(),B.viewport.observe(),B.voice.observe(),E],(I,D,L,G,X,Z,R,F,V,g,b,M,j,z,y,p,S)=>({wb:I,overlay:D,nav:L,ex:G,se:X,tr:Z,notif:R,ctx:F,settings:V,plugins:g,statusItems:b,so:M,off:j,act:z,vp:y,voice:p,_bump:S}));return PH(()=>J(Y,(I)=>NH(I,K)))}function NH(A,Q){let B=A.vp?.mode||"desktop",C=B==="phone";return OQ({className:`shell ${B} ${A.settings["workbench.density"]==="compact"?"compact":""}`},C?tJ(A,Q):null,OQ({className:"body"},C?null:y0(A,Q),qH(A,Q)),C?eJ(A,Q):v0(A,Q),C?AY(A,Q):null,zH(A,Q),s0(A,Q),pJ(A,Q),cJ(A,Q),nJ(A,Q),lJ(A,Q),dJ(A,Q),e0(A,Q))}function qH(A,Q){switch(A.wb.activity){case"settings":return p0(A,Q);case"plugins":return l0(A,Q);default:{if(!A.nav.activeTabId)return AC(A,Q);if(!A.wb.infoPanel)return CC(A,Q);return A.vp?.mode==="phone"?x0(A,Q):OQ({className:"editor-split"},CC(A,Q),x0(A,Q))}}}function zH(A,Q){if(!A.wb.searchModal)return OQ();return OQ({className:"search-modal"},OQ({className:"scrim"}).on({click:()=>Q.platform.workbench.closeSearchModal()}),OQ({className:"search-modal-panel"},AC(A,Q,{modal:!0})))}function BY({root:A=document.querySelector(".workbench"),baseUrl:Q="",openers:B=[],views:C=[],settings:E=[],serviceWorker:K=!0}={}){let J=wK({baseUrl:Q}),{engine:Y,app:I}=eK(J);if(xJ(J),$J(J),QY(J,"opener",B),QY(J,"view",C),E.length)J.settings.register(E);J.plugins.restore();let L=AE({engine:Y,app:I,platform:J,plugins:{uninstall:(X)=>J.plugins.uninstall(X)}});w.reconcile(A,[L()]);let G=()=>{document.documentElement.dataset.theme=J.settings.get("workbench.theme")||"dark"};if(G(),_A(J.settings.observe(),()=>G()),J.viewport.install(),J.voice.refresh().catch(()=>{}),J.spatialNav.install(),J.keybindings.install(window),window.addEventListener("popstate",(X)=>J.workbench.onPopState(X)),OH(J),K&&"serviceWorker"in navigator)window.addEventListener("load",()=>navigator.serviceWorker.register("/sw.js").catch(()=>{}));return jH(Y,I),(async()=>{try{J.capabilities=await J.api.capabilities(),J.workbench.touch()}catch(X){J.notifications.error(`Cannot reach the Trove server: ${X.message}`)}Y.dispatch(new oB)})(),window.__trove={platform:J,engine:Y,app:I,test:{parsePackage:$Q,assessTrust:(X)=>J.plugins.assessTrust(X),install:(X,Z)=>J.plugins.install(X,Z),NavigateAction:jA,attachMedia:vQ}},{platform:J,engine:Y,app:I}}function QY(A,Q,B){for(let C of B){if(!C?.id)throw Error(`A ${Q} passed to createWorkbench needs an "id"`);let{id:E,...K}=C;A.contributions.register(E,{type:Q,...K})}}function OH(A){let Q=0;window.addEventListener("keydown",(B)=>{if(B.key==="Shift"&&!B.repeat){let C=Date.now();if(C-Q<400)A.workbench.openSearchModal(),Q=0;else Q=C}else if(B.key!=="Shift")Q=0})}function jH(A,Q){let B=0;window.addEventListener("dragenter",(C)=>{if(!C.dataTransfer?.types.includes("Files"))return;B++,document.body.classList.add("dragging-file")}),window.addEventListener("dragover",(C)=>{if(C.dataTransfer?.types.includes("Files"))C.preventDefault()}),window.addEventListener("dragleave",()=>{if(--B<=0)B=0,document.body.classList.remove("dragging-file")}),window.addEventListener("drop",(C)=>{if(!C.dataTransfer?.files?.length)return;C.preventDefault(),B=0,document.body.classList.remove("dragging-file"),A.dispatch(new KB(C.dataTransfer.files,Q.explorer.state.collectionId))})}BY();
|
|
354
|
+
|
|
355
|
+
//# debugId=1FB47C976F5B8EDD64756E2164756E21
|
|
356
|
+
//# sourceMappingURL=main-4cxs7prw.js.map
|