@ai4b-team/fsaos-gateway-sdk 3.12.2 → 3.13.0

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.
@@ -1,6 +1,6 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-07-10T04:59:20.564Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var aa=Object.create;var jt=Object.defineProperty;var ca=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var la=Object.getPrototypeOf,da=Object.prototype.hasOwnProperty;var pr=t=>{throw TypeError(t)};var fa=(t,e,n)=>e in t?jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Vt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),pa=(t,e)=>{for(var n in e)jt(t,n,{get:e[n],enumerable:!0})},hr=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ua(e))!da.call(t,r)&&r!==n&&jt(t,r,{get:()=>e[r],enumerable:!(s=ca(e,r))||s.enumerable});return t};var $=(t,e,n)=>(n=t!=null?aa(la(t)):{},hr(e||!t||!t.__esModule?jt(n,"default",{value:t,enumerable:!0}):n,t)),ha=t=>hr(jt({},"__esModule",{value:!0}),t);var Ht=(t,e,n)=>fa(t,typeof e!="symbol"?e+"":e,n),gs=(t,e,n)=>e.has(t)||pr("Cannot "+n);var o=(t,e,n)=>(gs(t,e,"read from private field"),n?n.call(t):e.get(t)),b=(t,e,n)=>e.has(t)?pr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),_=(t,e,n,s)=>(gs(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),P=(t,e,n)=>(gs(t,e,"access private method"),n);var Bt=(t,e,n,s)=>({set _(r){_(t,e,r,n)},get _(){return o(t,e,s)}});var gr=Vt((dc,mr)=>{mr.exports={createClient:window.supabase.createClient}});var fe=Vt((ml,ai)=>{ai.exports=React});var Wn=Vt((gl,ci)=>{ci.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Qi=Vt((ld,Ui)=>{Ui.exports=ReactDOM});var Xi=Vt((yd,Yi)=>{Yi.exports=ReactDOM});var fr={};pa(fr,{ComponentRenderer:()=>qo,EnforcementDeniedError:()=>lt,KernelProvider:()=>Do,QueryClientProvider:()=>dn,auth:()=>Gi,awaitAnchorReady:()=>zt,awaitScopeReady:()=>Er,callTool:()=>Bi,clearCachedToken:()=>ws,clearSession:()=>Ts,createItem:()=>ji,disconnectSSE:()=>nr,disposeVfsRealtimeWs:()=>ds,electHomeAnchor:()=>Jt,emitEvent:()=>ki,fetchChannelMessages:()=>Ri,fetchChannelMessagesPage:()=>yn,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>rs,fetchItemVersions:()=>mn,fetchItems:()=>gn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>ss,fetchResolvedItems:()=>dr,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>Xn,fetchVfsChildrenPage:()=>Zn,fetchVfsItem:()=>Yn,fetchVfsItemById:()=>Jn,fetchVfsTree:()=>ns,gatewayCall:()=>R,getAccessToken:()=>Ce,getAnchor:()=>Gt,getAnchorRef:()=>Je,getAnchorVersion:()=>Cs,getAssetUrl:()=>$i,getDefaultSort:()=>Zo,getHomeAnchor:()=>Ue,getMountVersion:()=>Xt,getMounts:()=>pt,getRequiredFormFields:()=>ea,getScope:()=>ue,getScopeVersion:()=>ye,getSessionEntry:()=>qn,initSession:()=>kn,initVfsRealtimeWs:()=>Rn,interpretSchema:()=>lr,invalidateAllVfs:()=>xi,invalidateChannelMessages:()=>Ti,invalidateChildren:()=>zn,invalidateItem:()=>er,invalidateOpenEnvelope:()=>Mi,invalidatePathAndParent:()=>Ci,invalidateSubtree:()=>Pi,invalidateTypes:()=>Ei,isAnchorReady:()=>xs,isScopeReady:()=>Dn,listChildren:()=>Li,mount:()=>zi,mountRealtimeScope:()=>Cn,normalizeItem:()=>pe,ping:()=>qi,pushChanges:()=>Hi,queryClient:()=>M,readItem:()=>Ki,registerCleanup:()=>Pe,resetAllSdkState:()=>ht,resolvePrincipalId:()=>Fo,setAnchor:()=>De,setCachedToken:()=>vr,setScope:()=>xr,setupRequireShim:()=>Ji,signal:()=>Wi,subscribeAnchor:()=>Ps,subscribeMounts:()=>An,subscribeScope:()=>Ye,subscribeToEvents:()=>ce,subscribeToPath:()=>Ai,subscribeToScope:()=>us,unmountRealtimeScope:()=>Di,updateItem:()=>Vi,uploadFile:()=>ta,useAccounts:()=>Ro,useAllChannels:()=>hs,useArrangement:()=>Yo,useAsset:()=>Po,useAuth:()=>ps,useChannelMessages:()=>Uo,useChannels:()=>No,useChildren:()=>oo,useComponent:()=>cr,useCreate:()=>jo,useDelete:()=>Bo,useDmChannels:()=>Ko,useEdges:()=>ho,useEventStream:()=>zo,useFileUpload:()=>sa,useInfiniteChannelMessages:()=>Qo,useInfiniteChildren:()=>po,useInfiniteItems:()=>fo,useItem:()=>ro,useItemById:()=>io,useItemHistory:()=>bo,useItemVersions:()=>vo,useItems:()=>lo,useLink:()=>$o,useList:()=>ar,useMemberFocus:()=>_o,useMounts:()=>Co,useMove:()=>Wo,useMutation:()=>Go,useNotifications:()=>ur,useOpen:()=>go,usePermission:()=>Mo,usePermissions:()=>Oo,usePrincipal:()=>Ao,useRealtimeQuery:()=>Jo,useRecentActivity:()=>wo,useResolve:()=>uo,useResolvedItems:()=>ia,useScope:()=>So,useScopeReady:()=>so,useSearch:()=>co,useTheme:()=>To,useTool:()=>ko,useTree:()=>ao,useType:()=>mo,useTypeHelpers:()=>yo,useTypes:()=>fs,useUnreadCounts:()=>Lo,useUpdate:()=>Vo,useUpdatePrincipal:()=>Ho,vfsKeys:()=>w});var lt=class t extends Error{constructor(n){let s=n.message||t.fallbackMessage(n);super(s);Ht(this,"name","EnforcementDeniedError");Ht(this,"deniedBy");Ht(this,"ruleKey");Ht(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let r=n.enforcement;this.ruleKey=r?.rule_key??void 0,this.displayName=r?.display_name??void 0}static fallbackMessage(n){let s=n.error||"",r=n.denied_by||"";return r==="rule"||s==="RULE_DENIED"?"This feature is not enabled for this workspace.":r==="entitlement"||s==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":r==="access"||s==="ACCESS_DENIED"||s==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var yr=$(gr(),1),ys=typeof window<"u"&&window.__FSAOS_CONFIG__||{},ma=ys.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",ga=ys.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",qe=ys.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",A=(0,yr.createClient)(ma,ga,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var $t=null,Tn=0,_r,bs,Mn=!1;_r=new Promise(t=>{bs=t});A.auth.onAuthStateChange((t,e)=>{e?.access_token?($t=e.access_token,Tn=e.expires_at??Math.floor(Date.now()/1e3)+3600):($t=null,Tn=0),Mn||(Mn=!0,bs())});setTimeout(()=>{Mn||(Mn=!0,bs())},5e3);function vr(t,e){$t=t,Tn=e??Math.floor(Date.now()/1e3)+3600}function ws(){$t=null,Tn=0}async function Ce(){return await _r,$t}var On=null,Fn=null,br=0,_s=new Set,Ss,Rs,In=!1;Ss=new Promise(t=>{Rs=t});function wr(){br++,_s.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Anchor listener error:",e)}})}function De(t){let e=typeof t=="string"?t:t.path,n=On!==e;On=e,Fn=typeof t=="string"?null:t,typeof t!="string"&&!ie.some(s=>s.id===t.id)&&(ie=[...ie,t],Yt()),In||(In=!0,Rs()),n&&wr()}function Gt(){return On}function Je(){return Fn}function Cs(){return br}function Ps(t){return _s.add(t),()=>{_s.delete(t)}}function zt(){return Ss}function xs(){return In}var ft=null;function Jt(t){if(ft){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}ft=t,De(t)}function Ue(){return ft}var ie=[],vs=new Set,Sr=0;function Yt(){Sr++,vs.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Mount listener error:",e)}})}function pt(){return ie}function Xt(){return Sr}function An(t){return vs.add(t),()=>{vs.delete(t)}}function Es(t){ie=t,Yt()}function Rr(t){ie.some(e=>e.id===t.id)||(ie=[...ie,t],Yt())}function Cr(t){ie.find(n=>n.id===t)&&(ie=ie.filter(n=>n.id!==t),Yt(),Fn?.id===t&&ft&&De(ft))}var dt=null,Wt=null;async function kn(){return dt||Wt||(Wt=(async()=>{let t=Ms(),e=await Ce(),n={};e&&(n.Authorization=`Bearer ${e}`);let s=await fetch(`${qe}/d/${t}/init`,{method:"GET",headers:n});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let r=await s.json(),i=r.entry||r;return dt={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},dt})(),Wt)}function qn(){return dt}function Ts(){dt=null,Wt=null,On=null,Fn=null,ft=null,ie=[]}var Pr=[];function Pe(t){Pr.push(t)}function ht(){Ts(),ws(),In=!1,Ss=new Promise(t=>{Rs=t}),wr(),Yt();for(let t of Pr)try{t()}catch(e){console.warn("[SDK] Cleanup function failed:",e)}}function Ms(){if(typeof window<"u"){let t=window.__FSAOS_CONFIG__;return t?.hostname?t.hostname:window.location.hostname}return"localhost"}var xr=De,ue=Gt,ye=Cs,Ye=Ps,Er=zt,Dn=xs;var ya=new Set(["list-memberships","init"]);async function R(t,e={}){let n=Ms(),s=`${qe}/d/${n}`,r={"Content-Type":"application/json"},i=await Ce();i&&(r.Authorization=`Bearer ${i}`),!ya.has(t)&&!e._scope_path&&await zt();let a={...e},c=qn();!a.domain_scope_id&&c?.scope_id&&(a.domain_scope_id=c.scope_id);let u=Gt();!a._scope_path&&u&&(a._scope_path=u);let l=await fetch(s,{method:"POST",headers:r,body:JSON.stringify({method:t,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let d=await l.json();if(d.success===!1){let m=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||m==="RULE_DENIED"||m==="ACCESS_DENIED"||m==="PERMISSION_DENIED"||m==="ENTITLEMENT_REQUIRED"?new lt(d):new Error(d.message||d.error||`Gateway call ${t} failed`)}return d}var oe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Xe,Qe,mt,Tr,_a=(Tr=class extends oe{constructor(){super();b(this,Xe);b(this,Qe);b(this,mt);_(this,mt,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Qe)||this.setEventListener(o(this,mt))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Qe))==null||e.call(this),_(this,Qe,void 0))}setEventListener(e){var n;_(this,mt,e),(n=o(this,Qe))==null||n.call(this),_(this,Qe,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){o(this,Xe)!==e&&(_(this,Xe,e),this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){return typeof o(this,Xe)=="boolean"?o(this,Xe):globalThis.document?.visibilityState!=="hidden"}},Xe=new WeakMap,Qe=new WeakMap,mt=new WeakMap,Tr),gt=new _a;var va={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Ne,Os,Mr,ba=(Mr=class{constructor(){b(this,Ne,va);b(this,Os,!1)}setTimeoutProvider(t){_(this,Ne,t)}setTimeout(t,e){return o(this,Ne).setTimeout(t,e)}clearTimeout(t){o(this,Ne).clearTimeout(t)}setInterval(t,e){return o(this,Ne).setInterval(t,e)}clearInterval(t){o(this,Ne).clearInterval(t)}},Ne=new WeakMap,Os=new WeakMap,Mr),_e=new ba;function Or(t){setTimeout(t,0)}var Fs=typeof window>"u"||"Deno"in globalThis;function q(){}function Ar(t,e){return typeof t=="function"?t(e):t}function Zt(t){return typeof t=="number"&&t>=0&&t!==1/0}function Un(t,e){return Math.max(t+(e||0)-Date.now(),0)}function le(t,e){return typeof t=="function"?t(e):t}function Y(t,e){return typeof t=="function"?t(e):t}function Qn(t,e){let{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==en(a,e.options))return!1}else if(!Ze(e.queryKey,a))return!1}if(n!=="all"){let u=e.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||r&&r!==e.state.fetchStatus||i&&!i(e))}function Nn(t,e){let{exact:n,status:s,predicate:r,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(ve(e.options.mutationKey)!==ve(i))return!1}else if(!Ze(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||r&&!r(e))}function en(t,e){return(e?.queryKeyHashFn||ve)(t)}function ve(t){return JSON.stringify(t,(e,n)=>Is(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function Ze(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>Ze(t[n],e[n])):!1}var wa=Object.prototype.hasOwnProperty;function As(t,e,n=0){if(t===e)return t;if(n>500)return e;let s=Ir(t)&&Ir(e);if(!s&&!(Is(t)&&Is(e)))return e;let i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},l=0;for(let d=0;d<c;d++){let m=s?d:a[d],f=t[m],p=e[m];if(f===p){u[m]=f,(s?d<i:wa.call(t,m))&&l++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[m]=p;continue}let v=As(f,p,n+1);u[m]=v,v===f&&l++}return i===c&&l===i?t:u}function yt(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let n in t)if(t[n]!==e[n])return!1;return!0}function Ir(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Is(t){if(!Fr(t))return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(!Fr(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Fr(t){return Object.prototype.toString.call(t)==="[object Object]"}function kr(t){return new Promise(e=>{_e.setTimeout(e,t)})}function tn(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?As(t,e):e}function qr(t,e,n=0){let s=[...t,e];return n&&s.length>n?s.slice(1):s}function Dr(t,e,n=0){let s=[e,...t];return n&&s.length>n?s.slice(0,-1):s}var _t=Symbol();function Kn(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===_t?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function vt(t,e){return typeof t=="function"?t(...e):!!t}function Ur(t,e,n){let s=!1,r;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(r??(r=e()),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),t}var be=(()=>{let t=()=>Fs;return{isServer(){return t()},setIsServer(e){t=e}}})();function nn(){let t,e,n=new Promise((r,i)=>{t=r,e=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),t(r)},n.reject=r=>{s({status:"rejected",reason:r}),e(r)},n}var Qr=Or;function Sa(){let t=[],e=0,n=c=>{c()},s=c=>{c()},r=Qr,i=c=>{e?t.push(c):r(()=>{n(c)})},a=()=>{let c=t;t=[],c.length&&r(()=>{s(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},batchCalls:c=>(...u)=>{i(()=>{c(...u)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{s=c},setScheduler:c=>{r=c}}}var F=Sa();var bt,Ke,wt,Nr,Ra=(Nr=class extends oe{constructor(){super();b(this,bt,!0);b(this,Ke);b(this,wt);_(this,wt,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",s)}}})}onSubscribe(){o(this,Ke)||this.setEventListener(o(this,wt))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Ke))==null||e.call(this),_(this,Ke,void 0))}setEventListener(e){var n;_(this,wt,e),(n=o(this,Ke))==null||n.call(this),_(this,Ke,e(this.setOnline.bind(this)))}setOnline(e){o(this,bt)!==e&&(_(this,bt,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return o(this,bt)}},bt=new WeakMap,Ke=new WeakMap,wt=new WeakMap,Nr),St=new Ra;function Ca(t){return Math.min(1e3*2**t,3e4)}function ks(t){return(t??"online")==="online"?St.isOnline():!0}var Ln=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function jn(t){let e=!1,n=0,s,r=nn(),i=()=>r.status!=="pending",a=h=>{if(!i()){let g=new Ln(h);f(g),t.onCancel?.(g)}},c=()=>{e=!0},u=()=>{e=!1},l=()=>gt.isFocused()&&(t.networkMode==="always"||St.isOnline())&&t.canRun(),d=()=>ks(t.networkMode)&&t.canRun(),m=h=>{i()||(s?.(),r.resolve(h))},f=h=>{i()||(s?.(),r.reject(h))},p=()=>new Promise(h=>{s=g=>{(i()||l())&&h(g)},t.onPause?.()}).then(()=>{s=void 0,i()||t.onContinue?.()}),v=()=>{if(i())return;let h,g=n===0?t.initialPromise:void 0;try{h=g??t.fn()}catch(S){h=Promise.reject(S)}Promise.resolve(h).then(m).catch(S=>{if(i())return;let C=t.retry??(be.isServer()?0:3),x=t.retryDelay??Ca,U=typeof x=="function"?x(n,S):x,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(e||!L){f(S);return}n++,t.onFail?.(n,S),kr(U).then(()=>l()?void 0:p()).then(()=>{e?f(S):v()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(s?.(),r),cancelRetry:c,continueRetry:u,canStart:d,start:()=>(d()?v():p().then(v),r)}}var et,Kr,Vn=(Kr=class{constructor(){b(this,et)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Zt(this.gcTime)&&_(this,et,_e.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(be.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,et)!==void 0&&(_e.clearTimeout(o(this,et)),_(this,et,void 0))}},et=new WeakMap,Kr);var tt,Rt,ae,nt,j,sn,st,se,Br,xe,Vr,Hr=(Vr=class extends Vn{constructor(e){super();b(this,se);b(this,tt);b(this,Rt);b(this,ae);b(this,nt);b(this,j);b(this,sn);b(this,st);_(this,st,!1),_(this,sn,e.defaultOptions),this.setOptions(e.options),this.observers=[],_(this,nt,e.client),_(this,ae,o(this,nt).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_(this,tt,jr(this.options)),this.state=e.state??o(this,tt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,j)?.promise}setOptions(e){if(this.options={...o(this,sn),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=jr(this.options);n.data!==void 0&&(this.setState(Lr(n.data,n.dataUpdatedAt)),_(this,tt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,ae).remove(this)}setData(e,n){let s=tn(this.state.data,e,this.options);return P(this,se,xe).call(this,{data:s,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),s}setState(e,n){P(this,se,xe).call(this,{type:"setState",state:e,setStateOptions:n})}cancel(e){let n=o(this,j)?.promise;return o(this,j)?.cancel(e),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,tt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===_t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>le(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Un(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),o(this,ae).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(o(this,j)&&(o(this,st)||P(this,se,Br).call(this)?o(this,j).cancel({revert:!0}):o(this,j).cancelRetry()),this.scheduleGc()),o(this,ae).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,se,xe).call(this,{type:"invalidate"})}async fetch(e,n){if(this.state.fetchStatus!=="idle"&&o(this,j)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,j))return o(this,j).continueRetry(),o(this,j).promise}if(e&&this.setOptions(e),!this.options.queryFn){let u=this.observers.find(l=>l.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(_(this,st,!0),s.signal)})},i=()=>{let u=Kn(this.options,n),d=(()=>{let m={client:o(this,nt),queryKey:this.queryKey,meta:this.meta};return r(m),m})();return _(this,st,!1),this.options.persister?this.options.persister(u,d,this):u(d)},c=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,nt),state:this.state,fetchFn:i};return r(u),u})();this.options.behavior?.onFetch(c,this),_(this,Rt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&P(this,se,xe).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),_(this,j,jn({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:u=>{u instanceof Ln&&u.revert&&this.setState({...o(this,Rt),fetchStatus:"idle"}),s.abort()},onFail:(u,l)=>{P(this,se,xe).call(this,{type:"failed",failureCount:u,error:l})},onPause:()=>{P(this,se,xe).call(this,{type:"pause"})},onContinue:()=>{P(this,se,xe).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let u=await o(this,j).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),o(this,ae).config.onSuccess?.(u,this),o(this,ae).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Ln){if(u.silent)return o(this,j).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw P(this,se,xe).call(this,{type:"error",error:u}),o(this,ae).config.onError?.(u,this),o(this,ae).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},tt=new WeakMap,Rt=new WeakMap,ae=new WeakMap,nt=new WeakMap,j=new WeakMap,sn=new WeakMap,st=new WeakMap,se=new WeakSet,Br=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},xe=function(e){let n=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...qs(s.data,this.options),fetchMeta:e.meta??null};case"success":let r={...s,...Lr(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return _(this,Rt,e.manual?r:void 0),r;case"error":let i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=n(this.state),F.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),o(this,ae).notify({query:this,type:"updated",action:e})})},Vr);function qs(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Lr(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function jr(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,s=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var X,E,on,z,rt,Ct,Ee,Le,an,Pt,xt,it,ot,je,Et,O,rn,Ds,Us,Qs,Ns,Ks,Ls,js,zr,Gr,cn=(Gr=class extends oe{constructor(e,n){super();b(this,O);b(this,X);b(this,E);b(this,on);b(this,z);b(this,rt);b(this,Ct);b(this,Ee);b(this,Le);b(this,an);b(this,Pt);b(this,xt);b(this,it);b(this,ot);b(this,je);b(this,Et,new Set);this.options=n,_(this,X,e),_(this,Le,null),_(this,Ee,nn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,E).addObserver(this),Wr(o(this,E),this.options)?P(this,O,rn).call(this):this.updateResult(),P(this,O,Ns).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Vs(o(this,E),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Vs(o(this,E),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,O,Ks).call(this),P(this,O,Ls).call(this),o(this,E).removeObserver(this)}setOptions(e){let n=this.options,s=o(this,E);if(this.options=o(this,X).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Y(this.options.enabled,o(this,E))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,O,js).call(this),o(this,E).setOptions(this.options),n._defaulted&&!yt(this.options,n)&&o(this,X).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,E),observer:this});let r=this.hasListeners();r&&$r(o(this,E),s,this.options,n)&&P(this,O,rn).call(this),this.updateResult(),r&&(o(this,E)!==s||Y(this.options.enabled,o(this,E))!==Y(n.enabled,o(this,E))||le(this.options.staleTime,o(this,E))!==le(n.staleTime,o(this,E)))&&P(this,O,Ds).call(this);let i=P(this,O,Us).call(this);r&&(o(this,E)!==s||Y(this.options.enabled,o(this,E))!==Y(n.enabled,o(this,E))||i!==o(this,je))&&P(this,O,Qs).call(this,i)}getOptimisticResult(e){let n=o(this,X).getQueryCache().build(o(this,X),e),s=this.createResult(n,e);return xa(this,s)&&(_(this,z,s),_(this,Ct,this.options),_(this,rt,o(this,E).state)),s}getCurrentResult(){return o(this,z)}trackResult(e,n){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),n?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Ee).status==="pending"&&o(this,Ee).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){o(this,Et).add(e)}getCurrentQuery(){return o(this,E)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let n=o(this,X).defaultQueryOptions(e),s=o(this,X).getQueryCache().build(o(this,X),n);return s.fetch().then(()=>this.createResult(s,n))}fetch(e){return P(this,O,rn).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(e,n){let s=o(this,E),r=this.options,i=o(this,z),a=o(this,rt),c=o(this,Ct),l=e!==s?e.state:o(this,on),{state:d}=e,m={...d},f=!1,p;if(n._optimisticResults){let Q=this.hasListeners(),J=!Q&&Wr(e,n),he=Q&&$r(e,s,n,r);(J||he)&&(m={...m,...qs(d.data,e.options)}),n._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:v,errorUpdatedAt:h,status:g}=m;p=m.data;let S=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(o(this,xt)?.state.data,o(this,xt)):n.placeholderData,Q!==void 0&&(g="success",p=tn(i?.data,Q,n),f=!0)}if(n.select&&p!==void 0&&!S)if(i&&p===a?.data&&n.select===o(this,an))p=o(this,Pt);else try{_(this,an,n.select),p=n.select(p),p=tn(i?.data,p,n),_(this,Pt,p),_(this,Le,null)}catch(Q){_(this,Le,Q)}o(this,Le)&&(v=o(this,Le),p=o(this,Pt),h=Date.now(),g="error");let C=m.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&C,H=p!==void 0,ne={status:g,fetchStatus:m.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:p,dataUpdatedAt:m.dataUpdatedAt,error:v,errorUpdatedAt:h,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:m.dataUpdateCount>l.dataUpdateCount||m.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!x,isLoadingError:U&&!H,isPaused:m.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&H,isStale:Hs(e,n),refetch:this.refetch,promise:o(this,Ee),isEnabled:Y(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let Q=ne.data!==void 0,J=ne.status==="error"&&!Q,he=T=>{J?T.reject(ne.error):Q&&T.resolve(ne.data)},me=()=>{let T=_(this,Ee,ne.promise=nn());he(T)},ge=o(this,Ee);switch(ge.status){case"pending":e.queryHash===s.queryHash&&he(ge);break;case"fulfilled":(J||ne.data!==ge.value)&&me();break;case"rejected":(!J||ne.error!==ge.reason)&&me();break}}return ne}updateResult(){let e=o(this,z),n=this.createResult(o(this,E),this.options);if(_(this,rt,o(this,E).state),_(this,Ct,this.options),o(this,rt).data!==void 0&&_(this,xt,o(this,E)),yt(n,e))return;_(this,z,n);let s=()=>{if(!e)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!o(this,Et).size)return!0;let a=new Set(i??o(this,Et));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(c=>{let u=c;return o(this,z)[u]!==e[u]&&a.has(u)})};P(this,O,zr).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,O,Ns).call(this)}},X=new WeakMap,E=new WeakMap,on=new WeakMap,z=new WeakMap,rt=new WeakMap,Ct=new WeakMap,Ee=new WeakMap,Le=new WeakMap,an=new WeakMap,Pt=new WeakMap,xt=new WeakMap,it=new WeakMap,ot=new WeakMap,je=new WeakMap,Et=new WeakMap,O=new WeakSet,rn=function(e){P(this,O,js).call(this);let n=o(this,E).fetch(this.options,e);return e?.throwOnError||(n=n.catch(q)),n},Ds=function(){P(this,O,Ks).call(this);let e=le(this.options.staleTime,o(this,E));if(be.isServer()||o(this,z).isStale||!Zt(e))return;let s=Un(o(this,z).dataUpdatedAt,e)+1;_(this,it,_e.setTimeout(()=>{o(this,z).isStale||this.updateResult()},s))},Us=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,E)):this.options.refetchInterval)??!1},Qs=function(e){P(this,O,Ls).call(this),_(this,je,e),!(be.isServer()||Y(this.options.enabled,o(this,E))===!1||!Zt(o(this,je))||o(this,je)===0)&&_(this,ot,_e.setInterval(()=>{(this.options.refetchIntervalInBackground||gt.isFocused())&&P(this,O,rn).call(this)},o(this,je)))},Ns=function(){P(this,O,Ds).call(this),P(this,O,Qs).call(this,P(this,O,Us).call(this))},Ks=function(){o(this,it)!==void 0&&(_e.clearTimeout(o(this,it)),_(this,it,void 0))},Ls=function(){o(this,ot)!==void 0&&(_e.clearInterval(o(this,ot)),_(this,ot,void 0))},js=function(){let e=o(this,X).getQueryCache().build(o(this,X),this.options);if(e===o(this,E))return;let n=o(this,E);_(this,E,e),_(this,on,e.state),this.hasListeners()&&(n?.removeObserver(this),e.addObserver(this))},zr=function(e){F.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,X).getQueryCache().notify({query:o(this,E),type:"observerResultsUpdated"})})},Gr);function Pa(t,e){return Y(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Wr(t,e){return Pa(t,e)||t.state.data!==void 0&&Vs(t,e,e.refetchOnMount)}function Vs(t,e,n){if(Y(e.enabled,t)!==!1&&le(e.staleTime,t)!=="static"){let s=typeof n=="function"?n(t):n;return s==="always"||s!==!1&&Hs(t,e)}return!1}function $r(t,e,n,s){return(t!==e||Y(s.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&Hs(t,n)}function Hs(t,e){return Y(e.enabled,t)!==!1&&t.isStaleByTime(le(e.staleTime,t))}function xa(t,e){return!yt(t.getCurrentResult(),e)}function Tt(t){return{onFetch:(e,n)=>{let s=e.options,r=e.fetchOptions?.meta?.fetchMore?.direction,i=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,l=async()=>{let d=!1,m=v=>{Ur(v,()=>e.signal,()=>d=!0)},f=Kn(e.options,e.fetchOptions),p=async(v,h,g)=>{if(d)return Promise.reject();if(h==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let H={client:e.client,queryKey:e.queryKey,pageParam:h,direction:g?"backward":"forward",meta:e.options.meta};return m(H),H})(),x=await f(C),{maxPages:U}=e.options,L=g?Dr:qr;return{pages:L(v.pages,x,U),pageParams:L(v.pageParams,h,U)}};if(r&&i.length){let v=r==="backward",h=v?Jr:Bs,g={pages:i,pageParams:a},S=h(s,g);c=await p(g,S,v)}else{let v=t??i.length;do{let h=u===0?a[0]??s.initialPageParam:Bs(s,c);if(u>0&&h==null)break;c=await p(c,h),u++}while(u<v)}return c};e.options.persister?e.fetchFn=()=>e.options.persister?.(l,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=l}}}function Bs(t,{pages:e,pageParams:n}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,n[s],n):void 0}function Jr(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}function Yr(t,e){return e?Bs(t,e)!=null:!1}function Xr(t,e){return!e||!t.getPreviousPageParam?!1:Jr(t,e)!=null}var Ws=class extends cn{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t){super.setOptions({...t,behavior:Tt()})}getOptimisticResult(t){return t.behavior=Tt(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){let{state:n}=t,s=super.createResult(t,e),{isFetching:r,isRefetching:i,isError:a,isRefetchError:c}=s,u=n.fetchMeta?.fetchMore?.direction,l=a&&u==="forward",d=r&&u==="forward",m=a&&u==="backward",f=r&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Yr(e,n.data),hasPreviousPage:Xr(e,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:f,isRefetchError:c&&!l&&!m,isRefetching:i&&!d&&!f}}};var un,we,G,at,Se,Ve,Zr,ei=(Zr=class extends Vn{constructor(e){super();b(this,Se);b(this,un);b(this,we);b(this,G);b(this,at);_(this,un,e.client),this.mutationId=e.mutationId,_(this,G,e.mutationCache),_(this,we,[]),this.state=e.state||$s(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){o(this,we).includes(e)||(o(this,we).push(e),this.clearGcTimeout(),o(this,G).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_(this,we,o(this,we).filter(n=>n!==e)),this.scheduleGc(),o(this,G).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){o(this,we).length||(this.state.status==="pending"?this.scheduleGc():o(this,G).remove(this))}continue(){return o(this,at)?.continue()??this.execute(this.state.variables)}async execute(e){let n=()=>{P(this,Se,Ve).call(this,{type:"continue"})},s={client:o(this,un),meta:this.options.meta,mutationKey:this.options.mutationKey};_(this,at,jn({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,c)=>{P(this,Se,Ve).call(this,{type:"failed",failureCount:a,error:c})},onPause:()=>{P(this,Se,Ve).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,G).canRun(this)}));let r=this.state.status==="pending",i=!o(this,at).canStart();try{if(r)n();else{P(this,Se,Ve).call(this,{type:"pending",variables:e,isPaused:i}),o(this,G).config.onMutate&&await o(this,G).config.onMutate(e,this,s);let c=await this.options.onMutate?.(e,s);c!==this.state.context&&P(this,Se,Ve).call(this,{type:"pending",context:c,variables:e,isPaused:i})}let a=await o(this,at).start();return await o(this,G).config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await o(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),P(this,Se,Ve).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,G).config.onError?.(a,e,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(c){Promise.reject(c)}try{await o(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(c){Promise.reject(c)}throw P(this,Se,Ve).call(this,{type:"error",error:a}),a}finally{o(this,G).runNext(this)}}},un=new WeakMap,we=new WeakMap,G=new WeakMap,at=new WeakMap,Se=new WeakSet,Ve=function(e){let n=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),F.batch(()=>{o(this,we).forEach(s=>{s.onMutationUpdate(e)}),o(this,G).notify({mutation:this,type:"updated",action:e})})},Zr);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Te,de,ln,ti,ni=(ti=class extends oe{constructor(e={}){super();b(this,Te);b(this,de);b(this,ln);this.config=e,_(this,Te,new Set),_(this,de,new Map),_(this,ln,0)}build(e,n,s){let r=new ei({client:e,mutationCache:this,mutationId:++Bt(this,ln)._,options:e.defaultMutationOptions(n),state:s});return this.add(r),r}add(e){o(this,Te).add(e);let n=Hn(e);if(typeof n=="string"){let s=o(this,de).get(n);s?s.push(e):o(this,de).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(o(this,Te).delete(e)){let n=Hn(e);if(typeof n=="string"){let s=o(this,de).get(n);if(s)if(s.length>1){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&o(this,de).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){let n=Hn(e);if(typeof n=="string"){let r=o(this,de).get(n)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){let n=Hn(e);return typeof n=="string"?o(this,de).get(n)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){F.batch(()=>{o(this,Te).forEach(e=>{this.notify({type:"removed",mutation:e})}),o(this,Te).clear(),o(this,de).clear()})}getAll(){return Array.from(o(this,Te))}find(e){let n={exact:!0,...e};return this.getAll().find(s=>Nn(n,s))}findAll(e={}){return this.getAll().filter(n=>Nn(e,n))}notify(e){F.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){let e=this.getAll().filter(n=>n.state.isPaused);return F.batch(()=>Promise.all(e.map(n=>n.continue().catch(q))))}},Te=new WeakMap,de=new WeakMap,ln=new WeakMap,ti);function Hn(t){return t.options.scope?.id}var Me,He,Z,Oe,Ie,Bn,Gs,si,zs=(si=class extends oe{constructor(e,n){super();b(this,Ie);b(this,Me);b(this,He);b(this,Z);b(this,Oe);_(this,Me,e),this.setOptions(n),this.bindMethods(),P(this,Ie,Bn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let n=this.options;this.options=o(this,Me).defaultMutationOptions(e),yt(this.options,n)||o(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,Z),observer:this}),n?.mutationKey&&this.options.mutationKey&&ve(n.mutationKey)!==ve(this.options.mutationKey)?this.reset():o(this,Z)?.state.status==="pending"&&o(this,Z).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,Z)?.removeObserver(this)}onMutationUpdate(e){P(this,Ie,Bn).call(this),P(this,Ie,Gs).call(this,e)}getCurrentResult(){return o(this,He)}reset(){o(this,Z)?.removeObserver(this),_(this,Z,void 0),P(this,Ie,Bn).call(this),P(this,Ie,Gs).call(this)}mutate(e,n){return _(this,Oe,n),o(this,Z)?.removeObserver(this),_(this,Z,o(this,Me).getMutationCache().build(o(this,Me),this.options)),o(this,Z).addObserver(this),o(this,Z).execute(e)}},Me=new WeakMap,He=new WeakMap,Z=new WeakMap,Oe=new WeakMap,Ie=new WeakSet,Bn=function(){let e=o(this,Z)?.state??$s();_(this,He,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},Gs=function(e){F.batch(()=>{if(o(this,Oe)&&this.hasListeners()){let n=o(this,He).variables,s=o(this,He).context,r={client:o(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{o(this,Oe).onSuccess?.(e.data,n,s,r)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(e.data,null,n,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{o(this,Oe).onError?.(e.error,n,s,r)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(void 0,e.error,n,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,He))})})},si);var Re,ri,ii=(ri=class extends oe{constructor(e={}){super();b(this,Re);this.config=e,_(this,Re,new Map)}build(e,n,s){let r=n.queryKey,i=n.queryHash??en(r,n),a=this.get(i);return a||(a=new Hr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(n),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){o(this,Re).has(e.queryHash)||(o(this,Re).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let n=o(this,Re).get(e.queryHash);n&&(e.destroy(),n===e&&o(this,Re).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){F.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return o(this,Re).get(e)}getAll(){return[...o(this,Re).values()]}find(e){let n={exact:!0,...e};return this.getAll().find(s=>Qn(n,s))}findAll(e={}){let n=this.getAll();return Object.keys(e).length>0?n.filter(s=>Qn(e,s)):n}notify(e){F.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){F.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){F.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Re=new WeakMap,ri);var D,Be,We,Mt,Ot,$e,It,Ft,oi,Js=(oi=class{constructor(t={}){b(this,D);b(this,Be);b(this,We);b(this,Mt);b(this,Ot);b(this,$e);b(this,It);b(this,Ft);_(this,D,t.queryCache||new ii),_(this,Be,t.mutationCache||new ni),_(this,We,t.defaultOptions||{}),_(this,Mt,new Map),_(this,Ot,new Map),_(this,$e,0)}mount(){Bt(this,$e)._++,o(this,$e)===1&&(_(this,It,gt.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,D).onFocus())})),_(this,Ft,St.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,D).onOnline())})))}unmount(){var t,e;Bt(this,$e)._--,o(this,$e)===0&&((t=o(this,It))==null||t.call(this),_(this,It,void 0),(e=o(this,Ft))==null||e.call(this),_(this,Ft,void 0))}isFetching(t){return o(this,D).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return o(this,Be).findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,D).get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),n=o(this,D).build(this,e),s=n.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(le(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return o(this,D).findAll(t).map(({queryKey:e,state:n})=>{let s=n.data;return[e,s]})}setQueryData(t,e,n){let s=this.defaultQueryOptions({queryKey:t}),i=o(this,D).get(s.queryHash)?.state.data,a=Ar(e,i);if(a!==void 0)return o(this,D).build(this,s).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return F.batch(()=>o(this,D).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,n)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,D).get(e.queryHash)?.state}removeQueries(t){let e=o(this,D);F.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){let n=o(this,D);return F.batch(()=>(n.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let n={revert:!0,...e},s=F.batch(()=>o(this,D).findAll(t).map(r=>r.cancel(n)));return Promise.all(s).then(q).catch(q)}invalidateQueries(t,e={}){return F.batch(()=>(o(this,D).findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let n={...e,cancelRefetch:e.cancelRefetch??!0},s=F.batch(()=>o(this,D).findAll(t).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(q)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let n=o(this,D).build(this,e);return n.isStaleByTime(le(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(q).catch(q)}fetchInfiniteQuery(t){return t.behavior=Tt(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(q).catch(q)}ensureInfiniteQueryData(t){return t.behavior=Tt(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return St.isOnline()?o(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,D)}getMutationCache(){return o(this,Be)}getDefaultOptions(){return o(this,We)}setDefaultOptions(t){_(this,We,t)}setQueryDefaults(t,e){o(this,Mt).set(ve(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...o(this,Mt).values()],n={};return e.forEach(s=>{Ze(t,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(t,e){o(this,Ot).set(ve(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...o(this,Ot).values()],n={};return e.forEach(s=>{Ze(t,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;let e={...o(this,We).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=en(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===_t&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...o(this,We).mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){o(this,D).clear(),o(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,We=new WeakMap,Mt=new WeakMap,Ot=new WeakMap,$e=new WeakMap,It=new WeakMap,Ft=new WeakMap,oi);var At=$(fe(),1),ui=$(Wn(),1),Ys=At.createContext(void 0),K=t=>{let e=At.useContext(Ys);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},dn=({client:t,children:e})=>(At.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,ui.jsx)(Ys.Provider,{value:t,children:e}));var $n=$(fe(),1),li=$n.createContext(!1),di=()=>$n.useContext(li),_l=li.Provider;var fn=$(fe(),1),Ea=$(Wn(),1);function Ta(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Ma=fn.createContext(Ta()),fi=()=>fn.useContext(Ma);var pi=$(fe(),1);var hi=(t,e,n)=>{let s=n?.state.error&&typeof t.throwOnError=="function"?vt(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},mi=t=>{pi.useEffect(()=>{t.clearReset()},[t])},gi=({result:t,errorResetBoundary:e,throwOnError:n,query:s,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(r&&t.data===void 0||vt(n,[t.error,s]));var yi=t=>{if(t.suspense){let n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},_i=(t,e)=>t.isLoading&&t.isFetching&&!e,vi=(t,e)=>t?.suspense&&e.isPending,Xs=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});var Ge=$(fe(),1);function Gn(t,e,n){let s=di(),r=fi(),i=K(n),a=i.defaultQueryOptions(t);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=i.getQueryCache().get(a.queryHash);a._optimisticResults=s?"isRestoring":"optimistic",yi(a),hi(a,r,c),mi(r);let u=!i.getQueryCache().get(a.queryHash),[l]=Ge.useState(()=>new e(i,a)),d=l.getOptimisticResult(a),m=!s&&t.subscribed!==!1;if(Ge.useSyncExternalStore(Ge.useCallback(f=>{let p=m?l.subscribe(F.batchCalls(f)):q;return l.updateResult(),p},[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Ge.useEffect(()=>{l.setOptions(a)},[a,l]),vi(a,d))throw Xs(a,l,r);if(gi({result:d,errorResetBoundary:r,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!be.isServer()&&_i(d,s)&&(u?Xs(a,l,r):c?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function k(t,e){return Gn(t,cn,e)}var Fe=$(fe(),1);function Ae(t,e){let n=K(e),[s]=Fe.useState(()=>new zs(n,t));Fe.useEffect(()=>{s.setOptions(t)},[s,t]);let r=Fe.useSyncExternalStore(Fe.useCallback(a=>s.subscribe(F.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=Fe.useCallback((a,c)=>{s.mutate(a,c).catch(q)},[s]);if(r.error&&vt(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function pn(t,e){return Gn(t,Ws,e)}var M=new Js({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}});function V(){return ue()??"__unscoped__"}var w={all:()=>["vfs",V()],item:t=>["vfs",V(),"item",t],itemById:t=>["vfs","item-by-id",t],children:t=>["vfs",V(),"children",t],allChildren:()=>["vfs",V(),"children"],types:t=>["vfs","types",t??"default"],edges:t=>["vfs","edges",t],search:(t,e)=>["vfs",V(),"search",t,...e??[]],items:(t,e)=>["vfs",V(),"items",t,JSON.stringify(e??{})],allItems:()=>["vfs",V(),"items"],tree:(t,e)=>["vfs",V(),"tree",t,e??1],openEnvelope:(t,e)=>["vfs",V(),"open",t,e??"__default__"],allOpenEnvelopes:()=>["vfs",V(),"open"],memberFocus:t=>["vfs","member-focus",t],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(t,e,n)=>["vfs",V(),"get-activity-feed",t,e,n],itemVersions:(t,e,n,s)=>["vfs","item-versions",t,e,n,s],itemHistory:(t,e,n)=>["vfs","item-history",t,e,n],channelMessages:(t,e)=>["vfs",V(),"channel-messages",t,e??"__top__"],allChannelMessages:()=>["vfs",V(),"channel-messages"],channels:t=>["vfs",V(),"channels",t??"all"],allChannels:()=>["vfs",V(),"channels"],notifications:(t,e)=>["vfs",V(),"notifications",t??"all",e??200],allNotifications:()=>["vfs",V(),"notifications"],unreadCounts:()=>["vfs",V(),"unread-counts"],memberships:t=>["memberships",t]};function bi(){return new Date().toISOString()}function wi(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function pe(t){let e=t.path||t.item_path||"",n=e.split("/");n.pop();let s=n.join("/"),r=t.type_data||{};return r.allowed_parent_types&&!r.accepts&&(r.accepts=r.allowed_parent_types),delete r.allowed_parent_types,{id:t.id||t.item_id||"",name:t.name||t.item_name||"",item_type:t.item_type||"unknown",path:e,parent_path:s,is_active:t.is_active!==!1,has_children:t.has_children??!1,created_at:t.created_at||bi(),updated_at:t.updated_at||bi(),visibility:t.visibility,type_data:r,scope_item_id:t.scope_item_id,fractal_id:t.fractal_id,parent_instance_id:t.parent_instance_id,owner_principal_id:t.owner_principal_id,created_by_principal_id:t.created_by_principal_id,parent_id:t.parent_id,space_item_id:t.space_item_id,account_item_id:t.account_item_id}}function hn(t){return(t.content?.items||t.items||[]).map(pe)}async function Jn(t){try{let e=await R("read",{id:t});if(e.item_name||e.item_path){let s=pe(e);return s.path&&M.setQueryData(w.item(s.path),s),s}let n=e.item;if(n){let s=pe(n);return s.path&&M.setQueryData(w.item(s.path),s),s}return null}catch{return null}}async function Yn(t){try{let e=await R("read",{path:t});if(e.item_name||e.item_path)return pe(e);let n=e.item;return n?pe(n):null}catch{return null}}async function Xn(t){try{let e=await R("list",{path:t,limit:200}),n=hn(e);for(let s of n)M.setQueryData(w.item(s.path),s);return n}catch(e){return console.error(`[gateway] Failed to fetch children of ${t}:`,e),[]}}async function Zn(t,e,n){try{let s=await R("list",{path:t,limit:e,offset:n}),r=hn(s);for(let i of r)M.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch children page of ${t}:`,s),{items:[],total_hint:0}}}async function es(t){let n=await R("types-list",t?{scope_id:t}:{}),s=n.content?.items||n.items||[],r=new Map;for(let i of s){let a=i.name,c=i.type_data;!a||!c||r.set(a,{type_key:a,display_name:c.display_name||a,display_name_plural:c.display_name_plural||a+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return r}async function ts(t){try{let e=await R("edges",{item_id:t}),n=e.outgoing||[],s=e.incoming||[],r=[];for(let i of n)r.push({id:i.edge_id||wi(),source_item_id:t,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of s)r.push({id:i.edge_id||wi(),source_item_id:i.source_id||"",target_item_id:t,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return r}catch(e){return console.warn(`[gateway] Failed to fetch edges for ${t}:`,e),[]}}async function ns(t,e=1,n,s){try{let r={path:t,max_depth:e>0?e:999};n?.length&&(r.item_types=n),s&&(r.limit=s);let i=await R("tree",r),a=hn(i);for(let c of a)M.setQueryData(w.item(c.path),c);return a}catch(r){return console.error(`[gateway] Failed to fetch tree at ${t}:`,r),[]}}async function ss(t,e=50,n=0){try{let s=await R("get-activity-feed",{scope_path:t,limit:e,offset:n});return s.content?.items||s.items||s.entries||[]}catch(s){return console.error(`[gateway] Failed to fetch recent activity for ${t}:`,s),[]}}async function mn(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;try{let i=await R("item-versions",{id:t,limit:n,offset:s,include_snapshots:r});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${t}:`,i),{versions:[],total:0}}}async function rs(t,e=50,n=0){return mn(t,{limit:e,offset:n})}async function is(t,e,n){try{let s={scope_id:t};e?.length&&(s.item_types=e),n&&(s.limit=n);let r=await R("member-focus",s),i=hn(r);for(let a of i)M.setQueryData(w.item(a.path),a);return i}catch(s){return console.error(`[gateway] Failed to fetch member focus for scope ${t}:`,s),[]}}async function os(t,e){let n={path:t};e?.mode&&(n.mode=e.mode),e?.strategy&&(n.strategy=e.strategy),e?.arguments&&(n.arguments=e.arguments);let r=await R("open",n);return{item_id:r.item_id,item_path:r.item_path,item_name:r.item_name,item_type:r.item_type,render:r.render,compatible_components:r.compatible_components??[],content:r.content,metadata:r.metadata,instructions:r.instructions}}async function gn(t){let e={item_type:t.type};t.scope&&(e.scope_path=t.scope);let n={};if(t.name&&(n.name=t.name),t.tag&&(n.tag=t.tag),t.parent_id&&(n.parent_id=t.parent_id),t.sort_by&&(n.sort_by=t.sort_by),t.sort_dir&&(n.sort_dir=t.sort_dir),t.offset!=null&&(n.offset=t.offset),t.fields)for(let[s,r]of Object.entries(t.fields))n[`field.${s}`]=String(r);Object.keys(n).length>0&&(e.filters=n),t.limit!=null&&(e.limit=t.limit);try{let s=await R("query",e),r=hn(s);for(let i of r)M.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch items of type ${t.type}:`,s),{items:[],total_hint:0}}}function Si(t){return t.filter(e=>e.item_type==="card").map(e=>{let n=e.type_data||{},s=n.payload||{};return{id:e.id||"",path:e.path||"",name:e.name||(e.path||"").split("/").pop()||"",createdAt:e.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(e.name||"").startsWith("card-")?(e.name||"").substring(5):void 0,parentMessagePath:e.parent_message_path||void 0,visibility:n.visibility||"private",openWith:s.open_with||void 0,hostBundled:s.host_bundled===!0?!0:void 0,bundleExport:s.bundle_export||void 0,launchArguments:s.launch_arguments||void 0,requiresUserAttention:s.requires_user_attention===!0?!0:void 0}}).sort((e,n)=>e.createdAt.localeCompare(n.createdAt))}function Zs(t){return t.filter(e=>e.item_type==="message").map(e=>{let n=e.type_data||{},s="user";n.role==="assistant"?s="assistant":n.role==="system"&&(s="system");let r=n.metadata||{};return{id:e.id||"",path:e.path||"",content:n.message||n.content||"",created_at:e.created_at||"",role:s,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:r.intent_card,metadata:Object.keys(r).length>0?r:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((e,n)=>e.seq-n.seq)}async function Ri(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await R("get-channel-messages",n),i=r.messages||r.content?.items||r.items||[];return Zs(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${t}:`,n),[]}}async function as(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await R("get-channel-messages",n),i=r.messages||[],a=Zs(i),c=Si(i),u=new Map,l=[];for(let d of c)if(d.parentMessagePath){let m=u.get(d.parentMessagePath)||[];m.push(d),u.set(d.parentMessagePath,m)}else l.push(d);return{messages:a,messageCards:u,siblingCards:l,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function yn(t,e){try{let n={channel_path:t};e?.parentMessageId&&(n.parent_message_id=e.parentMessageId),e?.limit&&(n.limit=e.limit),e?.before_seq!=null&&(n.before_seq=e.before_seq),e?.after_seq!=null&&(n.after_seq=e.after_seq);let r=await R("get-channel-messages",n),i=r.messages||[],a=Si(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else u.push(l);return{messages:Zs(i),messageCards:c,siblingCards:u,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function zn(t){M.invalidateQueries({queryKey:w.children(t)})}function er(t){M.invalidateQueries({queryKey:w.item(t)})}function Ci(t,e){er(t),zn(t);let n=t.split("/");n.pop();let s=n.join("/")||e;s&&zn(s)}function Pi(t){let e=t+"/";M.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]!=="vfs"?!1:s.some(r=>typeof r=="string"&&(r===t||r.startsWith(e)))}})}function xi(){M.invalidateQueries({queryKey:w.all()})}function Ei(t){M.invalidateQueries({queryKey:w.types(t)})}function Ti(t,e){t?M.invalidateQueries({queryKey:w.channelMessages(t,e)}):M.invalidateQueries({queryKey:w.allChannelMessages()})}function Mi(t,e){t&&e?M.invalidateQueries({queryKey:w.openEnvelope(t,e)}):t?M.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]==="vfs"&&s[2]==="open"&&s[3]===t}}):M.invalidateQueries({queryKey:w.allOpenEnvelopes()})}var Oa=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function B(...t){Oa&&console.log("[WS]",...t)}var I=null,kt=null,qt=null,_n=0,Ia=3e4,Oi=1e4,Ut=!1,Fa=3e4,cs=null,Ii=!1;function Aa(){bn(),cs=setInterval(()=>{ke({type:"ping"})},Fa)}function bn(){cs&&(clearInterval(cs),cs=null)}function ka(){typeof document>"u"||(document.hidden?bn():vn()&&(B("Tab visible, reconnecting..."),wn()))}function qa(){Ii||typeof document>"u"||(document.addEventListener("visibilitychange",ka),Ii=!0)}var ee={},Dt=[],Qt=new Map,ct=new Map;function Da(){return Object.keys(ee).some(e=>ee[e]&&ee[e].length>0)||Dt.length>0}function vn(){return Qt.size>0||ct.size>0}async function wn(){if(!vn()){B("ensureConnection: no active subscriptions, skipping");return}if(I&&I.readyState===WebSocket.OPEN){B("ensureConnection: already open");return}if(kt)return B("ensureConnection: connection already in flight, waiting..."),kt;if(I){B("ensureConnection: killing stale WS in state",I.readyState);try{I.close()}catch{}I=null}return Ut=!1,kt=(async()=>{try{let t=typeof window<"u"&&window.__FSAOS_CONFIG__||{},e=qe,s=t.embedToken||null;if(s||(s=await Ce()),!s){B("ensureConnection: no token available, will retry"),Fi();return}let r=e.startsWith("https")?"wss":"ws",i=e.replace(/^https?:\/\//,""),a=`${r}://${i}/ws`;a+=`?token=${encodeURIComponent(s)}`,B("ensureConnection: opening WS to",a.substring(0,50)+"..."),I=new WebSocket(a),await new Promise((c,u)=>{if(!I)return u(new Error("WebSocket not created"));let l=setTimeout(()=>{if(B("ensureConnection: TIMEOUT after",Oi,"ms"),I&&I.readyState!==WebSocket.OPEN){try{I.close()}catch{}I=null}u(new Error("WebSocket connection timeout"))},Oi);I.onopen=()=>{clearTimeout(l),B("ensureConnection: CONNECTED"),_n=0,Ua(),(typeof document>"u"||!document.hidden)&&Aa(),qa(),c()},I.onmessage=d=>{Qa(d.data)},I.onerror=()=>{B("ensureConnection: WS error event")},I.onclose=d=>{clearTimeout(l),B("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),I=null,bn(),!Ut&&vn()&&Fi(),u(new Error(`WebSocket closed: ${d.code}`))}})}catch(t){B("ensureConnection: failed -",t?.message||t)}finally{kt=null}})(),kt}function Fi(){if(qt||typeof document<"u"&&document.hidden)return;let t=Math.min(1e3*Math.pow(2,_n)+Math.random()*1e3,Ia);_n++,B("scheduleReconnect: attempt",_n,"in",Math.round(t),"ms"),qt=setTimeout(()=>{qt=null,vn()&&wn()},t)}function Ua(){for(let t of Qt.values())B("resubscribeAll: scope",t.scope_id),ke({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ct.values())B("resubscribeAll: path",t.path),ke({type:"subscribe_path",path:t.path,event_types:t.event_types})}function ke(t){I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify(t))}function Qa(t){try{let e=JSON.parse(t);if(e.type==="subscribed"||e.type==="subscribed_path"||e.type==="unsubscribed"||e.type==="unsubscribed_path"||e.type==="pong")return;if(e.type==="error"){console.warn("[WS] Server error:",e.message);return}if(e.type==="event"||e.event_type){let n=e.event_type||"message",s=e.data||e;s.path&&ee[s.path]&&ee[s.path].forEach(r=>r(s)),ee["*"]&&ee["*"].forEach(r=>r(s));for(let r of Dt)r.eventType!=="*"&&r.eventType!==n||r.filter&&!r.filter(s)||r.callback(s)}}catch{}}function tr(){!Da()&&Qt.size===0&&ct.size===0&&I&&(Ut=!0,bn(),I.close(),I=null,Ut=!1)}function Ai(t,e){return ee[t]||(ee[t]=[]),ee[t].push(e),ct.has(t)||(ct.set(t,{path:t,event_types:["token_stream"]}),I&&I.readyState===WebSocket.OPEN&&ke({type:"subscribe_path",path:t,event_types:["token_stream"]})),wn(),()=>{let n=ee[t];if(n){let s=n.indexOf(e);s!==-1&&n.splice(s,1),n.length===0&&(delete ee[t],ct.delete(t),ke({type:"unsubscribe_path",path:t}))}tr()}}function ce(t,e,n){let r=(Array.isArray(t)?t:[t]).map(i=>({eventType:i,callback:e,filter:n}));return Dt.push(...r),vn()&&wn(),()=>{for(let i of r){let a=Dt.indexOf(i);a!==-1&&Dt.splice(a,1)}tr()}}function us(t,e=["vfs_change","ccm_change"]){return B("subscribeToScope:",t,e),Qt.set(t,{scope_id:t,event_types:e}),I&&I.readyState===WebSocket.OPEN&&ke({type:"subscribe",scope_id:t,event_types:e}),wn(),()=>{Qt.delete(t),ke({type:"unsubscribe",scope_id:t}),tr()}}function ki(t,e,n={}){ke({type:"emit",scope_id:t,event_type:e,payload:n})}function nr(){B("disconnectSSE: tearing down"),Ut=!0,bn(),I&&(I.close(),I=null),qt&&(clearTimeout(qt),qt=null),kt=null,Ut=!1,_n=0;for(let t of Object.keys(ee))delete ee[t];Dt.length=0,Qt.clear(),ct.clear()}function qi(){ke({type:"ping"})}Pe(nr);var Nt=new Map,ls=null,Sn=new Map,Na=250;function Rn(t){ds(),Cn(t),ls=ce("vfs_change",e=>Ka(e))}function Cn(t){if(Nt.has(t))return;let e=us(t,["vfs_change","ccm_change"]);Nt.set(t,e)}function Di(t){let e=Nt.get(t);e&&(e(),Nt.delete(t))}function ds(){for(let[,t]of Nt)t();Nt.clear(),ls&&(ls(),ls=null),Sn.forEach(t=>clearTimeout(t)),Sn.clear()}Pe(ds);function Ka(t){let e=t.path,n=t.action;if(!e)return;let s=e.split("/");s.pop();let r=s.join("/")||"/root",i=Sn.get(r);i&&clearTimeout(i);let a=setTimeout(()=>{Sn.delete(r),La(n,e,t,r)},Na);Sn.set(r,a)}function La(t,e,n,s){if((t||"").toUpperCase()==="DELETE")M.removeQueries({queryKey:w.item(e)}),M.removeQueries({queryKey:w.children(e)}),M.removeQueries({queryKey:w.tree(e)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},a=pe(i);a&&a.id&&M.setQueryData(w.item(e),a)}catch{}M.invalidateQueries({queryKey:w.children(s)}),M.invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let c=a[2];return e.startsWith(c+"/")||e===c}}),n.item_id&&M.invalidateQueries({queryKey:w.itemById(n.item_id)})}var sr=$(fe(),1),Ni=$(Qi(),1);function Ki(t){return R("read",{path:t})}function Li(t,e){return R("list",{path:t,...e})}function ji(t){return R("create",t)}function Vi(t){return R("update",t)}function Hi(t){return R("create",t)}function Bi(t,e){let s=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:t,instance_path:s,...e||{}})}function Wi(t,e,n){return R("signal",{target_id:t,event_name:e,payload:n||{}})}function $i(t){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+t}var Gi={signIn:t=>t.provider?A.auth.signInWithOAuth({provider:t.provider,options:{redirectTo:t.redirectTo||window.location.href}}):A.auth.signInWithPassword({email:t.email,password:t.password}),signUp:t=>A.auth.signUp({email:t.email,password:t.password,options:{data:t.metadata||{}}}),signOut:async()=>{await A.auth.signOut(),ht(),M.clear()},getSession:()=>A.auth.getSession().then(t=>t.data.session),getUser:()=>A.auth.getUser().then(t=>t.data.user),onAuthStateChange:t=>{let{data:{subscription:e}}=A.auth.onAuthStateChange((n,s)=>{t({event:n,session:s,user:s?.user??null})});return()=>e?.unsubscribe()},resetPassword:t=>A.auth.resetPasswordForEmail(t),signInWithMagicLink:(t,e)=>A.auth.signInWithOtp({email:t,options:{emailRedirectTo:e||window.location.href}})};function zi(){let t=document.getElementById("root");if(t)try{let e=window.__FSAOS_COMPONENT__;if(!e){t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=e.default||e,s=window.__FSAOS_ITEM_DATA__||null,r=s?{item:s,...s}:{};(0,Ni.createRoot)(t).render((0,sr.createElement)(dn,{client:M},(0,sr.createElement)(n,r)))}catch(e){console.error("[FSAOS] Failed to mount root component:",e),t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(e.message||e)+"</pre></div>"}}function Ji(){let t=window.React,e=window.ReactDOM,n=window.__FSAOS_GATEWAY__,s=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let r={react:t,"react-dom":e,"react-dom/client":e,"react/jsx-runtime":{jsx:t?.createElement,jsxs:t?.createElement,Fragment:t?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":s||{}};window.require=function(a){if(r[a])return r[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=$(fe(),1),Va=$(Xi(),1),Ha=$(Wn(),1);function ja(t){return`${t}/settings/mounts`}var Pn=null;async function rr(t,e){Pn=ja(t);try{let r=((await R("read",{path:Pn}))?.item?.type_data?.mounts??[]).map(e).filter(a=>a!==null),i=Ue();return i&&!r.some(a=>a.id===i.id)&&r.unshift(i),Es(r),r}catch{let n=Ue(),s=n?[n]:[];return Es(s),s}}async function Zi(){if(!Pn)return;let t=pt().map(n=>n.id),e=Je()?.id??null;try{await R("update",{path:Pn,type_data:{mounts:t,last_anchor:e}})}catch{try{let s=Pn.split("/").slice(0,-1).join("/");await R("create",{parent_path:s,name:"mounts",item_type:"file",type_data:{mounts:t,last_anchor:e}})}catch(s){console.warn("[SDK] mount declaration persist failed:",s)}}}async function ir(t){Rr(t),await Zi()}async function eo(t){Cr(t),await Zi()}function N(){return(0,y.useSyncExternalStore)(Ye,ye,ye)}function so(){return N(),Dn()}function ro(t){return N(),k({queryKey:w.item(t),queryFn:()=>Yn(t),enabled:!!t})}function io(t){return N(),k({queryKey:w.itemById(t),queryFn:()=>Jn(t),enabled:!!t})}function ar(t){return N(),k({queryKey:w.children(t),queryFn:()=>Xn(t),enabled:!!t})}function oo(t){let e=ar(t);return{...e,children:e.data??[]}}function ao(t,e=1){return N(),k({queryKey:w.tree(t,e),queryFn:()=>ns(t,e),enabled:!!t})}function co(t,e){return N(),k({queryKey:w.search(t,e),queryFn:async()=>{let n={query:t};e?.length&&(n.item_types=e);let s=await R("search",n);return(s.content?.items||s.items||[]).map(pe)},enabled:!!t&&t.length>0})}function uo(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return k({queryKey:["vfs",ue()??"__unscoped__","resolve",JSON.stringify(e??{})],queryFn:async()=>await R("resolve",e),enabled:!!e?.query&&e.query.length>0})}function lo(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return k({queryKey:w.items(e?.type??"",e),queryFn:()=>gn(e),enabled:!!e?.type,select:n=>n.items})}function fo(t){N();let e=t?.limit??20,n=(0,y.useMemo)(()=>t,[JSON.stringify(t)]),s=pn({queryKey:["vfs",ue()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>gn({...n,limit:e,offset:i}),initialPageParam:0,getNextPageParam:(i,a,c)=>{if(!(i.items.length<e))return c+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!s.data?.pages)return[];let i=new Set,a=[];for(let c of s.data.pages)for(let u of c.items)u.id&&!i.has(u.id)&&(i.add(u.id),a.push(u));return a},[s.data?.pages]),fetchNextPage:s.fetchNextPage,isFetchingNextPage:s.isFetchingNextPage,isExhausted:!s.hasNextPage,isLoading:s.isLoading,isFetching:s.isFetching,error:s.error,totalHint:s.data?.pages?.[0]?.total_hint}}function po(t){N();let e=20,n=pn({queryKey:["vfs",ue()??"__unscoped__","infinite-children",t??""],queryFn:async({pageParam:r=0})=>Zn(t,e,r),initialPageParam:0,getNextPageParam:(r,i,a)=>{if(!(r.items.length<e))return a+r.items.length},enabled:!!t});return{allItems:(0,y.useMemo)(()=>{if(!n.data?.pages)return[];let r=new Set,i=[];for(let a of n.data.pages)for(let c of a.items)c.id&&!r.has(c.id)&&(r.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function ho(t){return N(),k({queryKey:w.edges(t),queryFn:()=>ts(t),enabled:!!t})}function fs(t){return N(),k({queryKey:w.types(t),queryFn:()=>es(t)})}function mo(t,e){let n=fs(e);return{...n,data:n.data?.get(t)??void 0}}function go(t,e){N();let n=(0,y.useMemo)(()=>e?.arguments,[JSON.stringify(e?.arguments)]),s=e?.mode,r=e?.strategy,i=e?.width;return k({queryKey:[...w.openEnvelope(t,r),i],queryFn:async()=>{let a=await os(t,{mode:s,strategy:r,arguments:n});if(i&&a.render?.props?.url){let c=a.render.props.url,u=c.includes("?")?"&":"?";a.render.props.url=`${c}${u}w=${i}`}return a},enabled:!!t})}var to={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function yo(t){let e=fs(t),n=e.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(to).map(([p,v])=>({key:p,label:v})),getEdgeTypeLabel:p=>to[p]??p.replace(/_/g," "),allTypes:n,loading:e.isLoading}),[n,e.isLoading])}function _o(t,e,n){return N(),k({queryKey:w.memberFocus(t),queryFn:()=>is(t,e,n),enabled:!!t})}function vo(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;return k({queryKey:w.itemVersions(t,String(n),String(s),String(r)),queryFn:()=>mn(t,{limit:n,offset:s,include_snapshots:r}),enabled:!!t})}function bo(t,e=50,n=0){return k({queryKey:w.itemHistory(t,String(e),String(n)),queryFn:()=>rs(t,e,n),enabled:!!t})}function wo(t,e=50,n=0){return N(),k({queryKey:w.recentActivity(t,String(e),String(n)),queryFn:()=>ss(t,e,n),enabled:!!t})}function So(){let[t,e]=(0,y.useState)(null),[n,s]=(0,y.useState)(!0),[r,i]=(0,y.useState)(null);return(0,y.useEffect)(()=>{let a=!1;return kn().then(c=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};e({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:u.componentPath||"",isEmbed:!!u.embedToken}),s(!1)}}).catch(c=>{a||(i(c instanceof Error?c:new Error(String(c))),s(!1))}),()=>{a=!0}},[]),{data:t,loading:n,error:r}}var Ba=[];function xn(t){return{id:t.accountId,path:t.path,kind:t.isSpace?"space":"account",name:t.name,grantedUnderAccountId:t.grantedUnderAccountId??void 0}}function Ro(){let{user:t}=ps(),e=(0,y.useRef)(!1),n=k({queryKey:w.memberships(t?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!t?.id,staleTime:1e3*60*2}),s=n.data??Ba,r=(0,y.useMemo)(()=>s.filter(d=>d.isAccount!==!1&&!d.isSpace),[s]),i=(0,y.useMemo)(()=>{let d=new Set(r.map(f=>f.accountId)),m=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...r].sort((f,p)=>Number(m(p))-Number(m(f)))},[r]),a=(0,y.useSyncExternalStore)(Ye,ye,ye),c=(0,y.useMemo)(()=>{let d=Je();return d?s.find(m=>m.accountId===d.id)??null:null},[a,s]);(0,y.useEffect)(()=>{if(!t?.id){e.current=!1;return}if(!e.current)if(i.length===1){let d=i[0];Jt(xn(d)),Rn(d.accountId),d.personalSpacePath&&rr(d.personalSpacePath,m=>{let f=s.find(p=>p.accountId===m);return f?xn(f):null}).catch(()=>{}),e.current=!0}else i.length>1&&(e.current=!0)},[t?.id,i,s]);let u=(0,y.useCallback)(d=>{let m=s.find(p=>p.path===d);if(!m)return;let f=xn(m);Ue()?De(f):(Jt(f),m.personalSpacePath&&rr(m.personalSpacePath,p=>{let v=s.find(h=>h.accountId===p);return v?xn(v):null}).catch(()=>{})),Rn(m.accountId)},[s]),l=(0,y.useCallback)(d=>{let m=s.find(f=>f.path===d);m&&(ir(xn(m)).catch(()=>{}),Cn(d))},[s]);return{accounts:i,allMemberships:s,currentAccount:c,mountedScope:null,switchAccount:u,mountScope:l,loading:n.isLoading,error:n.error}}function Co(){let t=(0,y.useSyncExternalStore)(An,Xt,Xt);return{mounts:(0,y.useMemo)(()=>pt(),[t]),homeAnchor:Ue(),anchor:Je(),setAnchor:De,mount:ir,unmount:eo}}function ps(){let[t,e]=(0,y.useState)(null),[n,s]=(0,y.useState)(null),[r,i]=(0,y.useState)(!0),a=(0,y.useRef)(null);(0,y.useEffect)(()=>{A.auth.getSession().then(({data:p,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),A.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(p?.session??null),e(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),A.auth.signOut().catch(()=>{}),s(null),e(null),i(!1)});let{data:{subscription:f}}=A.auth.onAuthStateChange((p,v)=>{if(p==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),A.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(v),e(v?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let c=(0,y.useCallback)(async f=>f.provider?A.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):A.auth.signInWithPassword({email:f.email,password:f.password}),[]),u=(0,y.useCallback)(async f=>A.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,y.useCallback)(async()=>{await A.auth.signOut(),ht(),M.clear()},[]),d=(0,y.useCallback)(async f=>{let{error:p}=await A.auth.resetPasswordForEmail(f);if(p)throw p},[]),m=(0,y.useCallback)(async(f,p)=>{let{error:v}=await A.auth.signInWithOtp({email:f,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:t,session:n,loading:r,signIn:c,signUp:u,signOut:l,resetPassword:d,signInWithMagicLink:m}}function Po(t){let[e,n]=(0,y.useState)(null),[s,r]=(0,y.useState)(!1),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t){n(null),r(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))r(!0),R("resolve-asset",{asset_id:t}).then(u=>{u.success&&u.public_url?n({url:u.public_url,id:u.asset_id,name:u.name,mimeType:u.mime_type,width:u.width,height:u.height,sizeBytes:u.size_bytes}):a(new Error(u.error||"Asset not found")),r(!1)}).catch(u=>{a(u instanceof Error?u:new Error(String(u))),r(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+t}),r(!1)}},[t]),{data:e,loading:s,error:i}}var En={},no={};Pe(()=>{for(let t of Object.keys(En))delete En[t]});var xo=null;function Eo(t){xo=t,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=t)}function Wa(t){switch(t){case"react":return typeof window<"u"&&window.React||y.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Va;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:Ha;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||xo||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${t}`),{}}}function $a(t,e){return t.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,s,r,i)=>`${s}.${e}${i}`)}async function Ga(t,e){if(!no[t])try{let n=await fetch(t);if(!n.ok)return;let s=await n.text();if(!s.trim()||s.includes("No CSS bundle for this component"))return;e&&!s.includes(`.fsaos-c-${e}`)&&(s=$a(s,`fsaos-c-${e}`));let r=document.createElement("style");r.setAttribute("data-fsaos-component-css",t),e&&r.setAttribute("data-fsaos-component-id",e),r.textContent=s,document.head.appendChild(r),no[t]=r}catch{}}function za(t){let e=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=s=>{e=s};try{let s=["var require = arguments[0];",t,"return window.__FSAOS_COMPONENT__;"].join(`
3
- `),i=new Function(s)(Wa),a=e??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function cr(t){let[e,n]=(0,y.useState)(null),[s,r]=(0,y.useState)(!0),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t)return;let c=!1;r(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,m=t+"@v1",f=l+t+"/__bundle.js";try{let S=await fetch(l+t+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,m=t+"@v"+d,f=l+t+"/__bundle.v"+d+".js")}catch{f=l+t+"/__bundle.js?v="+Date.now()}if(c)return;if(En[m]){n(()=>En[m]),r(!1);return}let p=await fetch(f);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${f})`);let v=await p.text();if(c)return;let h=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Ga(h).catch(()=>{});let g=za(v);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);En[m]=g,c||(n(()=>g),r(!1))}catch(d){c||(a(d instanceof Error?d:new Error(String(d))),r(!1))}})(),()=>{c=!0}},[t]),{Component:e,loading:s,error:i}}var Ja=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function To(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let e={},n=getComputedStyle(document.documentElement);return Ja.forEach(s=>{e[s]=n.getPropertyValue(s).trim()}),{tokens:e}},[]),loading:!1,error:null}}function Mo(t,e){return{data:{allowed:!0},loading:!1,error:null}}function Oo(t,e){let n={};return(e||[]).forEach(s=>{n[s]=!0}),{data:n,loading:!1,error:null}}var re=null,Kt=null,or=new Set;function Ya(){or.forEach(t=>t())}Pe(()=>{re=null,Kt=null});async function Io(t){let e=t;if(!e){let{data:s}=await A.auth.getSession();e=s?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!e)return n;if(re&&re.authUserId===e){let{principalId:s,displayName:r,createdAt:i,metadata:a,vfsPath:c}=re;return{principalId:s,displayName:r,createdAt:i,metadata:a,vfsPath:c}}return Kt||(Kt=(async()=>{try{let{data:s,error:r}=await A.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",e).eq("principal_type","user").maybeSingle();if(r)return console.warn("[SDK] Could not resolve principal:",r.message),n;let i=s?.id??null,a=null;if(i){let{data:u}=await A.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let c={principalId:i,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return re={authUserId:e,...c},c}finally{Kt=null}})(),Kt)}async function Fo(t){return(await Io(t)).principalId}function Ao(){let t=ps(),e=t.user,n=re?.authUserId===e?.id?re:null,[s,r]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let c=re;c&&c.authUserId===e?.id&&r({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return or.add(a),()=>{or.delete(a)}},[e?.id]),(0,y.useEffect)(()=>{if(!e?.id){r(null),i.current=null;return}i.current===e.id&&s?.principalId!=null||(i.current=e.id,Io(e.id).then(a=>{r(a)}))},[e?.id]),t.loading?{data:null,loading:!0,error:null}:e?{data:{id:e.id,principalId:s?.principalId??null,email:e.email,display_name:s?.displayName??void 0,created_at:s?.createdAt??void 0,vfs_path:s?.vfsPath??void 0,role:e.role||e.app_metadata?.role||"user",authenticated:!0,metadata:s?.metadata??e.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function ko(){return{data:null,loading:!1,error:null}}function qo(t){let{path:e,...n}=t,s=cr(e),r=s.Component,{loading:i,error:a}=s;return i?(0,y.createElement)("div",{className:"fsaos-loading"},""):a?(0,y.createElement)("div",{className:"fsaos-error"},"Failed to load component"):r?(0,y.createElement)(r,n):null}function Do(t){return t.children}function Uo(t){let e=N(),{channelPath:n,parentMessageId:s,realtime:r=!0,enabled:i}=t,a=i!==void 0?i&&!!n:!!n,c=(0,y.useMemo)(()=>w.channelMessages(n??"",s),[n,s,e]),u=K(),l=(0,y.useRef)(null),d=k({queryKey:c,queryFn:()=>as(n,s),enabled:a});(0,y.useEffect)(()=>{if(!r||!a)return;let h=ce("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:c})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{h(),l.current&&clearTimeout(l.current)}},[r,a,n,c,u]);let m=d.data,f=m?.messages??[],p=m?.messageCards??new Map,v=m?.siblingCards??[];return{messages:f,messageCards:p,siblingCards:v,threads:(0,y.useMemo)(()=>f.filter(h=>h.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Qo(t){N();let{channelPath:e,parentMessageId:n,limit:s=50,realtime:r=!0,enabled:i=!0}=t,a=!!n,c=i&&!!e,u=pn({queryKey:[...w.channelMessages(e||"",n),"infinite",s],queryFn:async({pageParam:h})=>yn(e,{parentMessageId:n,limit:s,before_seq:a?void 0:h,after_seq:a?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!a||h.messages.length<s?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>a||h.messages.length<s?void 0:h.messages[0]?.seq,enabled:c}),l=(0,y.useMemo)(()=>{if(!u.data?.pages)return[];let h=new Set,g=[];for(let S of u.data.pages)for(let C of S.messages)h.has(C.id)||(h.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[u.data?.pages]),{messageCards:d,siblingCards:m}=(0,y.useMemo)(()=>{let h=new Map,g=[];if(!u.data?.pages)return{messageCards:h,siblingCards:g};let S=new Set;for(let C of u.data.pages){for(let[x,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let H=h.get(x)||[];H.push(L),h.set(x,H)}for(let x of C.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:h,siblingCards:g}},[u.data?.pages]),f=K(),p=(0,y.useRef)(null),v=(0,y.useMemo)(()=>[...w.channelMessages(e||"",n),"infinite",s],[e,n,s]);return(0,y.useEffect)(()=>{if(!r||!e||!c)return;let h=ce("vfs_change",()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(async()=>{let g=f.getQueryData(v);if(!g?.pages?.length){f.invalidateQueries({queryKey:v});return}let S=0;for(let C of g.pages)for(let x of C.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:v});return}try{let C=await yn(e,{parentMessageId:n,limit:s,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let x=Math.min(...C.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:v});return}}f.setQueryData(v,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,H=U[L],ut=new Set(H.messages.map(T=>T.id)),ne=C.messages.filter(T=>!ut.has(T.id)),Q=[...H.messages,...ne].sort((T,ze)=>T.seq-ze.seq),J=new Map(H.messageCards);for(let[T,ze]of C.messageCards){let W=J.get(T)||[],Lt=new Set(W.map(ms=>ms.id)),oa=ze.filter(ms=>!Lt.has(ms.id));J.set(T,[...W,...oa])}let he=new Set(H.siblingCards.map(T=>T.id)),me=C.siblingCards.filter(T=>!he.has(T.id)),ge=[...H.siblingCards,...me];return U[L]={...H,messages:Q,messageCards:J,siblingCards:ge},{...x,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:v})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(e));return()=>{h(),p.current&&clearTimeout(p.current)}},[r,e,c,v,f,n,s]),{messages:l,messageCards:d,siblingCards:m,threads:l.filter(h=>h.reply_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasPreviousPage??!1,fetchPreviousPage:u.fetchPreviousPage,isFetchingPreviousPage:u.isFetchingPreviousPage??!1,hasNextPage:u.hasNextPage??!1,fetchNextPage:u.fetchNextPage,isFetchingNextPage:u.isFetchingNextPage??!1}}function Xa(t){return t==="on"||t==="auto"?"on":"off"}function Za(t){let e=t.type_data||{},n=t._reader||{},s=n.context_lineage||{};return{id:t.id||"",path:t.path||"",name:t.name||"",displayName:e.display_name||t.name||"",aiMode:Xa(e.ai_mode),isPrivate:e.is_private||!1,isDm:e.is_dm||!1,messageCount:e.message_count||0,updatedAt:t.updated_at||"",chatScopePath:s.context_path||"",contextId:t.scope_item_id||"",contextPath:s.context_path||"",contextType:s.context_type||"",contextName:s.context_name||"",contextDisplayName:s.context_name||"",contextPrincipalId:void 0,accountId:t.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:e.auto_pilot||!1}}function hs(t={}){let e=N(),{realtime:n=!0,enabled:s=!0}=t,r=K(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[e]),c=k({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Za),enabled:s});return(0,y.useEffect)(()=>{if(!n||!s)return;let l=ce("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},m=>m.item_type==="channel"||m.item_type==="message"),d=ce("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},m=>m.item_type==="channel"||m.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,s,a,r]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function No(t={}){let e=hs(t),n=(0,y.useMemo)(()=>e.channels.filter(s=>!s.isDm),[e.channels]);return{...e,channels:n}}function Ko(t={}){let e=hs(t),n=(0,y.useMemo)(()=>e.channels.filter(s=>s.isDm),[e.channels]);return{...e,channels:n}}function ur(t={}){let e=N(),{filter:n="all",limit:s=200,realtime:r=!0,enabled:i=!0}=t,a=K(),c=(0,y.useRef)(null),u=(0,y.useMemo)(()=>w.notifications(n,s),[n,s,e]),l=k({queryKey:u,queryFn:async()=>{let m={limit:s};return n==="unread"&&(m.filter="unread"),(await R("get-notifications",m)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!r||!i)return;let m=["vfs_change","ccm_change"].map(f=>ce(f,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},p=>p.item_type==="notification"||p.item_type==="message"));return()=>{m.forEach(f=>f()),c.current&&clearTimeout(c.current)}},[r,i,u,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Lo(t={}){let{channels:e,realtime:n=!0,enabled:s=!0}=t,{notifications:r,isLoading:i,isFetching:a,error:c,refetch:u}=ur({filter:"unread",limit:200,realtime:n,enabled:s}),l=(0,y.useMemo)(()=>{let p=new Map;for(let v of r)v.is_unread&&v.channel_id&&p.set(v.channel_id,(p.get(v.channel_id)||0)+1);return p},[r]),d=(0,y.useMemo)(()=>{let p=0;return l.forEach(v=>{p+=v}),p},[l]),{dmUnread:m,channelUnread:f}=(0,y.useMemo)(()=>{if(!e)return{dmUnread:0,channelUnread:0};let p=new Set(e.filter(g=>g.isDm).map(g=>g.id)),v=0,h=0;return l.forEach((g,S)=>{p.has(S)?v+=g:h+=g}),{dmUnread:v,channelUnread:h}},[e,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:m,channelUnread:f,isLoading:i,isFetching:a,error:c,refetch:u}}function jo(){let t=K();return Ae({mutationFn:e=>R("create",e),onSuccess:(e,n)=>{let s=n.parent_path;s&&t.invalidateQueries({queryKey:w.children(s)})}})}function Vo(){let t=K();return Ae({mutationFn:e=>R("update",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.invalidateQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function Ho(){return Ae({mutationFn:t=>R("update-principal",t),onSuccess:(t,e)=>{if(!re)return;let n=t&&typeof t=="object"&&t.metadata?t.metadata:{...re.metadata??{},...typeof e.language=="string"?{language:e.language}:{},...typeof e.timezone=="string"?{timezone:e.timezone}:{},..."avatar_file_id"in e?{avatar_file_id:e.avatar_file_id}:{}};re={...re,displayName:typeof e.display_name=="string"?e.display_name:re.displayName,metadata:n},Ya()}})}function Bo(){let t=K();return Ae({mutationFn:e=>R("delete",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.removeQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function Wo(){let t=K();return Ae({mutationFn:e=>R("move",e),onSuccess:(e,n)=>{let s=n.path,r=n.new_parent_path;if(s){t.invalidateQueries({queryKey:w.item(s)});let i=s.split("/");i.pop();let a=i.join("/");a&&t.invalidateQueries({queryKey:w.children(a)})}r&&t.invalidateQueries({queryKey:w.children(r)})}})}function $o(){let t=K();return Ae({mutationFn:e=>R("link",e),onSuccess:(e,n)=>{let s=n.source_id,r=n.target_id;s&&t.invalidateQueries({queryKey:w.edges(s)}),r&&t.invalidateQueries({queryKey:w.edges(r)})}})}function Go(t,e){let n=K(),{optimistic:s,...r}=e??{};return Ae({mutationFn:i=>R(t,i),onMutate:s?async i=>{await n.cancelQueries({queryKey:s.queryKey});let a=n.getQueryData(s.queryKey);return n.setQueryData(s.queryKey,c=>s.update(c,i)),{previous:a}}:void 0,onError:(i,a,c)=>{s&&c?.previous!==void 0&&n.setQueryData(s.queryKey,c.previous),r.onError?.(i)},onSuccess:r.onSuccess,onSettled:s?()=>{n.invalidateQueries({queryKey:s.queryKey})}:void 0})}function zo(t,e,n){let s,r,i,a=!0;if(typeof t=="string")s=t,r=e,i=n;else{r=t;let l=e;s=l.eventType,i=l.filter,a=l.enabled??!0}let c=(0,y.useRef)(r),u=(0,y.useRef)(i);(0,y.useEffect)(()=>{c.current=r,u.current=i},[r,i]),(0,y.useEffect)(()=>a?ce(s,d=>c.current(d),u.current?d=>u.current(d):void 0):void 0,[s,a])}function Jo(t){let{queryKey:e,queryFn:n,eventType:s,filter:r,enabled:i=!0,debounceMs:a=500}=t,c=K(),u=(0,y.useRef)(null),l=k({queryKey:e,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let d=ce(s,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:e})},a)},r);return()=>{d(),u.current&&clearTimeout(u.current)}},[s,i,a,c,JSON.stringify(e)]),l}function Yo(t){N();let e=(0,y.useMemo)(()=>t?typeof t=="string"?{path:t}:t:null,[typeof t=="string"?t:JSON.stringify(t)]),n=!!e&&!!(e.key||e.path||e.item_id),s=e?.key??e?.path??e?.item_id??"",r=k({queryKey:["vfs",ue()??"__unscoped__","arrangement",s],queryFn:async()=>{if(!e)return null;let d=await R("resolve-arrangement",e);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=r.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),c=i?.resolution_level??null,u=(0,y.useMemo)(()=>{let m=(i?.type_data??null)?.order;return Array.isArray(m)?m:null},[i]),l=(0,y.useCallback)(d=>{if(!u||!d?.length)return d??[];let m=h=>h.id??h.name??"",f=new Map(u.map((h,g)=>[h,g])),p=[],v=[];for(let h of d)(f.has(m(h))?p:v).push(h);return p.sort((h,g)=>f.get(m(h))-f.get(m(g))),[...p,...v]},[u]);return{...r,arrangement:i,resolvedChildren:a,resolutionLevel:c,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function ec(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function tc(t,e){return e&&e.length>0?"select":t==="boolean"?"toggle":t==="integer"||t==="number"?"range":t==="string"?"text":"none"}function nc(t,e){return!(t==="object"||t==="array")}function sc(t){return["string","number","integer","boolean"].includes(t)}function rc(t){return t!=="object"&&t!=="array"}function Xo(t,e,n,s){let r=t?.properties;if(!r||typeof r!="object")return[];let i=[];for(let[a,c]of Object.entries(r)){let u=c.type||"string",l=c.enum,d=nc(u,l),m=sc(u),f=tc(u,l);i.push({key:a,label:c.title||ec(a),type:u,description:c.description,enum_values:l,default_value:n[a]??s[a]??c.default,editable:e,filterable:d,sortable:m,filter_widget:f})}return i}function lr(t){let e=t.default_data||{},n=t.field_defaults||{},s=Xo(t.input_schema,!0,e,n),r=Xo(t.system_schema,!1,e,n),i=[...s,...r],a=i.filter(l=>rc(l.type)),c=i.filter(l=>l.filterable),u=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:c,sortable:u,form_fields:s,system_fields:r}}function Zo(t){return{field:"updated_at",direction:"desc"}}function ea(t){let e=lr(t),n=new Set(t.input_schema?.required||[]);return e.form_fields.filter(s=>n.has(s.key)||s.default_value===void 0)}var te=$(fe(),1);var ic=0;function oc(){return`upload_${Date.now()}_${++ic}`}async function ta(t,e,n,s){let r=e.name||(t instanceof File?t.name:`file-${Date.now()}`),i=t.type||"application/octet-stream",a=e.itemType||"file",u=await R("create",{parent_path:e.parentPath,item_type:a,name:r,type_data:{...e.typeData||{},file_source:{type:"upload",content_type:i}}});if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let l=u.id,d=u.path;if(u.storage_completed&&u.file_ref)return{itemId:l,itemPath:d,fileRef:u.file_ref};let m=u.storage_key,f=u.upload_token,p=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await ac(p,m,f,t,i,n,s);let v=await na(l,m,i);return{itemId:l,itemPath:d,fileRef:v}}function ac(t,e,n,s,r,i,a){return new Promise((c,u)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${t}/upload`),l.setRequestHeader("X-Storage-Key",e),l.setRequestHeader("Content-Type",r),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():u(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>u(new Error("Storage upload network error")),l.ontimeout=()=>u(new Error("Storage upload timed out")),a){if(a.aborted){u(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),u(new Error("Upload cancelled"))})}l.send(s)})}async function na(t,e,n){let s=await Ce(),r=await fetch(`${qe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({item_id:t,storage_key:e,content_type:n})});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${r.status} \u2014 ${a.slice(0,300)}`)}let i=await r.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function sa(){let[t,e]=(0,te.useState)([]),n=K(),s=(0,te.useRef)(t);s.current=t;let r=(0,te.useCallback)((h,g)=>{e(S=>S.map(C=>C.id===h?{...C,...g}:C))},[]),i=(0,te.useCallback)(h=>{e(g=>[...g,h])},[]),a=(0,te.useCallback)(async(h,g,S,C,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",H=S.itemType||"file",ut=x?.itemId||null,ne=x?.itemPath||null,Q=x?.storageKey||null,J=x?.uploadToken||null,he=x?.storageWorkerUrl||null;try{if(!C||C==="create"){r(h,{status:"creating",error:null,_failedAt:null});let T=await R("create",{parent_path:S.parentPath,item_type:H,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!T.id)throw Object.assign(new Error(T.error||T.message||"Failed to create file item"),{_step:"create"});if(ut=T.id,ne=T.path,r(h,{itemId:ut,itemPath:ne}),T.storage_completed&&T.file_ref){r(h,{status:"complete",progress:100,fileRef:T.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=T.storage_key,J=T.upload_token||"",he=T.storage_worker_url||"https://fsaos-storage.radns.workers.dev",r(h,{_storageKey:Q,_uploadToken:J,_storageWorkerUrl:he}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(r(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((T,ze)=>{let W=new XMLHttpRequest;r(h,{_xhr:W}),W.open("PUT",`${he}/upload`),W.setRequestHeader("X-Storage-Key",Q),W.setRequestHeader("Content-Type",L),J&&W.setRequestHeader("X-Upload-Token",J),W.upload.onprogress=Lt=>{Lt.lengthComputable&&r(h,{progress:Math.round(Lt.loaded/Lt.total*100)})},W.onload=()=>{W.status>=200&&W.status<300?T():ze(Object.assign(new Error(`Storage upload failed: HTTP ${W.status}`),{_step:"upload"}))},W.onerror=()=>ze(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),W.ontimeout=()=>ze(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),W.send(g)}),r(h,{progress:100,_xhr:null})),r(h,{status:"confirming",error:null,_failedAt:null});let me=await na(ut,Q,L);r(h,{status:"complete",fileRef:me}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(me){let ge=me?.message||String(me),T=me?._step||"create";r(h,{status:"error",error:ge,_failedAt:T,_xhr:null})}},[r,n]),c=(0,te.useCallback)((h,g)=>{let S=oc();i({id:S,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,h,g)},[i,a]),u=(0,te.useCallback)((h,g)=>{for(let S of h)c(S,g)},[c]),l=(0,te.useCallback)(h=>{let g=s.current.find(x=>x.id===h);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(h,g.file,g.options,S,C)},[a]),d=(0,te.useCallback)(h=>{let g=s.current.find(S=>S.id===h);g&&(g._xhr&&g._xhr.abort(),r(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[r]),m=(0,te.useCallback)(h=>{e(g=>g.filter(S=>S.id!==h))},[]),f=(0,te.useCallback)(()=>{e(h=>h.filter(g=>g.status!=="complete"))},[]),p=t.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),v=t.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:x,...U})=>U);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:d,removeUpload:m,clearCompleted:f,isUploading:p}}var ra=$(fe(),1);async function dr(t,e){return await R("resolve-items",{context_id:t,item_type:e})}function ia(t,e){return(0,ra.useSyncExternalStore)(Ye,ye,ye),k({queryKey:["vfs",ue()??"__unscoped__","resolved-items",t??"",e],queryFn:()=>dr(t,e),enabled:!!(t&&e)})}Eo(fr);return ha(fr);})();
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-03T02:19:52.884Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var da=Object.create;var Vt=Object.defineProperty;var fa=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames;var ha=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var gs=t=>{throw TypeError(t)};var ga=(t,e,n)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Ht=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ya=(t,e)=>{for(var n in e)Vt(t,n,{get:e[n],enumerable:!0})},ys=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pa(e))!ma.call(t,s)&&s!==n&&Vt(t,s,{get:()=>e[s],enumerable:!(r=fa(e,s))||r.enumerable});return t};var B=(t,e,n)=>(n=t!=null?da(ha(t)):{},ys(e||!t||!t.__esModule?Vt(n,"default",{value:t,enumerable:!0}):n,t)),_a=t=>ys(Vt({},"__esModule",{value:!0}),t);var Bt=(t,e,n)=>ga(t,typeof e!="symbol"?e+"":e,n),vr=(t,e,n)=>e.has(t)||gs("Cannot "+n);var o=(t,e,n)=>(vr(t,e,"read from private field"),n?n.call(t):e.get(t)),b=(t,e,n)=>e.has(t)?gs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),_=(t,e,n,r)=>(vr(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),P=(t,e,n)=>(vr(t,e,"access private method"),n);var Wt=(t,e,n,r)=>({set _(s){_(t,e,s,n)},get _(){return o(t,e,r)}});var vs=Ht((mc,_s)=>{_s.exports={createClient:window.supabase.createClient}});var ce=Ht((vl,li)=>{li.exports=React});var $n=Ht((bl,di)=>{di.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Ki=Ht((hd,Ni)=>{Ni.exports=ReactDOM});var eo=Ht((wd,Zi)=>{Zi.exports=ReactDOM});var ms={};ya(ms,{ComponentRenderer:()=>Uo,EnforcementDeniedError:()=>dt,KernelProvider:()=>Qo,QueryClientProvider:()=>fn,auth:()=>Ji,awaitAnchorReady:()=>Jt,awaitScopeReady:()=>Ms,callTool:()=>$i,clearCachedToken:()=>Cr,clearSession:()=>Or,createItem:()=>Hi,disconnectSSE:()=>is,disposeVfsRealtimeWs:()=>pr,electHomeAnchor:()=>Yt,emitEvent:()=>Di,fetchChannelMessages:()=>xi,fetchChannelMessagesPage:()=>_n,fetchChannelMessagesWithCards:()=>cr,fetchEdgesForItem:()=>nr,fetchItemHistory:()=>ir,fetchItemVersions:()=>gn,fetchItems:()=>yn,fetchMemberFocus:()=>or,fetchOpenEnvelope:()=>ar,fetchRecentActivity:()=>sr,fetchResolvedItems:()=>hs,fetchTypeDefinitions:()=>tr,fetchVfsChildren:()=>Zn,fetchVfsChildrenPage:()=>er,fetchVfsItem:()=>Xn,fetchVfsItemById:()=>Yn,fetchVfsTree:()=>rr,gatewayCall:()=>R,getAccessToken:()=>Pe,getAnchor:()=>zt,getAnchorRef:()=>Ye,getAnchorVersion:()=>Er,getAssetUrl:()=>zi,getDefaultSort:()=>ta,getHomeAnchor:()=>Qe,getMountVersion:()=>Zt,getMounts:()=>ht,getRequiredFormFields:()=>na,getScope:()=>le,getScopeVersion:()=>_e,getSessionEntry:()=>Dn,initSession:()=>qn,initVfsRealtimeWs:()=>Cn,interpretSchema:()=>ps,invalidateAllVfs:()=>Ai,invalidateChannelMessages:()=>Oi,invalidateChildren:()=>Jn,invalidateItem:()=>rs,invalidateOpenEnvelope:()=>Ii,invalidatePathAndParent:()=>Ei,invalidateSubtree:()=>Ti,invalidateTypes:()=>Mi,isAnchorReady:()=>Ar,isScopeReady:()=>Un,listChildren:()=>Vi,mount:()=>Yi,mountRealtimeScope:()=>Pn,normalizeItem:()=>pe,ping:()=>Ui,pushChanges:()=>Wi,queryClient:()=>A,readItem:()=>ji,registerCleanup:()=>xe,resetAllSdkState:()=>mt,resolvePrincipalId:()=>ko,setAnchor:()=>Ue,setCachedToken:()=>Ss,setScope:()=>As,setupRequireShim:()=>Xi,signal:()=>Gi,subscribeAnchor:()=>Tr,subscribeArtifactStream:()=>yr,subscribeMounts:()=>kn,subscribeScope:()=>Xe,subscribeToEvents:()=>ue,subscribeToPath:()=>lr,subscribeToScope:()=>dr,unmountRealtimeScope:()=>Qi,updateItem:()=>Bi,uploadFile:()=>ra,useAccounts:()=>Po,useAgentTimeline:()=>ua,useAllChannels:()=>gr,useArrangement:()=>Zo,useArtifactStream:()=>ca,useAsset:()=>Eo,useAuth:()=>mr,useChannelMessages:()=>No,useChannels:()=>Lo,useChildren:()=>co,useComponent:()=>ds,useCreate:()=>Ho,useDelete:()=>$o,useDmChannels:()=>jo,useEdges:()=>go,useEventStream:()=>Yo,useFileUpload:()=>ia,useInfiniteChannelMessages:()=>Ko,useInfiniteChildren:()=>mo,useInfiniteItems:()=>ho,useItem:()=>oo,useItemById:()=>ao,useItemHistory:()=>So,useItemVersions:()=>wo,useItems:()=>po,useLink:()=>zo,useList:()=>ls,useMemberFocus:()=>bo,useMounts:()=>xo,useMove:()=>Go,useMutation:()=>Jo,useNotifications:()=>fs,useOpen:()=>_o,usePermission:()=>Oo,usePermissions:()=>Io,usePrincipal:()=>qo,useRealtimeQuery:()=>Xo,useRecentActivity:()=>Ro,useResolve:()=>fo,useResolvedItems:()=>aa,useScope:()=>Co,useScopeReady:()=>io,useSearch:()=>lo,useTheme:()=>Mo,useTool:()=>Do,useTree:()=>uo,useType:()=>yo,useTypeHelpers:()=>vo,useTypes:()=>hr,useUnreadCounts:()=>Vo,useUpdate:()=>Bo,useUpdatePrincipal:()=>Wo,vfsKeys:()=>w});var dt=class t extends Error{constructor(n){let r=n.message||t.fallbackMessage(n);super(r);Bt(this,"name","EnforcementDeniedError");Bt(this,"deniedBy");Bt(this,"ruleKey");Bt(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var bs=B(vs(),1),br=typeof window<"u"&&window.__FSAOS_CONFIG__||{},va=br.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",ba=br.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",De=br.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",F=(0,bs.createClient)(va,ba,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Gt=null,An=0,ws,Rr,Mn=!1;ws=new Promise(t=>{Rr=t});F.auth.onAuthStateChange((t,e)=>{e?.access_token?(Gt=e.access_token,An=e.expires_at??Math.floor(Date.now()/1e3)+3600):(Gt=null,An=0),Mn||(Mn=!0,Rr())});setTimeout(()=>{Mn||(Mn=!0,Rr())},5e3);function Ss(t,e){Gt=t,An=e??Math.floor(Date.now()/1e3)+3600}function Cr(){Gt=null,An=0}async function Pe(){let t=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(t.embedToken){if(typeof t.embedToken=="function")try{return await t.embedToken()??null}catch{return null}return t.embedToken}return await ws,Gt}var On=null,Fn=null,Rs=0,wr=new Set,Pr,xr,In=!1;Pr=new Promise(t=>{xr=t});function Cs(){Rs++,wr.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Anchor listener error:",e)}})}function Ue(t){let e=typeof t=="string"?t:t.path,n=On!==e;On=e,Fn=typeof t=="string"?null:t,typeof t!="string"&&!ie.some(r=>r.id===t.id)&&(ie=[...ie,t],Xt()),In||(In=!0,xr()),n&&Cs()}function zt(){return On}function Ye(){return Fn}function Er(){return Rs}function Tr(t){return wr.add(t),()=>{wr.delete(t)}}function Jt(){return Pr}function Ar(){return In}var pt=null;function Yt(t){if(pt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}pt=t,Ue(t)}function Qe(){return pt}var ie=[],Sr=new Set,Ps=0;function Xt(){Ps++,Sr.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Mount listener error:",e)}})}function ht(){return ie}function Zt(){return Ps}function kn(t){return Sr.add(t),()=>{Sr.delete(t)}}function Mr(t){ie=t,Xt()}function xs(t){ie.some(e=>e.id===t.id)||(ie=[...ie,t],Xt())}function Es(t){ie.find(n=>n.id===t)&&(ie=ie.filter(n=>n.id!==t),Xt(),Fn?.id===t&&pt&&Ue(pt))}var ft=null,$t=null;async function qn(){return ft||$t||($t=(async()=>{let t=Ir(),e=await Pe(),n={};e&&(n.Authorization=`Bearer ${e}`);let r=await fetch(`${De}/d/${t}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return ft={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},ft})(),$t)}function Dn(){return ft}function Or(){ft=null,$t=null,On=null,Fn=null,pt=null,ie=[]}var Ts=[];function xe(t){Ts.push(t)}function mt(){Or(),Cr(),In=!1,Pr=new Promise(t=>{xr=t}),Cs(),Xt();for(let t of Ts)try{t()}catch(e){console.warn("[SDK] Cleanup function failed:",e)}}function Ir(){if(typeof window<"u"){let t=window.__FSAOS_CONFIG__;return t?.hostname?t.hostname:window.location.hostname}return"localhost"}var As=Ue,le=zt,_e=Er,Xe=Tr,Ms=Jt,Un=Ar;var wa=new Set(["list-memberships","init"]);async function R(t,e={}){let n=Ir(),r=`${De}/d/${n}`,s={"Content-Type":"application/json"},i=await Pe();i&&(s.Authorization=`Bearer ${i}`),!wa.has(t)&&!e._scope_path&&await Jt();let a={...e},u=Dn();!a.domain_scope_id&&u?.scope_id&&(a.domain_scope_id=u.scope_id);let c=zt();!a._scope_path&&c&&(a._scope_path=c);let d=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:t,params:a})});if(!d.ok)throw new Error(`Gateway HTTP error: ${d.status} ${d.statusText}`);let l=await d.json();if(l.success===!1){let p=l.error||"",f=l.denied_by||l.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||p==="RULE_DENIED"||p==="ACCESS_DENIED"||p==="PERMISSION_DENIED"||p==="ENTITLEMENT_REQUIRED"?new dt(l):new Error(l.message||l.error||`Gateway call ${t} failed`)}return l}var oe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Ze,Ne,gt,Os,Sa=(Os=class extends oe{constructor(){super();b(this,Ze);b(this,Ne);b(this,gt);_(this,gt,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Ne)||this.setEventListener(o(this,gt))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Ne))==null||e.call(this),_(this,Ne,void 0))}setEventListener(e){var n;_(this,gt,e),(n=o(this,Ne))==null||n.call(this),_(this,Ne,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){o(this,Ze)!==e&&(_(this,Ze,e),this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){return typeof o(this,Ze)=="boolean"?o(this,Ze):globalThis.document?.visibilityState!=="hidden"}},Ze=new WeakMap,Ne=new WeakMap,gt=new WeakMap,Os),yt=new Sa;var Ra={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Ke,Fr,Is,Ca=(Is=class{constructor(){b(this,Ke,Ra);b(this,Fr,!1)}setTimeoutProvider(t){_(this,Ke,t)}setTimeout(t,e){return o(this,Ke).setTimeout(t,e)}clearTimeout(t){o(this,Ke).clearTimeout(t)}setInterval(t,e){return o(this,Ke).setInterval(t,e)}clearInterval(t){o(this,Ke).clearInterval(t)}},Ke=new WeakMap,Fr=new WeakMap,Is),ve=new Ca;function Fs(t){setTimeout(t,0)}var qr=typeof window>"u"||"Deno"in globalThis;function q(){}function Ds(t,e){return typeof t=="function"?t(e):t}function en(t){return typeof t=="number"&&t>=0&&t!==1/0}function Qn(t,e){return Math.max(t+(e||0)-Date.now(),0)}function de(t,e){return typeof t=="function"?t(e):t}function Y(t,e){return typeof t=="function"?t(e):t}function Nn(t,e){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:u}=t;if(a){if(r){if(e.queryHash!==tn(a,e.options))return!1}else if(!et(e.queryKey,a))return!1}if(n!=="all"){let c=e.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof u=="boolean"&&e.isStale()!==u||s&&s!==e.state.fetchStatus||i&&!i(e))}function Kn(t,e){let{exact:n,status:r,predicate:s,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(be(e.options.mutationKey)!==be(i))return!1}else if(!et(e.options.mutationKey,i))return!1}return!(r&&e.state.status!==r||s&&!s(e))}function tn(t,e){return(e?.queryKeyHashFn||be)(t)}function be(t){return JSON.stringify(t,(e,n)=>kr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function et(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>et(t[n],e[n])):!1}var Pa=Object.prototype.hasOwnProperty;function Dr(t,e,n=0){if(t===e)return t;if(n>500)return e;let r=ks(t)&&ks(e);if(!r&&!(kr(t)&&kr(e)))return e;let i=(r?t:Object.keys(t)).length,a=r?e:Object.keys(e),u=a.length,c=r?new Array(u):{},d=0;for(let l=0;l<u;l++){let p=r?l:a[l],f=t[p],h=e[p];if(f===h){c[p]=f,(r?l<i:Pa.call(t,p))&&d++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){c[p]=h;continue}let v=Dr(f,h,n+1);c[p]=v,v===f&&d++}return i===u&&d===i?t:c}function _t(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let n in t)if(t[n]!==e[n])return!1;return!0}function ks(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function kr(t){if(!qs(t))return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(!qs(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function qs(t){return Object.prototype.toString.call(t)==="[object Object]"}function Us(t){return new Promise(e=>{ve.setTimeout(e,t)})}function nn(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?Dr(t,e):e}function Qs(t,e,n=0){let r=[...t,e];return n&&r.length>n?r.slice(1):r}function Ns(t,e,n=0){let r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var vt=Symbol();function Ln(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===vt?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function bt(t,e){return typeof t=="function"?t(...e):!!t}function Ks(t,e,n){let r=!1,s;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(s??(s=e()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),t}var we=(()=>{let t=()=>qr;return{isServer(){return t()},setIsServer(e){t=e}}})();function rn(){let t,e,n=new Promise((s,i)=>{t=s,e=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),t(s)},n.reject=s=>{r({status:"rejected",reason:s}),e(s)},n}var Ls=Fs;function xa(){let t=[],e=0,n=u=>{u()},r=u=>{u()},s=Ls,i=u=>{e?t.push(u):s(()=>{n(u)})},a=()=>{let u=t;t=[],u.length&&s(()=>{r(()=>{u.forEach(c=>{n(c)})})})};return{batch:u=>{let c;e++;try{c=u()}finally{e--,e||a()}return c},batchCalls:u=>(...c)=>{i(()=>{u(...c)})},schedule:i,setNotifyFunction:u=>{n=u},setBatchNotifyFunction:u=>{r=u},setScheduler:u=>{s=u}}}var I=xa();var wt,Le,St,js,Ea=(js=class extends oe{constructor(){super();b(this,wt,!0);b(this,Le);b(this,St);_(this,St,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){o(this,Le)||this.setEventListener(o(this,St))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Le))==null||e.call(this),_(this,Le,void 0))}setEventListener(e){var n;_(this,St,e),(n=o(this,Le))==null||n.call(this),_(this,Le,e(this.setOnline.bind(this)))}setOnline(e){o(this,wt)!==e&&(_(this,wt,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return o(this,wt)}},wt=new WeakMap,Le=new WeakMap,St=new WeakMap,js),Rt=new Ea;function Ta(t){return Math.min(1e3*2**t,3e4)}function Ur(t){return(t??"online")==="online"?Rt.isOnline():!0}var jn=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Vn(t){let e=!1,n=0,r,s=rn(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new jn(m);f(g),t.onCancel?.(g)}},u=()=>{e=!0},c=()=>{e=!1},d=()=>yt.isFocused()&&(t.networkMode==="always"||Rt.isOnline())&&t.canRun(),l=()=>Ur(t.networkMode)&&t.canRun(),p=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},h=()=>new Promise(m=>{r=g=>{(i()||d())&&m(g)},t.onPause?.()}).then(()=>{r=void 0,i()||t.onContinue?.()}),v=()=>{if(i())return;let m,g=n===0?t.initialPromise:void 0;try{m=g??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(p).catch(S=>{if(i())return;let C=t.retry??(we.isServer()?0:3),x=t.retryDelay??Ta,U=typeof x=="function"?x(n,S):x,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(e||!L){f(S);return}n++,t.onFail?.(n,S),Us(U).then(()=>d()?void 0:h()).then(()=>{e?f(S):v()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:c,canStart:l,start:()=>(l()?v():h().then(v),s)}}var tt,Vs,Hn=(Vs=class{constructor(){b(this,tt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),en(this.gcTime)&&_(this,tt,ve.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(we.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,tt)!==void 0&&(ve.clearTimeout(o(this,tt)),_(this,tt,void 0))}},tt=new WeakMap,Vs);var nt,Ct,ae,rt,j,sn,st,re,Gs,Ee,Ws,$s=(Ws=class extends Hn{constructor(e){super();b(this,re);b(this,nt);b(this,Ct);b(this,ae);b(this,rt);b(this,j);b(this,sn);b(this,st);_(this,st,!1),_(this,sn,e.defaultOptions),this.setOptions(e.options),this.observers=[],_(this,rt,e.client),_(this,ae,o(this,rt).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_(this,nt,Bs(this.options)),this.state=e.state??o(this,nt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,j)?.promise}setOptions(e){if(this.options={...o(this,sn),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Bs(this.options);n.data!==void 0&&(this.setState(Hs(n.data,n.dataUpdatedAt)),_(this,nt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,ae).remove(this)}setData(e,n){let r=nn(this.state.data,e,this.options);return P(this,re,Ee).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(e,n){P(this,re,Ee).call(this,{type:"setState",state:e,setStateOptions:n})}cancel(e){let n=o(this,j)?.promise;return o(this,j)?.cancel(e),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,nt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>de(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Qn(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),o(this,ae).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(o(this,j)&&(o(this,st)||P(this,re,Gs).call(this)?o(this,j).cancel({revert:!0}):o(this,j).cancelRetry()),this.scheduleGc()),o(this,ae).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,re,Ee).call(this,{type:"invalidate"})}async fetch(e,n){if(this.state.fetchStatus!=="idle"&&o(this,j)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,j))return o(this,j).continueRetry(),o(this,j).promise}if(e&&this.setOptions(e),!this.options.queryFn){let c=this.observers.find(d=>d.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(_(this,st,!0),r.signal)})},i=()=>{let c=Ln(this.options,n),l=(()=>{let p={client:o(this,rt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return _(this,st,!1),this.options.persister?this.options.persister(c,l,this):c(l)},u=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,rt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(u,this),_(this,Ct,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&P(this,re,Ee).call(this,{type:"fetch",meta:u.fetchOptions?.meta}),_(this,j,Vn({initialPromise:n?.initialPromise,fn:u.fetchFn,onCancel:c=>{c instanceof jn&&c.revert&&this.setState({...o(this,Ct),fetchStatus:"idle"}),r.abort()},onFail:(c,d)=>{P(this,re,Ee).call(this,{type:"failed",failureCount:c,error:d})},onPause:()=>{P(this,re,Ee).call(this,{type:"pause"})},onContinue:()=>{P(this,re,Ee).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{let c=await o(this,j).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),o(this,ae).config.onSuccess?.(c,this),o(this,ae).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof jn){if(c.silent)return o(this,j).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw P(this,re,Ee).call(this,{type:"error",error:c}),o(this,ae).config.onError?.(c,this),o(this,ae).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},nt=new WeakMap,Ct=new WeakMap,ae=new WeakMap,rt=new WeakMap,j=new WeakMap,sn=new WeakMap,st=new WeakMap,re=new WeakSet,Gs=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ee=function(e){let n=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Qr(r.data,this.options),fetchMeta:e.meta??null};case"success":let s={...r,...Hs(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return _(this,Ct,e.manual?s:void 0),s;case"error":let i=e.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=n(this.state),I.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),o(this,ae).notify({query:this,type:"updated",action:e})})},Ws);function Qr(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ur(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Hs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Bs(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var X,E,an,z,it,Pt,Te,je,cn,xt,Et,ot,at,Ve,Tt,M,on,Nr,Kr,Lr,jr,Vr,Hr,Br,Xs,Ys,un=(Ys=class extends oe{constructor(e,n){super();b(this,M);b(this,X);b(this,E);b(this,an);b(this,z);b(this,it);b(this,Pt);b(this,Te);b(this,je);b(this,cn);b(this,xt);b(this,Et);b(this,ot);b(this,at);b(this,Ve);b(this,Tt,new Set);this.options=n,_(this,X,e),_(this,je,null),_(this,Te,rn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,E).addObserver(this),zs(o(this,E),this.options)?P(this,M,on).call(this):this.updateResult(),P(this,M,jr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wr(o(this,E),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wr(o(this,E),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,M,Vr).call(this),P(this,M,Hr).call(this),o(this,E).removeObserver(this)}setOptions(e){let n=this.options,r=o(this,E);if(this.options=o(this,X).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Y(this.options.enabled,o(this,E))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,M,Br).call(this),o(this,E).setOptions(this.options),n._defaulted&&!_t(this.options,n)&&o(this,X).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,E),observer:this});let s=this.hasListeners();s&&Js(o(this,E),r,this.options,n)&&P(this,M,on).call(this),this.updateResult(),s&&(o(this,E)!==r||Y(this.options.enabled,o(this,E))!==Y(n.enabled,o(this,E))||de(this.options.staleTime,o(this,E))!==de(n.staleTime,o(this,E)))&&P(this,M,Nr).call(this);let i=P(this,M,Kr).call(this);s&&(o(this,E)!==r||Y(this.options.enabled,o(this,E))!==Y(n.enabled,o(this,E))||i!==o(this,Ve))&&P(this,M,Lr).call(this,i)}getOptimisticResult(e){let n=o(this,X).getQueryCache().build(o(this,X),e),r=this.createResult(n,e);return Ma(this,r)&&(_(this,z,r),_(this,Pt,this.options),_(this,it,o(this,E).state)),r}getCurrentResult(){return o(this,z)}trackResult(e,n){return new Proxy(e,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Te).status==="pending"&&o(this,Te).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(e){o(this,Tt).add(e)}getCurrentQuery(){return o(this,E)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let n=o(this,X).defaultQueryOptions(e),r=o(this,X).getQueryCache().build(o(this,X),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(e){return P(this,M,on).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(e,n){let r=o(this,E),s=this.options,i=o(this,z),a=o(this,it),u=o(this,Pt),d=e!==r?e.state:o(this,an),{state:l}=e,p={...l},f=!1,h;if(n._optimisticResults){let Q=this.hasListeners(),J=!Q&&zs(e,n),me=Q&&Js(e,r,n,s);(J||me)&&(p={...p,...Qr(l.data,e.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:v,errorUpdatedAt:m,status:g}=p;h=p.data;let S=!1;if(n.placeholderData!==void 0&&h===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===u?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(o(this,Et)?.state.data,o(this,Et)):n.placeholderData,Q!==void 0&&(g="success",h=nn(i?.data,Q,n),f=!0)}if(n.select&&h!==void 0&&!S)if(i&&h===a?.data&&n.select===o(this,cn))h=o(this,xt);else try{_(this,cn,n.select),h=n.select(h),h=nn(i?.data,h,n),_(this,xt,h),_(this,je,null)}catch(Q){_(this,je,Q)}o(this,je)&&(v=o(this,je),h=o(this,xt),m=Date.now(),g="error");let C=p.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&C,H=h!==void 0,ne={status:g,fetchStatus:p.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:h,dataUpdatedAt:p.dataUpdatedAt,error:v,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:p.dataUpdateCount>d.dataUpdateCount||p.errorUpdateCount>d.errorUpdateCount,isFetching:C,isRefetching:C&&!x,isLoadingError:U&&!H,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&H,isStale:$r(e,n),refetch:this.refetch,promise:o(this,Te),isEnabled:Y(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let Q=ne.data!==void 0,J=ne.status==="error"&&!Q,me=T=>{J?T.reject(ne.error):Q&&T.resolve(ne.data)},ge=()=>{let T=_(this,Te,ne.promise=rn());me(T)},ye=o(this,Te);switch(ye.status){case"pending":e.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(J||ne.data!==ye.value)&&ge();break;case"rejected":(!J||ne.error!==ye.reason)&&ge();break}}return ne}updateResult(){let e=o(this,z),n=this.createResult(o(this,E),this.options);if(_(this,it,o(this,E).state),_(this,Pt,this.options),o(this,it).data!==void 0&&_(this,Et,o(this,E)),_t(n,e))return;_(this,z,n);let r=()=>{if(!e)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!o(this,Tt).size)return!0;let a=new Set(i??o(this,Tt));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(u=>{let c=u;return o(this,z)[c]!==e[c]&&a.has(c)})};P(this,M,Xs).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,M,jr).call(this)}},X=new WeakMap,E=new WeakMap,an=new WeakMap,z=new WeakMap,it=new WeakMap,Pt=new WeakMap,Te=new WeakMap,je=new WeakMap,cn=new WeakMap,xt=new WeakMap,Et=new WeakMap,ot=new WeakMap,at=new WeakMap,Ve=new WeakMap,Tt=new WeakMap,M=new WeakSet,on=function(e){P(this,M,Br).call(this);let n=o(this,E).fetch(this.options,e);return e?.throwOnError||(n=n.catch(q)),n},Nr=function(){P(this,M,Vr).call(this);let e=de(this.options.staleTime,o(this,E));if(we.isServer()||o(this,z).isStale||!en(e))return;let r=Qn(o(this,z).dataUpdatedAt,e)+1;_(this,ot,ve.setTimeout(()=>{o(this,z).isStale||this.updateResult()},r))},Kr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,E)):this.options.refetchInterval)??!1},Lr=function(e){P(this,M,Hr).call(this),_(this,Ve,e),!(we.isServer()||Y(this.options.enabled,o(this,E))===!1||!en(o(this,Ve))||o(this,Ve)===0)&&_(this,at,ve.setInterval(()=>{(this.options.refetchIntervalInBackground||yt.isFocused())&&P(this,M,on).call(this)},o(this,Ve)))},jr=function(){P(this,M,Nr).call(this),P(this,M,Lr).call(this,P(this,M,Kr).call(this))},Vr=function(){o(this,ot)!==void 0&&(ve.clearTimeout(o(this,ot)),_(this,ot,void 0))},Hr=function(){o(this,at)!==void 0&&(ve.clearInterval(o(this,at)),_(this,at,void 0))},Br=function(){let e=o(this,X).getQueryCache().build(o(this,X),this.options);if(e===o(this,E))return;let n=o(this,E);_(this,E,e),_(this,an,e.state),this.hasListeners()&&(n?.removeObserver(this),e.addObserver(this))},Xs=function(e){I.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,X).getQueryCache().notify({query:o(this,E),type:"observerResultsUpdated"})})},Ys);function Aa(t,e){return Y(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function zs(t,e){return Aa(t,e)||t.state.data!==void 0&&Wr(t,e,e.refetchOnMount)}function Wr(t,e,n){if(Y(e.enabled,t)!==!1&&de(e.staleTime,t)!=="static"){let r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&$r(t,e)}return!1}function Js(t,e,n,r){return(t!==e||Y(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&$r(t,n)}function $r(t,e){return Y(e.enabled,t)!==!1&&t.isStaleByTime(de(e.staleTime,t))}function Ma(t,e){return!_t(t.getCurrentResult(),e)}function At(t){return{onFetch:(e,n)=>{let r=e.options,s=e.fetchOptions?.meta?.fetchMore?.direction,i=e.state.data?.pages||[],a=e.state.data?.pageParams||[],u={pages:[],pageParams:[]},c=0,d=async()=>{let l=!1,p=v=>{Ks(v,()=>e.signal,()=>l=!0)},f=Ln(e.options,e.fetchOptions),h=async(v,m,g)=>{if(l)return Promise.reject();if(m==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let H={client:e.client,queryKey:e.queryKey,pageParam:m,direction:g?"backward":"forward",meta:e.options.meta};return p(H),H})(),x=await f(C),{maxPages:U}=e.options,L=g?Ns:Qs;return{pages:L(v.pages,x,U),pageParams:L(v.pageParams,m,U)}};if(s&&i.length){let v=s==="backward",m=v?Zs:Gr,g={pages:i,pageParams:a},S=m(r,g);u=await h(g,S,v)}else{let v=t??i.length;do{let m=c===0?a[0]??r.initialPageParam:Gr(r,u);if(c>0&&m==null)break;u=await h(u,m),c++}while(c<v)}return u};e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=d}}}function Gr(t,{pages:e,pageParams:n}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function Zs(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}function ei(t,e){return e?Gr(t,e)!=null:!1}function ti(t,e){return!e||!t.getPreviousPageParam?!1:Zs(t,e)!=null}var zr=class extends un{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t){super.setOptions({...t,behavior:At()})}getOptimisticResult(t){return t.behavior=At(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){let{state:n}=t,r=super.createResult(t,e),{isFetching:s,isRefetching:i,isError:a,isRefetchError:u}=r,c=n.fetchMeta?.fetchMore?.direction,d=a&&c==="forward",l=s&&c==="forward",p=a&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:ei(e,n.data),hasPreviousPage:ti(e,n.data),isFetchNextPageError:d,isFetchingNextPage:l,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:u&&!d&&!p,isRefetching:i&&!l&&!f}}};var ln,Se,G,ct,Re,He,ni,ri=(ni=class extends Hn{constructor(e){super();b(this,Re);b(this,ln);b(this,Se);b(this,G);b(this,ct);_(this,ln,e.client),this.mutationId=e.mutationId,_(this,G,e.mutationCache),_(this,Se,[]),this.state=e.state||Jr(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){o(this,Se).includes(e)||(o(this,Se).push(e),this.clearGcTimeout(),o(this,G).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_(this,Se,o(this,Se).filter(n=>n!==e)),this.scheduleGc(),o(this,G).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){o(this,Se).length||(this.state.status==="pending"?this.scheduleGc():o(this,G).remove(this))}continue(){return o(this,ct)?.continue()??this.execute(this.state.variables)}async execute(e){let n=()=>{P(this,Re,He).call(this,{type:"continue"})},r={client:o(this,ln),meta:this.options.meta,mutationKey:this.options.mutationKey};_(this,ct,Vn({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,u)=>{P(this,Re,He).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{P(this,Re,He).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,G).canRun(this)}));let s=this.state.status==="pending",i=!o(this,ct).canStart();try{if(s)n();else{P(this,Re,He).call(this,{type:"pending",variables:e,isPaused:i}),o(this,G).config.onMutate&&await o(this,G).config.onMutate(e,this,r);let u=await this.options.onMutate?.(e,r);u!==this.state.context&&P(this,Re,He).call(this,{type:"pending",context:u,variables:e,isPaused:i})}let a=await o(this,ct).start();return await o(this,G).config.onSuccess?.(a,e,this.state.context,this,r),await this.options.onSuccess?.(a,e,this.state.context,r),await o(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,e,this.state.context,r),P(this,Re,He).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,G).config.onError?.(a,e,this.state.context,this,r)}catch(u){Promise.reject(u)}try{await this.options.onError?.(a,e,this.state.context,r)}catch(u){Promise.reject(u)}try{await o(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,r)}catch(u){Promise.reject(u)}throw P(this,Re,He).call(this,{type:"error",error:a}),a}finally{o(this,G).runNext(this)}}},ln=new WeakMap,Se=new WeakMap,G=new WeakMap,ct=new WeakMap,Re=new WeakSet,He=function(e){let n=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),I.batch(()=>{o(this,Se).forEach(r=>{r.onMutationUpdate(e)}),o(this,G).notify({mutation:this,type:"updated",action:e})})},ni);function Jr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ae,fe,dn,si,ii=(si=class extends oe{constructor(e={}){super();b(this,Ae);b(this,fe);b(this,dn);this.config=e,_(this,Ae,new Set),_(this,fe,new Map),_(this,dn,0)}build(e,n,r){let s=new ri({client:e,mutationCache:this,mutationId:++Wt(this,dn)._,options:e.defaultMutationOptions(n),state:r});return this.add(s),s}add(e){o(this,Ae).add(e);let n=Bn(e);if(typeof n=="string"){let r=o(this,fe).get(n);r?r.push(e):o(this,fe).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(o(this,Ae).delete(e)){let n=Bn(e);if(typeof n=="string"){let r=o(this,fe).get(n);if(r)if(r.length>1){let s=r.indexOf(e);s!==-1&&r.splice(s,1)}else r[0]===e&&o(this,fe).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){let n=Bn(e);if(typeof n=="string"){let s=o(this,fe).get(n)?.find(i=>i.state.status==="pending");return!s||s===e}else return!0}runNext(e){let n=Bn(e);return typeof n=="string"?o(this,fe).get(n)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){I.batch(()=>{o(this,Ae).forEach(e=>{this.notify({type:"removed",mutation:e})}),o(this,Ae).clear(),o(this,fe).clear()})}getAll(){return Array.from(o(this,Ae))}find(e){let n={exact:!0,...e};return this.getAll().find(r=>Kn(n,r))}findAll(e={}){return this.getAll().filter(n=>Kn(e,n))}notify(e){I.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){let e=this.getAll().filter(n=>n.state.isPaused);return I.batch(()=>Promise.all(e.map(n=>n.continue().catch(q))))}},Ae=new WeakMap,fe=new WeakMap,dn=new WeakMap,si);function Bn(t){return t.options.scope?.id}var Me,Be,Z,Oe,Ie,Wn,Yr,oi,Xr=(oi=class extends oe{constructor(e,n){super();b(this,Ie);b(this,Me);b(this,Be);b(this,Z);b(this,Oe);_(this,Me,e),this.setOptions(n),this.bindMethods(),P(this,Ie,Wn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let n=this.options;this.options=o(this,Me).defaultMutationOptions(e),_t(this.options,n)||o(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,Z),observer:this}),n?.mutationKey&&this.options.mutationKey&&be(n.mutationKey)!==be(this.options.mutationKey)?this.reset():o(this,Z)?.state.status==="pending"&&o(this,Z).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,Z)?.removeObserver(this)}onMutationUpdate(e){P(this,Ie,Wn).call(this),P(this,Ie,Yr).call(this,e)}getCurrentResult(){return o(this,Be)}reset(){o(this,Z)?.removeObserver(this),_(this,Z,void 0),P(this,Ie,Wn).call(this),P(this,Ie,Yr).call(this)}mutate(e,n){return _(this,Oe,n),o(this,Z)?.removeObserver(this),_(this,Z,o(this,Me).getMutationCache().build(o(this,Me),this.options)),o(this,Z).addObserver(this),o(this,Z).execute(e)}},Me=new WeakMap,Be=new WeakMap,Z=new WeakMap,Oe=new WeakMap,Ie=new WeakSet,Wn=function(){let e=o(this,Z)?.state??Jr();_(this,Be,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},Yr=function(e){I.batch(()=>{if(o(this,Oe)&&this.hasListeners()){let n=o(this,Be).variables,r=o(this,Be).context,s={client:o(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{o(this,Oe).onSuccess?.(e.data,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(e.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{o(this,Oe).onError?.(e.error,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(void 0,e.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,Be))})})},oi);var Ce,ai,ci=(ai=class extends oe{constructor(e={}){super();b(this,Ce);this.config=e,_(this,Ce,new Map)}build(e,n,r){let s=n.queryKey,i=n.queryHash??tn(s,n),a=this.get(i);return a||(a=new $s({client:e,queryKey:s,queryHash:i,options:e.defaultQueryOptions(n),state:r,defaultOptions:e.getQueryDefaults(s)}),this.add(a)),a}add(e){o(this,Ce).has(e.queryHash)||(o(this,Ce).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let n=o(this,Ce).get(e.queryHash);n&&(e.destroy(),n===e&&o(this,Ce).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){I.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return o(this,Ce).get(e)}getAll(){return[...o(this,Ce).values()]}find(e){let n={exact:!0,...e};return this.getAll().find(r=>Nn(n,r))}findAll(e={}){let n=this.getAll();return Object.keys(e).length>0?n.filter(r=>Nn(e,r)):n}notify(e){I.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){I.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){I.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ce=new WeakMap,ai);var D,We,$e,Mt,Ot,Ge,It,Ft,ui,Zr=(ui=class{constructor(t={}){b(this,D);b(this,We);b(this,$e);b(this,Mt);b(this,Ot);b(this,Ge);b(this,It);b(this,Ft);_(this,D,t.queryCache||new ci),_(this,We,t.mutationCache||new ii),_(this,$e,t.defaultOptions||{}),_(this,Mt,new Map),_(this,Ot,new Map),_(this,Ge,0)}mount(){Wt(this,Ge)._++,o(this,Ge)===1&&(_(this,It,yt.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,D).onFocus())})),_(this,Ft,Rt.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,D).onOnline())})))}unmount(){var t,e;Wt(this,Ge)._--,o(this,Ge)===0&&((t=o(this,It))==null||t.call(this),_(this,It,void 0),(e=o(this,Ft))==null||e.call(this),_(this,Ft,void 0))}isFetching(t){return o(this,D).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return o(this,We).findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,D).get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),n=o(this,D).build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(de(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return o(this,D).findAll(t).map(({queryKey:e,state:n})=>{let r=n.data;return[e,r]})}setQueryData(t,e,n){let r=this.defaultQueryOptions({queryKey:t}),i=o(this,D).get(r.queryHash)?.state.data,a=Ds(e,i);if(a!==void 0)return o(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return I.batch(()=>o(this,D).findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,D).get(e.queryHash)?.state}removeQueries(t){let e=o(this,D);I.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){let n=o(this,D);return I.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let n={revert:!0,...e},r=I.batch(()=>o(this,D).findAll(t).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(t,e={}){return I.batch(()=>(o(this,D).findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let n={...e,cancelRefetch:e.cancelRefetch??!0},r=I.batch(()=>o(this,D).findAll(t).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let n=o(this,D).build(this,e);return n.isStaleByTime(de(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(q).catch(q)}fetchInfiniteQuery(t){return t.behavior=At(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(q).catch(q)}ensureInfiniteQueryData(t){return t.behavior=At(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Rt.isOnline()?o(this,We).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,D)}getMutationCache(){return o(this,We)}getDefaultOptions(){return o(this,$e)}setDefaultOptions(t){_(this,$e,t)}setQueryDefaults(t,e){o(this,Mt).set(be(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...o(this,Mt).values()],n={};return e.forEach(r=>{et(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){o(this,Ot).set(be(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...o(this,Ot).values()],n={};return e.forEach(r=>{et(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;let e={...o(this,$e).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=tn(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===vt&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...o(this,$e).mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){o(this,D).clear(),o(this,We).clear()}},D=new WeakMap,We=new WeakMap,$e=new WeakMap,Mt=new WeakMap,Ot=new WeakMap,Ge=new WeakMap,It=new WeakMap,Ft=new WeakMap,ui);var kt=B(ce(),1),fi=B($n(),1),es=kt.createContext(void 0),K=t=>{let e=kt.useContext(es);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},fn=({client:t,children:e})=>(kt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,fi.jsx)(es.Provider,{value:t,children:e}));var Gn=B(ce(),1),pi=Gn.createContext(!1),hi=()=>Gn.useContext(pi),Sl=pi.Provider;var pn=B(ce(),1),Oa=B($n(),1);function Ia(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Fa=pn.createContext(Ia()),mi=()=>pn.useContext(Fa);var gi=B(ce(),1);var yi=(t,e,n)=>{let r=n?.state.error&&typeof t.throwOnError=="function"?bt(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},_i=t=>{gi.useEffect(()=>{t.clearReset()},[t])},vi=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:s})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(s&&t.data===void 0||bt(n,[t.error,r]));var bi=t=>{if(t.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},wi=(t,e)=>t.isLoading&&t.isFetching&&!e,Si=(t,e)=>t?.suspense&&e.isPending,ts=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});var ze=B(ce(),1);function zn(t,e,n){let r=hi(),s=mi(),i=K(n),a=i.defaultQueryOptions(t);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let u=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",bi(a),yi(a,s,u),_i(s);let c=!i.getQueryCache().get(a.queryHash),[d]=ze.useState(()=>new e(i,a)),l=d.getOptimisticResult(a),p=!r&&t.subscribed!==!1;if(ze.useSyncExternalStore(ze.useCallback(f=>{let h=p?d.subscribe(I.batchCalls(f)):q;return d.updateResult(),h},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ze.useEffect(()=>{d.setOptions(a)},[a,d]),Si(a,l))throw ts(a,d,s);if(vi({result:l,errorResetBoundary:s,throwOnError:a.throwOnError,query:u,suspense:a.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!we.isServer()&&wi(l,r)&&(c?ts(a,d,s):u?.promise)?.catch(q).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}function k(t,e){return zn(t,un,e)}var Fe=B(ce(),1);function ke(t,e){let n=K(e),[r]=Fe.useState(()=>new Xr(n,t));Fe.useEffect(()=>{r.setOptions(t)},[r,t]);let s=Fe.useSyncExternalStore(Fe.useCallback(a=>r.subscribe(I.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Fe.useCallback((a,u)=>{r.mutate(a,u).catch(q)},[r]);if(s.error&&bt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function hn(t,e){return zn(t,zr,e)}var A=new Zr({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}});function V(){return le()??"__unscoped__"}var w={all:()=>["vfs",V()],item:t=>["vfs",V(),"item",t],itemById:t=>["vfs","item-by-id",t],children:t=>["vfs",V(),"children",t],allChildren:()=>["vfs",V(),"children"],types:t=>["vfs","types",t??"default"],edges:t=>["vfs","edges",t],search:(t,e)=>["vfs",V(),"search",t,...e??[]],items:(t,e)=>["vfs",V(),"items",t,JSON.stringify(e??{})],allItems:()=>["vfs",V(),"items"],tree:(t,e)=>["vfs",V(),"tree",t,e??1],openEnvelope:(t,e)=>["vfs",V(),"open",t,e??"__default__"],allOpenEnvelopes:()=>["vfs",V(),"open"],memberFocus:t=>["vfs","member-focus",t],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(t,e,n)=>["vfs",V(),"get-activity-feed",t,e,n],itemVersions:(t,e,n,r)=>["vfs","item-versions",t,e,n,r],itemHistory:(t,e,n)=>["vfs","item-history",t,e,n],channelMessages:(t,e)=>["vfs",V(),"channel-messages",t,e??"__top__"],allChannelMessages:()=>["vfs",V(),"channel-messages"],channels:t=>["vfs",V(),"channels",t??"all"],allChannels:()=>["vfs",V(),"channels"],notifications:(t,e)=>["vfs",V(),"notifications",t??"all",e??200],allNotifications:()=>["vfs",V(),"notifications"],unreadCounts:()=>["vfs",V(),"unread-counts"],memberships:t=>["memberships",t]};function Ri(){return new Date().toISOString()}function Ci(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function pe(t){let e=t.path||t.item_path||"",n=e.split("/");n.pop();let r=n.join("/"),s=t.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:t.id||t.item_id||"",name:t.name||t.item_name||"",item_type:t.item_type||"unknown",path:e,parent_path:r,is_active:t.is_active!==!1,has_children:t.has_children??!1,created_at:t.created_at||Ri(),updated_at:t.updated_at||Ri(),visibility:t.visibility,type_data:s,scope_item_id:t.scope_item_id,fractal_id:t.fractal_id,parent_instance_id:t.parent_instance_id,owner_principal_id:t.owner_principal_id,created_by_principal_id:t.created_by_principal_id,parent_id:t.parent_id,space_item_id:t.space_item_id,account_item_id:t.account_item_id}}function mn(t){return(t.content?.items||t.items||[]).map(pe)}async function Yn(t){try{let e=await R("read",{id:t});if(e.item_name||e.item_path){let r=pe(e);return r.path&&A.setQueryData(w.item(r.path),r),r}let n=e.item;if(n){let r=pe(n);return r.path&&A.setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function Xn(t){try{let e=await R("read",{path:t});if(e.item_name||e.item_path)return pe(e);let n=e.item;return n?pe(n):null}catch{return null}}async function Zn(t){try{let e=await R("list",{path:t,limit:200}),n=mn(e);for(let r of n)A.setQueryData(w.item(r.path),r);return n}catch(e){return console.error(`[gateway] Failed to fetch children of ${t}:`,e),[]}}async function er(t,e,n){try{let r=await R("list",{path:t,limit:e,offset:n}),s=mn(r);for(let i of s)A.setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${t}:`,r),{items:[],total_hint:0}}}async function tr(t){let n=await R("types-list",t?{scope_id:t}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,u=i.type_data;!a||!u||s.set(a,{type_key:a,display_name:u.display_name||a,display_name_plural:u.display_name_plural||a+"s",icon:u.icon||"File",color:u.color||"gray",description:u.description||"",input_schema:u.input_schema||{},system_schema:u.system_schema||{},json_schema:u.input_schema||u.json_schema||{},default_data:u.default_data||{},field_defaults:u.field_defaults||{},renderer_config:u.renderer_config||{},is_system:u.is_system??!1,is_active:u.is_active??!0,is_container:u.is_container??!1,is_scope:u.is_scope??!1,render_mode:u.render_mode||"none",placement_mode:u.placement_mode,direct_parent_types:u.direct_parent_types,allowed_parent_types:u.allowed_parent_types,governed_create:u.governed_create,create_method:u.create_method,dedup:u.dedup,edges:u.edges,events:u.events})}return s}async function nr(t){try{let e=await R("edges",{item_id:t}),n=e.outgoing||[],r=e.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Ci(),source_item_id:t,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||Ci(),source_item_id:i.source_id||"",target_item_id:t,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(e){return console.warn(`[gateway] Failed to fetch edges for ${t}:`,e),[]}}async function rr(t,e=1,n,r){try{let s={path:t,max_depth:e>0?e:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await R("tree",s),a=mn(i);for(let u of a)A.setQueryData(w.item(u.path),u);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${t}:`,s),[]}}async function sr(t,e=50,n=0){try{let r=await R("get-activity-feed",{scope_path:t,limit:e,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${t}:`,r),[]}}async function gn(t,e={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=e;try{let i=await R("item-versions",{id:t,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${t}:`,i),{versions:[],total:0}}}async function ir(t,e=50,n=0){return gn(t,{limit:e,offset:n})}async function or(t,e,n){try{let r={scope_id:t};e?.length&&(r.item_types=e),n&&(r.limit=n);let s=await R("member-focus",r),i=mn(s);for(let a of i)A.setQueryData(w.item(a.path),a);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${t}:`,r),[]}}async function ar(t,e){let n={path:t};e?.mode&&(n.mode=e.mode),e?.strategy&&(n.strategy=e.strategy),e?.arguments&&(n.arguments=e.arguments);let s=await R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}async function yn(t){let e={item_type:t.type};t.scope&&(e.scope_path=t.scope);let n={};if(t.name&&(n.name=t.name),t.tag&&(n.tag=t.tag),t.parent_id&&(n.parent_id=t.parent_id),t.sort_by&&(n.sort_by=t.sort_by),t.sort_dir&&(n.sort_dir=t.sort_dir),t.offset!=null&&(n.offset=t.offset),t.fields)for(let[r,s]of Object.entries(t.fields))n[`field.${r}`]=String(s);Object.keys(n).length>0&&(e.filters=n),t.limit!=null&&(e.limit=t.limit);try{let r=await R("query",e),s=mn(r);for(let i of s)A.setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch items of type ${t.type}:`,r),{items:[],total_hint:0}}}function Pi(t){return t.filter(e=>e.item_type==="card").map(e=>{let n=e.type_data||{},r=n.payload||{};return{id:e.id||"",path:e.path||"",name:e.name||(e.path||"").split("/").pop()||"",createdAt:e.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(e.name||"").startsWith("card-")?(e.name||"").substring(5):void 0,parentMessagePath:e.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0}}).sort((e,n)=>e.createdAt.localeCompare(n.createdAt))}function ns(t){return t.filter(e=>e.item_type==="message").map(e=>{let n=e.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:e.id||"",path:e.path||"",content:n.message||n.content||"",created_at:e.created_at||"",role:r,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((e,n)=>e.seq-n.seq)}async function xi(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ns(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${t}:`,n),[]}}async function cr(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let s=await R("get-channel-messages",n),i=s.messages||[],a=ns(i),u=Pi(i),c=new Map,d=[];for(let l of u)if(l.parentMessagePath){let p=c.get(l.parentMessagePath)||[];p.push(l),c.set(l.parentMessagePath,p)}else d.push(l);return{messages:a,messageCards:c,siblingCards:d,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function _n(t,e){try{let n={channel_path:t};e?.parentMessageId&&(n.parent_message_id=e.parentMessageId),e?.limit&&(n.limit=e.limit),e?.before_seq!=null&&(n.before_seq=e.before_seq),e?.after_seq!=null&&(n.after_seq=e.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],a=Pi(i),u=new Map,c=[];for(let d of a)if(d.parentMessagePath){let l=u.get(d.parentMessagePath)||[];l.push(d),u.set(d.parentMessagePath,l)}else c.push(d);return{messages:ns(i),messageCards:u,siblingCards:c,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Jn(t){A.invalidateQueries({queryKey:w.children(t)})}function rs(t){A.invalidateQueries({queryKey:w.item(t)})}function Ei(t,e){rs(t),Jn(t);let n=t.split("/");n.pop();let r=n.join("/")||e;r&&Jn(r)}function Ti(t){let e=t+"/";A.invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===t||s.startsWith(e)))}})}function Ai(){A.invalidateQueries({queryKey:w.all()})}function Mi(t){A.invalidateQueries({queryKey:w.types(t)})}function Oi(t,e){t?A.invalidateQueries({queryKey:w.channelMessages(t,e)}):A.invalidateQueries({queryKey:w.allChannelMessages()})}function Ii(t,e){t&&e?A.invalidateQueries({queryKey:w.openEnvelope(t,e)}):t?A.invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===t}}):A.invalidateQueries({queryKey:w.allOpenEnvelopes()})}var ka=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...t){ka&&console.log("[WS]",...t)}var O=null,qt=null,Dt=null,vn=0,qa=3e4,Fi=1e4,Qt=!1,Da=3e4,ur=null,ki=!1;function Ua(){wn(),ur=setInterval(()=>{qe({type:"ping"})},Da)}function wn(){ur&&(clearInterval(ur),ur=null)}function Qa(){typeof document>"u"||(document.hidden?wn():bn()&&(W("Tab visible, reconnecting..."),Sn()))}function Na(){ki||typeof document>"u"||(document.addEventListener("visibilitychange",Qa),ki=!0)}var ee={},Ut=[],Nt=new Map,ut=new Map;function Ka(){return Object.keys(ee).some(e=>ee[e]&&ee[e].length>0)||Ut.length>0}function bn(){return Nt.size>0||ut.size>0}async function Sn(){if(!bn()){W("ensureConnection: no active subscriptions, skipping");return}if(O&&O.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(qt)return W("ensureConnection: connection already in flight, waiting..."),qt;if(O){W("ensureConnection: killing stale WS in state",O.readyState);try{O.close()}catch{}O=null}return Qt=!1,qt=(async()=>{try{let t=typeof window<"u"&&window.__FSAOS_CONFIG__||{},e=De,n=await Pe();if(!n){W("ensureConnection: no token available, will retry"),qi();return}let r=e.startsWith("https")?"wss":"ws",s=e.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),O=new WebSocket(i),await new Promise((a,u)=>{if(!O)return u(new Error("WebSocket not created"));let c=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",Fi,"ms"),O&&O.readyState!==WebSocket.OPEN){try{O.close()}catch{}O=null}u(new Error("WebSocket connection timeout"))},Fi);O.onopen=()=>{clearTimeout(c),W("ensureConnection: CONNECTED"),vn=0,La(),(typeof document>"u"||!document.hidden)&&Ua(),Na(),a()},O.onmessage=d=>{ja(d.data)},O.onerror=()=>{W("ensureConnection: WS error event")},O.onclose=d=>{clearTimeout(c),W("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),O=null,wn(),!Qt&&bn()&&qi(),u(new Error(`WebSocket closed: ${d.code}`))}})}catch(t){W("ensureConnection: failed -",t?.message||t)}finally{qt=null}})(),qt}function qi(){if(Dt||typeof document<"u"&&document.hidden)return;let t=Math.min(1e3*Math.pow(2,vn)+Math.random()*1e3,qa);vn++,W("scheduleReconnect: attempt",vn,"in",Math.round(t),"ms"),Dt=setTimeout(()=>{Dt=null,bn()&&Sn()},t)}function La(){for(let t of Nt.values())W("resubscribeAll: scope",t.scope_id),qe({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ut.values())W("resubscribeAll: path",t.path),qe({type:"subscribe_path",path:t.path,event_types:t.event_types})}function qe(t){O&&O.readyState===WebSocket.OPEN&&O.send(JSON.stringify(t))}function ja(t){try{let e=JSON.parse(t);if(e.type==="subscribed"||e.type==="subscribed_path"||e.type==="unsubscribed"||e.type==="unsubscribed_path"||e.type==="pong")return;if(e.type==="error"){console.warn("[WS] Server error:",e.message);return}if(e.type==="event"||e.event_type){let n=e.event_type||"message",r=e.data||e;r.path&&ee[r.path]&&ee[r.path].forEach(s=>s(r)),ee["*"]&&ee["*"].forEach(s=>s(r));for(let s of Ut)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ss(){!Ka()&&Nt.size===0&&ut.size===0&&O&&(Qt=!0,wn(),O.close(),O=null,Qt=!1)}function lr(t,e){return ee[t]||(ee[t]=[]),ee[t].push(e),ut.has(t)||(ut.set(t,{path:t,event_types:["token_stream"]}),O&&O.readyState===WebSocket.OPEN&&qe({type:"subscribe_path",path:t,event_types:["token_stream"]})),Sn(),()=>{let n=ee[t];if(n){let r=n.indexOf(e);r!==-1&&n.splice(r,1),n.length===0&&(delete ee[t],ut.delete(t),qe({type:"unsubscribe_path",path:t}))}ss()}}function ue(t,e,n){let s=(Array.isArray(t)?t:[t]).map(i=>({eventType:i,callback:e,filter:n}));return Ut.push(...s),bn()&&Sn(),()=>{for(let i of s){let a=Ut.indexOf(i);a!==-1&&Ut.splice(a,1)}ss()}}function dr(t,e=["vfs_change","ccm_change"]){return W("subscribeToScope:",t,e),Nt.set(t,{scope_id:t,event_types:e}),O&&O.readyState===WebSocket.OPEN&&qe({type:"subscribe",scope_id:t,event_types:e}),Sn(),()=>{Nt.delete(t),qe({type:"unsubscribe",scope_id:t}),ss()}}function Di(t,e,n={}){qe({type:"emit",scope_id:t,event_type:e,payload:n})}function is(){W("disconnectSSE: tearing down"),Qt=!0,wn(),O&&(O.close(),O=null),Dt&&(clearTimeout(Dt),Dt=null),qt=null,Qt=!1,vn=0;for(let t of Object.keys(ee))delete ee[t];Ut.length=0,Nt.clear(),ut.clear()}function Ui(){qe({type:"ping"})}xe(is);var Kt=new Map,fr=null,Rn=new Map,Va=250;function Cn(t){pr(),Pn(t),fr=ue("vfs_change",e=>Ha(e))}function Pn(t){if(Kt.has(t))return;let e=dr(t,["vfs_change","ccm_change"]);Kt.set(t,e)}function Qi(t){let e=Kt.get(t);e&&(e(),Kt.delete(t))}function pr(){for(let[,t]of Kt)t();Kt.clear(),fr&&(fr(),fr=null),Rn.forEach(t=>clearTimeout(t)),Rn.clear()}xe(pr);function Ha(t){let e=t.path,n=t.action;if(!e)return;let r=e.split("/");r.pop();let s=r.join("/")||"/root",i=Rn.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Rn.delete(s),Ba(n,e,t,s)},Va);Rn.set(s,a)}function Ba(t,e,n,r){if((t||"").toUpperCase()==="DELETE")A.removeQueries({queryKey:w.item(e)}),A.removeQueries({queryKey:w.children(e)}),A.removeQueries({queryKey:w.tree(e)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},a=pe(i);a&&a.id&&A.setQueryData(w.item(e),a)}catch{}A.invalidateQueries({queryKey:w.children(r)}),A.invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let u=a[2];return e.startsWith(u+"/")||e===u}}),n.item_id&&A.invalidateQueries({queryKey:w.itemById(n.item_id)})}var os=B(ce(),1),Li=B(Ki(),1);function ji(t){return R("read",{path:t})}function Vi(t,e){return R("list",{path:t,...e})}function Hi(t){return R("create",t)}function Bi(t){return R("update",t)}function Wi(t){return R("create",t)}function $i(t,e){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:t,instance_path:r,...e||{}})}function Gi(t,e,n){return R("signal",{target_id:t,event_name:e,payload:n||{}})}function zi(t){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+t}var Ji={signIn:t=>t.provider?F.auth.signInWithOAuth({provider:t.provider,options:{redirectTo:t.redirectTo||window.location.href}}):F.auth.signInWithPassword({email:t.email,password:t.password}),signUp:t=>F.auth.signUp({email:t.email,password:t.password,options:{data:t.metadata||{}}}),signOut:async()=>{await F.auth.signOut(),mt(),A.clear()},getSession:()=>F.auth.getSession().then(t=>t.data.session),getUser:()=>F.auth.getUser().then(t=>t.data.user),onAuthStateChange:t=>{let{data:{subscription:e}}=F.auth.onAuthStateChange((n,r)=>{t({event:n,session:r,user:r?.user??null})});return()=>e?.unsubscribe()},resetPassword:t=>F.auth.resetPasswordForEmail(t),signInWithMagicLink:(t,e)=>F.auth.signInWithOtp({email:t,options:{emailRedirectTo:e||window.location.href}})};function Yi(){let t=document.getElementById("root");if(t)try{let e=window.__FSAOS_COMPONENT__;if(!e){t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=e.default||e,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Li.createRoot)(t).render((0,os.createElement)(fn,{client:A},(0,os.createElement)(n,s)))}catch(e){console.error("[FSAOS] Failed to mount root component:",e),t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(e.message||e)+"</pre></div>"}}function Xi(){let t=window.React,e=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:t,"react-dom":e,"react-dom/client":e,"react/jsx-runtime":{jsx:t?.createElement,jsxs:t?.createElement,Fragment:t?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=B(ce(),1),$a=B(eo(),1),Ga=B($n(),1);function Wa(t){return`${t}/settings/mounts`}var xn=null;async function as(t,e){xn=Wa(t);try{let s=((await R("read",{path:xn}))?.item?.type_data?.mounts??[]).map(e).filter(a=>a!==null),i=Qe();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Mr(s),s}catch{let n=Qe(),r=n?[n]:[];return Mr(r),r}}async function to(){if(!xn)return;let t=ht().map(n=>n.id),e=Ye()?.id??null;try{await R("update",{path:xn,type_data:{mounts:t,last_anchor:e}})}catch{try{let r=xn.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:t,last_anchor:e}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function cs(t){xs(t),await to()}async function no(t){Es(t),await to()}function N(){return(0,y.useSyncExternalStore)(Xe,_e,_e)}function io(){return N(),Un()}function oo(t){return N(),k({queryKey:w.item(t),queryFn:()=>Xn(t),enabled:!!t})}function ao(t){return N(),k({queryKey:w.itemById(t),queryFn:()=>Yn(t),enabled:!!t})}function ls(t){return N(),k({queryKey:w.children(t),queryFn:()=>Zn(t),enabled:!!t})}function co(t){let e=ls(t);return{...e,children:e.data??[]}}function uo(t,e=1){return N(),k({queryKey:w.tree(t,e),queryFn:()=>rr(t,e),enabled:!!t})}function lo(t,e){return N(),k({queryKey:w.search(t,e),queryFn:async()=>{let n={query:t};e?.length&&(n.item_types=e);let r=await R("search",n);return(r.content?.items||r.items||[]).map(pe)},enabled:!!t&&t.length>0})}function fo(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return k({queryKey:["vfs",le()??"__unscoped__","resolve",JSON.stringify(e??{})],queryFn:async()=>await R("resolve",e),enabled:!!e?.query&&e.query.length>0})}function po(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return k({queryKey:w.items(e?.type??"",e),queryFn:()=>yn(e),enabled:!!e?.type,select:n=>n.items})}function ho(t){N();let e=t?.limit??20,n=(0,y.useMemo)(()=>t,[JSON.stringify(t)]),r=hn({queryKey:["vfs",le()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>yn({...n,limit:e,offset:i}),initialPageParam:0,getNextPageParam:(i,a,u)=>{if(!(i.items.length<e))return u+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let u of r.data.pages)for(let c of u.items)c.id&&!i.has(c.id)&&(i.add(c.id),a.push(c));return a},[r.data?.pages]),fetchNextPage:r.fetchNextPage,isFetchingNextPage:r.isFetchingNextPage,isExhausted:!r.hasNextPage,isLoading:r.isLoading,isFetching:r.isFetching,error:r.error,totalHint:r.data?.pages?.[0]?.total_hint}}function mo(t){N();let e=20,n=hn({queryKey:["vfs",le()??"__unscoped__","infinite-children",t??""],queryFn:async({pageParam:s=0})=>er(t,e,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<e))return a+s.items.length},enabled:!!t});return{allItems:(0,y.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let u of a.items)u.id&&!s.has(u.id)&&(s.add(u.id),i.push(u));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function go(t){return N(),k({queryKey:w.edges(t),queryFn:()=>nr(t),enabled:!!t})}function hr(t){return N(),k({queryKey:w.types(t),queryFn:()=>tr(t)})}function yo(t,e){let n=hr(e);return{...n,data:n.data?.get(t)??void 0}}function _o(t,e){N();let n=(0,y.useMemo)(()=>e?.arguments,[JSON.stringify(e?.arguments)]),r=e?.mode,s=e?.strategy,i=e?.width;return k({queryKey:[...w.openEnvelope(t,s),i],queryFn:async()=>{let a=await ar(t,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let u=a.render.props.url,c=u.includes("?")?"&":"?";a.render.props.url=`${u}${c}w=${i}`}return a},enabled:!!t})}var ro={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function vo(t){let e=hr(t),n=e.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:h=>n.get(h.item_type)?.is_container??!1,isScope:h=>n.get(h.item_type)?.is_scope??!1,isScopeType:h=>n.get(h)?.is_scope??!1,isContainerType:h=>n.get(h)?.is_container??!1,getTypeDefinition:h=>n.get(h),getTypeColor:h=>n.get(h)?.color??"gray",getTypeIcon:h=>n.get(h)?.icon??"File",getTypeDisplayName:h=>n.get(h)?.display_name??h,getKnownEdgeTypes:()=>Object.entries(ro).map(([h,v])=>({key:h,label:v})),getEdgeTypeLabel:h=>ro[h]??h.replace(/_/g," "),allTypes:n,loading:e.isLoading}),[n,e.isLoading])}function bo(t,e,n){return N(),k({queryKey:w.memberFocus(t),queryFn:()=>or(t,e,n),enabled:!!t})}function wo(t,e={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=e;return k({queryKey:w.itemVersions(t,String(n),String(r),String(s)),queryFn:()=>gn(t,{limit:n,offset:r,include_snapshots:s}),enabled:!!t})}function So(t,e=50,n=0){return k({queryKey:w.itemHistory(t,String(e),String(n)),queryFn:()=>ir(t,e,n),enabled:!!t})}function Ro(t,e=50,n=0){return N(),k({queryKey:w.recentActivity(t,String(e),String(n)),queryFn:()=>sr(t,e,n),enabled:!!t})}function Co(){let[t,e]=(0,y.useState)(null),[n,r]=(0,y.useState)(!0),[s,i]=(0,y.useState)(null);return(0,y.useEffect)(()=>{let a=!1;return qn().then(u=>{if(!a){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};e({path:u.scope_path,scope_id:u.scope_id,fractal_id:u.fractal_id,instance_name:u.instance_name,display_name:u.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(u=>{a||(i(u instanceof Error?u:new Error(String(u))),r(!1))}),()=>{a=!0}},[]),{data:t,loading:n,error:s}}var za=[];function En(t){return{id:t.accountId,path:t.path,kind:t.isSpace?"space":"account",name:t.name,grantedUnderAccountId:t.grantedUnderAccountId??void 0}}function Po(){let{user:t}=mr(),e=(0,y.useRef)(!1),n=k({queryKey:w.memberships(t?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!t?.id,staleTime:1e3*60*2}),r=n.data??za,s=(0,y.useMemo)(()=>r.filter(l=>l.isAccount!==!1&&!l.isSpace),[r]),i=(0,y.useMemo)(()=>{let l=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!l.has(f.subordinateTo);return[...s].sort((f,h)=>Number(p(h))-Number(p(f)))},[s]),a=(0,y.useSyncExternalStore)(Xe,_e,_e),u=(0,y.useMemo)(()=>{let l=Ye();return l?r.find(p=>p.accountId===l.id)??null:null},[a,r]);(0,y.useEffect)(()=>{if(!t?.id){e.current=!1;return}if(!e.current)if(i.length===1){let l=i[0];Yt(En(l)),Cn(l.accountId),l.personalSpacePath&&as(l.personalSpacePath,p=>{let f=r.find(h=>h.accountId===p);return f?En(f):null}).catch(()=>{}),e.current=!0}else i.length>1&&(e.current=!0)},[t?.id,i,r]);let c=(0,y.useCallback)(l=>{let p=r.find(h=>h.path===l);if(!p)return;let f=En(p);Qe()?Ue(f):(Yt(f),p.personalSpacePath&&as(p.personalSpacePath,h=>{let v=r.find(m=>m.accountId===h);return v?En(v):null}).catch(()=>{})),Cn(p.accountId)},[r]),d=(0,y.useCallback)(l=>{let p=r.find(f=>f.path===l);p&&(cs(En(p)).catch(()=>{}),Pn(l))},[r]);return{accounts:i,allMemberships:r,currentAccount:u,mountedScope:null,switchAccount:c,mountScope:d,loading:n.isLoading,error:n.error}}function xo(){let t=(0,y.useSyncExternalStore)(kn,Zt,Zt);return{mounts:(0,y.useMemo)(()=>ht(),[t]),homeAnchor:Qe(),anchor:Ye(),setAnchor:Ue,mount:cs,unmount:no}}function mr(){let[t,e]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[s,i]=(0,y.useState)(!0),a=(0,y.useRef)(null);(0,y.useEffect)(()=>{F.auth.getSession().then(({data:h,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),F.auth.signOut().catch(()=>{}),r(null),e(null),i(!1);return}r(h?.session??null),e(h?.session?.user??null),i(!1)}).catch(h=>{console.warn("[useAuth] getSession threw, clearing stale session:",h?.message),F.auth.signOut().catch(()=>{}),r(null),e(null),i(!1)});let{data:{subscription:f}}=F.auth.onAuthStateChange((h,v)=>{if(h==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),F.auth.signOut().catch(()=>{}),r(null),e(null),i(!1);return}r(v),e(v?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let u=(0,y.useCallback)(async f=>f.provider?F.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):F.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,y.useCallback)(async f=>F.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),d=(0,y.useCallback)(async()=>{await F.auth.signOut(),mt(),A.clear()},[]),l=(0,y.useCallback)(async f=>{let{error:h}=await F.auth.resetPasswordForEmail(f);if(h)throw h},[]),p=(0,y.useCallback)(async(f,h)=>{let{error:v}=await F.auth.signInWithOtp({email:f,options:h?{emailRedirectTo:h}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:t,session:n,loading:s,signIn:u,signUp:c,signOut:d,resetPassword:l,signInWithMagicLink:p}}function Eo(t){let[e,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!1),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))s(!0),R("resolve-asset",{asset_id:t}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):a(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{a(c instanceof Error?c:new Error(String(c))),s(!1)});else{let d=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:d+t}),s(!1)}},[t]),{data:e,loading:r,error:i}}var Tn={},so={};xe(()=>{for(let t of Object.keys(Tn))delete Tn[t]});var To=null;function Ao(t){To=t,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=t)}function Ja(t){switch(t){case"react":return typeof window<"u"&&window.React||y.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||$a;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:Ga;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||To||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${t}`),{}}}function Ya(t,e){return t.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${e}${i}`)}async function Xa(t,e){if(!so[t])try{let n=await fetch(t);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;e&&!r.includes(`.fsaos-c-${e}`)&&(r=Ya(r,`fsaos-c-${e}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",t),e&&s.setAttribute("data-fsaos-component-id",e),s.textContent=r,document.head.appendChild(s),so[t]=s}catch{}}function Za(t){let e=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{e=r};try{let r=["var require = arguments[0];",t,"return window.__FSAOS_COMPONENT__;"].join(`
3
+ `),i=new Function(r)(Ja),a=e??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function ds(t){let[e,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!0),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t)return;let u=!1;s(!0),a(null);let d=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let l=1,p=t+"@v1",f=d+t+"/__bundle.js";try{let S=await fetch(d+t+"/__meta",{cache:"no-store"});S.ok&&(l=(await S.json()).version||1,p=t+"@v"+l,f=d+t+"/__bundle.v"+l+".js")}catch{f=d+t+"/__bundle.js?v="+Date.now()}if(u)return;if(Tn[p]){n(()=>Tn[p]),s(!1);return}let h=await fetch(f);if(!h.ok)throw new Error(`Failed to fetch bundle: ${h.status} ${h.statusText} (${f})`);let v=await h.text();if(u)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Xa(m).catch(()=>{});let g=Za(v);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);Tn[p]=g,u||(n(()=>g),s(!1))}catch(l){u||(a(l instanceof Error?l:new Error(String(l))),s(!1))}})(),()=>{u=!0}},[t]),{Component:e,loading:r,error:i}}var ec=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function Mo(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let e={},n=getComputedStyle(document.documentElement);return ec.forEach(r=>{e[r]=n.getPropertyValue(r).trim()}),{tokens:e}},[]),loading:!1,error:null}}function Oo(t,e){return{data:{allowed:!0},loading:!1,error:null}}function Io(t,e){let n={};return(e||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var se=null,Lt=null,us=new Set;function tc(){us.forEach(t=>t())}xe(()=>{se=null,Lt=null});async function Fo(t){let e=t;if(!e){let{data:r}=await F.auth.getSession();e=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!e)return n;if(se&&se.authUserId===e){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:u}=se;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:u}}return Lt||(Lt=(async()=>{try{let{data:r,error:s}=await F.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",e).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:c}=await F.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(c??[]).map(l=>l.path);a=d.find(l=>l.split("/").length===4)??d[0]??null}let u={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return se={authUserId:e,...u},u}finally{Lt=null}})(),Lt)}async function ko(t){return(await Fo(t)).principalId}function qo(){let t=mr(),e=t.user,n=se?.authUserId===e?.id?se:null,[r,s]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let u=se;u&&u.authUserId===e?.id&&s({principalId:u.principalId,displayName:u.displayName,createdAt:u.createdAt,metadata:u.metadata,vfsPath:u.vfsPath})};return us.add(a),()=>{us.delete(a)}},[e?.id]),(0,y.useEffect)(()=>{if(!e?.id){s(null),i.current=null;return}i.current===e.id&&r?.principalId!=null||(i.current=e.id,Fo(e.id).then(a=>{s(a)}))},[e?.id]),t.loading?{data:null,loading:!0,error:null}:e?{data:{id:e.id,principalId:r?.principalId??null,email:e.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:e.role||e.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??e.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Do(){return{data:null,loading:!1,error:null}}function Uo(t){let{path:e,...n}=t,r=ds(e),s=r.Component,{loading:i,error:a}=r;return i?(0,y.createElement)("div",{className:"fsaos-loading"},""):a?(0,y.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,y.createElement)(s,n):null}function Qo(t){return t.children}function No(t){let e=N(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=t,a=i!==void 0?i&&!!n:!!n,u=(0,y.useMemo)(()=>w.channelMessages(n??"",r),[n,r,e]),c=K(),d=(0,y.useRef)(null),l=k({queryKey:u,queryFn:()=>cr(n,r),enabled:a});(0,y.useEffect)(()=>{if(!s||!a)return;let m=ue("vfs_change",()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c.invalidateQueries({queryKey:u})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),d.current&&clearTimeout(d.current)}},[s,a,n,u,c]);let p=l.data,f=p?.messages??[],h=p?.messageCards??new Map,v=p?.siblingCards??[];return{messages:f,messageCards:h,siblingCards:v,threads:(0,y.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Ko(t){N();let{channelPath:e,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=t,a=!!n,u=i&&!!e,c=hn({queryKey:[...w.channelMessages(e||"",n),"infinite",r],queryFn:async({pageParam:m})=>_n(e,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:u}),d=(0,y.useMemo)(()=>{if(!c.data?.pages)return[];let m=new Set,g=[];for(let S of c.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[c.data?.pages]),{messageCards:l,siblingCards:p}=(0,y.useMemo)(()=>{let m=new Map,g=[];if(!c.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of c.data.pages){for(let[x,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let H=m.get(x)||[];H.push(L),m.set(x,H)}for(let x of C.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:m,siblingCards:g}},[c.data?.pages]),f=K(),h=(0,y.useRef)(null),v=(0,y.useMemo)(()=>[...w.channelMessages(e||"",n),"infinite",r],[e,n,r]);return(0,y.useEffect)(()=>{if(!s||!e||!u)return;let m=ue("vfs_change",()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{let g=f.getQueryData(v);if(!g?.pages?.length){f.invalidateQueries({queryKey:v});return}let S=0;for(let C of g.pages)for(let x of C.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:v});return}try{let C=await _n(e,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let x=Math.min(...C.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:v});return}}f.setQueryData(v,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,H=U[L],lt=new Set(H.messages.map(T=>T.id)),ne=C.messages.filter(T=>!lt.has(T.id)),Q=[...H.messages,...ne].sort((T,Je)=>T.seq-Je.seq),J=new Map(H.messageCards);for(let[T,Je]of C.messageCards){let $=J.get(T)||[],jt=new Set($.map(_r=>_r.id)),la=Je.filter(_r=>!jt.has(_r.id));J.set(T,[...$,...la])}let me=new Set(H.siblingCards.map(T=>T.id)),ge=C.siblingCards.filter(T=>!me.has(T.id)),ye=[...H.siblingCards,...ge];return U[L]={...H,messages:Q,messageCards:J,siblingCards:ye},{...x,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:v})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(e));return()=>{m(),h.current&&clearTimeout(h.current)}},[s,e,u,v,f,n,r]),{messages:d,messageCards:l,siblingCards:p,threads:d.filter(m=>m.reply_count>0),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch,hasPreviousPage:c.hasPreviousPage??!1,fetchPreviousPage:c.fetchPreviousPage,isFetchingPreviousPage:c.isFetchingPreviousPage??!1,hasNextPage:c.hasNextPage??!1,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage??!1}}function nc(t){return t==="on"||t==="auto"?"on":"off"}function rc(t){let e=t.type_data||{},n=t._reader||{},r=n.context_lineage||{};return{id:t.id||"",path:t.path||"",name:t.name||"",displayName:e.display_name||t.name||"",aiMode:nc(e.ai_mode),isPrivate:e.is_private||!1,isDm:e.is_dm||!1,messageCount:e.message_count||0,updatedAt:t.updated_at||"",chatScopePath:r.context_path||"",contextId:t.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:t.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:e.auto_pilot||!1}}function gr(t={}){let e=N(),{realtime:n=!0,enabled:r=!0}=t,s=K(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[e]),u=k({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(rc),enabled:r});return(0,y.useEffect)(()=>{if(!n||!r)return;let d=ue("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),l=ue("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{d(),l(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Lo(t={}){let e=gr(t),n=(0,y.useMemo)(()=>e.channels.filter(r=>!r.isDm),[e.channels]);return{...e,channels:n}}function jo(t={}){let e=gr(t),n=(0,y.useMemo)(()=>e.channels.filter(r=>r.isDm),[e.channels]);return{...e,channels:n}}function fs(t={}){let e=N(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=t,a=K(),u=(0,y.useRef)(null),c=(0,y.useMemo)(()=>w.notifications(n,r),[n,r,e]),d=k({queryKey:c,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>ue(f,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.invalidateQueries({queryKey:c})},2e3)},h=>h.item_type==="notification"||h.item_type==="message"));return()=>{p.forEach(f=>f()),u.current&&clearTimeout(u.current)}},[s,i,c,a]),{notifications:d.data??[],isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Vo(t={}){let{channels:e,realtime:n=!0,enabled:r=!0}=t,{notifications:s,isLoading:i,isFetching:a,error:u,refetch:c}=fs({filter:"unread",limit:200,realtime:n,enabled:r}),d=(0,y.useMemo)(()=>{let h=new Map;for(let v of s)v.is_unread&&v.channel_id&&h.set(v.channel_id,(h.get(v.channel_id)||0)+1);return h},[s]),l=(0,y.useMemo)(()=>{let h=0;return d.forEach(v=>{h+=v}),h},[d]),{dmUnread:p,channelUnread:f}=(0,y.useMemo)(()=>{if(!e)return{dmUnread:0,channelUnread:0};let h=new Set(e.filter(g=>g.isDm).map(g=>g.id)),v=0,m=0;return d.forEach((g,S)=>{h.has(S)?v+=g:m+=g}),{dmUnread:v,channelUnread:m}},[e,d]);return{unreadByChannel:d,totalUnread:l,dmUnread:p,channelUnread:f,isLoading:i,isFetching:a,error:u,refetch:c}}function Ho(){let t=K();return ke({mutationFn:e=>R("create",e),onSuccess:(e,n)=>{let r=n.parent_path;r&&t.invalidateQueries({queryKey:w.children(r)})}})}function Bo(){let t=K();return ke({mutationFn:e=>R("update",e),onSuccess:(e,n)=>{let r=n.path;if(r){t.invalidateQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function Wo(){return ke({mutationFn:t=>R("update-principal",t),onSuccess:(t,e)=>{if(!se)return;let n=t&&typeof t=="object"&&t.metadata?t.metadata:{...se.metadata??{},...typeof e.language=="string"?{language:e.language}:{},...typeof e.timezone=="string"?{timezone:e.timezone}:{},..."avatar_file_id"in e?{avatar_file_id:e.avatar_file_id}:{}};se={...se,displayName:typeof e.display_name=="string"?e.display_name:se.displayName,metadata:n},tc()}})}function $o(){let t=K();return ke({mutationFn:e=>R("delete",e),onSuccess:(e,n)=>{let r=n.path;if(r){t.removeQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function Go(){let t=K();return ke({mutationFn:e=>R("move",e),onSuccess:(e,n)=>{let r=n.path,s=n.new_parent_path;if(r){t.invalidateQueries({queryKey:w.item(r)});let i=r.split("/");i.pop();let a=i.join("/");a&&t.invalidateQueries({queryKey:w.children(a)})}s&&t.invalidateQueries({queryKey:w.children(s)})}})}function zo(){let t=K();return ke({mutationFn:e=>R("link",e),onSuccess:(e,n)=>{let r=n.source_id,s=n.target_id;r&&t.invalidateQueries({queryKey:w.edges(r)}),s&&t.invalidateQueries({queryKey:w.edges(s)})}})}function Jo(t,e){let n=K(),{optimistic:r,...s}=e??{};return ke({mutationFn:i=>R(t,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,u=>r.update(u,i)),{previous:a}}:void 0,onError:(i,a,u)=>{r&&u?.previous!==void 0&&n.setQueryData(r.queryKey,u.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Yo(t,e,n){let r,s,i,a=!0;if(typeof t=="string")r=t,s=e,i=n;else{s=t;let d=e;r=d.eventType,i=d.filter,a=d.enabled??!0}let u=(0,y.useRef)(s),c=(0,y.useRef)(i);(0,y.useEffect)(()=>{u.current=s,c.current=i},[s,i]),(0,y.useEffect)(()=>a?ue(r,l=>u.current(l),c.current?l=>c.current(l):void 0):void 0,[r,a])}function Xo(t){let{queryKey:e,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=t,u=K(),c=(0,y.useRef)(null),d=k({queryKey:e,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let l=ue(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{u.invalidateQueries({queryKey:e})},a)},s);return()=>{l(),c.current&&clearTimeout(c.current)}},[r,i,a,u,JSON.stringify(e)]),d}function Zo(t){N();let e=(0,y.useMemo)(()=>t?typeof t=="string"?{path:t}:t:null,[typeof t=="string"?t:JSON.stringify(t)]),n=!!e&&!!(e.key||e.path||e.item_id),r=e?.key??e?.path??e?.item_id??"",s=k({queryKey:["vfs",le()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!e)return null;let l=await R("resolve-arrangement",e);return l?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",l?.error),null):l??null},enabled:n}),i=s.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),u=i?.resolution_level??null,c=(0,y.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),d=(0,y.useCallback)(l=>{if(!c||!l?.length)return l??[];let p=m=>m.id??m.name??"",f=new Map(c.map((m,g)=>[m,g])),h=[],v=[];for(let m of l)(f.has(p(m))?h:v).push(m);return h.sort((m,g)=>f.get(p(m))-f.get(p(g))),[...h,...v]},[c]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:u,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:d}}function sc(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ic(t,e){return e&&e.length>0?"select":t==="boolean"?"toggle":t==="integer"||t==="number"?"range":t==="string"?"text":"none"}function oc(t,e){return!(t==="object"||t==="array")}function ac(t){return["string","number","integer","boolean"].includes(t)}function cc(t){return t!=="object"&&t!=="array"}function ea(t,e,n,r){let s=t?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,u]of Object.entries(s)){let c=u.type||"string",d=u.enum,l=oc(c,d),p=ac(c),f=ic(c,d);i.push({key:a,label:u.title||sc(a),type:c,description:u.description,enum_values:d,default_value:n[a]??r[a]??u.default,editable:e,filterable:l,sortable:p,filter_widget:f})}return i}function ps(t){let e=t.default_data||{},n=t.field_defaults||{},r=ea(t.input_schema,!0,e,n),s=ea(t.system_schema,!1,e,n),i=[...r,...s],a=i.filter(d=>cc(d.type)),u=i.filter(d=>d.filterable),c=i.filter(d=>d.sortable);return{fields:i,columns:a,filterable:u,sortable:c,form_fields:r,system_fields:s}}function ta(t){return{field:"updated_at",direction:"desc"}}function na(t){let e=ps(t),n=new Set(t.input_schema?.required||[]);return e.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var te=B(ce(),1);var uc=0;function lc(){return`upload_${Date.now()}_${++uc}`}async function ra(t,e,n,r){let s=e.name||(t instanceof File?t.name:`file-${Date.now()}`),i=t.type||"application/octet-stream",a=e.itemType||"file",c=await R("create",{parent_path:e.parentPath,item_type:a,name:s,type_data:{...e.typeData||{},file_source:{type:"upload",content_type:i}}});if(!c.id)throw new Error(c.error||c.message||"Failed to create file item");let d=c.id,l=c.path;if(c.storage_completed&&c.file_ref)return{itemId:d,itemPath:l,fileRef:c.file_ref};let p=c.storage_key,f=c.upload_token,h=c.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!p)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await dc(h,p,f,t,i,n,r);let v=await sa(d,p,i);return{itemId:d,itemPath:l,fileRef:v}}function dc(t,e,n,r,s,i,a){return new Promise((u,c)=>{let d=new XMLHttpRequest;if(d.open("PUT",`${t}/upload`),d.setRequestHeader("X-Storage-Key",e),d.setRequestHeader("Content-Type",s),n&&d.setRequestHeader("X-Upload-Token",n),d.upload.onprogress=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.total*100))},d.onload=()=>{d.status>=200&&d.status<300?u():c(new Error(`Storage upload failed: HTTP ${d.status} \u2014 ${d.responseText?.slice(0,300)}`))},d.onerror=()=>c(new Error("Storage upload network error")),d.ontimeout=()=>c(new Error("Storage upload timed out")),a){if(a.aborted){c(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{d.abort(),c(new Error("Upload cancelled"))})}d.send(r)})}async function sa(t,e,n){let r=await Pe(),s=await fetch(`${De}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:t,storage_key:e,content_type:n})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${a.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function ia(){let[t,e]=(0,te.useState)([]),n=K(),r=(0,te.useRef)(t);r.current=t;let s=(0,te.useCallback)((m,g)=>{e(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,te.useCallback)(m=>{e(g=>[...g,m])},[]),a=(0,te.useCallback)(async(m,g,S,C,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",H=S.itemType||"file",lt=x?.itemId||null,ne=x?.itemPath||null,Q=x?.storageKey||null,J=x?.uploadToken||null,me=x?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let T=await R("create",{parent_path:S.parentPath,item_type:H,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!T.id)throw Object.assign(new Error(T.error||T.message||"Failed to create file item"),{_step:"create"});if(lt=T.id,ne=T.path,s(m,{itemId:lt,itemPath:ne}),T.storage_completed&&T.file_ref){s(m,{status:"complete",progress:100,fileRef:T.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=T.storage_key,J=T.upload_token||"",me=T.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:Q,_uploadToken:J,_storageWorkerUrl:me}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((T,Je)=>{let $=new XMLHttpRequest;s(m,{_xhr:$}),$.open("PUT",`${me}/upload`),$.setRequestHeader("X-Storage-Key",Q),$.setRequestHeader("Content-Type",L),J&&$.setRequestHeader("X-Upload-Token",J),$.upload.onprogress=jt=>{jt.lengthComputable&&s(m,{progress:Math.round(jt.loaded/jt.total*100)})},$.onload=()=>{$.status>=200&&$.status<300?T():Je(Object.assign(new Error(`Storage upload failed: HTTP ${$.status}`),{_step:"upload"}))},$.onerror=()=>Je(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),$.ontimeout=()=>Je(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),$.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let ge=await sa(lt,Q,L);s(m,{status:"complete",fileRef:ge}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(ge){let ye=ge?.message||String(ge),T=ge?._step||"create";s(m,{status:"error",error:ye,_failedAt:T,_xhr:null})}},[s,n]),u=(0,te.useCallback)((m,g)=>{let S=lc();i({id:S,file:m,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,m,g)},[i,a]),c=(0,te.useCallback)((m,g)=>{for(let S of m)u(S,g)},[u]),d=(0,te.useCallback)(m=>{let g=r.current.find(x=>x.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(m,g.file,g.options,S,C)},[a]),l=(0,te.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,te.useCallback)(m=>{e(g=>g.filter(S=>S.id!==m))},[]),f=(0,te.useCallback)(()=>{e(m=>m.filter(g=>g.status!=="complete"))},[]),h=t.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),v=t.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:x,...U})=>U);return{upload:u,uploadMultiple:c,uploads:v,retryUpload:d,cancelUpload:l,removeUpload:p,clearCompleted:f,isUploading:h}}var oa=B(ce(),1);async function hs(t,e){return await R("resolve-items",{context_id:t,item_type:e})}function aa(t,e){return(0,oa.useSyncExternalStore)(Xe,_e,_e),k({queryKey:["vfs",le()??"__unscoped__","resolved-items",t??"",e],queryFn:()=>hs(t,e),enabled:!!(t&&e)})}var he=B(ce(),1);function yr(t,e){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let c,d=a.name;if(typeof d=="string"&&d.startsWith("{"))try{c=JSON.parse(d)}catch{return}else if(a.artifact_id)c=a;else return;switch(c.type){case"artifact_opened":{let l=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:l,completed_at:null}),r.has(c.tool_id)){let p=r.get(c.tool_id);n.timeline[p].artifact_ids.push(c.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:l,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,p)}break}case"artifact_delta":{let l=n.artifacts.get(c.artifact_id);l&&(l.content+=c.content_delta,l.total_chars+=c.content_delta.length,l.delta_count+=1,c.target_uri&&!l.target_uri&&(l.target_uri=c.target_uri));break}case"artifact_done":{let l=n.artifacts.get(c.artifact_id);l&&(l.status=c.status,l.total_chars=c.total_chars,l.artifact_item_uri=c.artifact_item_uri,l.evidence_uri=c.evidence_uri,c.target_uri&&(l.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(l.completed_at=Date.now()));let p=r.get(c.tool_id);if(p!==void 0){let f=n.timeline[p];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}e(n)}return lr(t,s)}function ca(t,e=!0){let[n,r]=(0,he.useState)(new Map),[s,i]=(0,he.useState)([]),a=(0,he.useRef)({artifacts:new Map,timeline:[]});(0,he.useEffect)(()=>!t||!e?void 0:yr(t,p=>{a.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[t,e]);let u=(0,he.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,d=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:d,reset:u}}function ua(t,e=!0){let[n,r]=(0,he.useState)([]);(0,he.useEffect)(()=>!t||!e?void 0:yr(t,a=>{r([...a.timeline])}),[t,e]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}Ao(ms);return _a(ms);})();
4
4
 
5
5
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
6
6
  (function() {