@ai4b-team/fsaos-gateway-sdk 5.4.0 → 5.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-13T01:15:04.394Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var jn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?jn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)jn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&jn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?jn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(jn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var $n=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=Bn((Qf,lo)=>{lo.exports=React});var Lr=Bn((Fm,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=Bn((dg,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=Bn((Tg,Oa)=>{Oa.exports=ReactDOM});var Ju=Bn((Iy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>Hn,GatewayRequestError:()=>ge,HostSessionUnavailableError:()=>Kt,InteractionTrackingError:()=>Kn,KernelProvider:()=>gu,QueryClientProvider:()=>rr,acceptInvitation:()=>wf,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>cr,awaitScopeReady:()=>ha,callTool:()=>rl,cancelInvitation:()=>xf,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>bi,configureGatewayReads:()=>Ia,connectHostSession:()=>_a,createAgent:()=>Zi,createInvitation:()=>vf,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Dt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>br,fetchChannelMessagesWithCards:()=>_s,fetchEdgesForItem:()=>ps,fetchItemHistory:()=>hs,fetchItemVersions:()=>_r,fetchItems:()=>Bt,fetchMemberFocus:()=>ys,fetchOpenEnvelope:()=>vr,fetchRecentActivity:()=>gs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>fs,fetchVfsChildren:()=>yr,fetchVfsChildrenPage:()=>ds,fetchVfsItem:()=>hr,fetchVfsItemById:()=>gr,fetchVfsTree:()=>ms,gatewayCall:()=>x,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>gi,getAssetUrl:()=>il,getDefaultSort:()=>gl,getHomeAnchor:()=>me,getInvitation:()=>bf,getMountVersion:()=>ur,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>hl,getScope:()=>W,getScopeVersion:()=>ne,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>vt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>$t,initializeFsaos:()=>ju,initializeWorkspace:()=>ks,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>hc,invalidateChildren:()=>ls,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>gc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>he,isListableItemsFilter:()=>On,isScopeReady:()=>Gr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,listInvitations:()=>Pf,loadMounts:()=>Vt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>us,pathSubscriptionMatches:()=>Ti,personalSectionsKey:()=>kr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>be,registerCleanup:()=>se,rejectInvitation:()=>Sf,replaceMounts:()=>xs,resendInvitation:()=>Rf,resetAllSdkState:()=>Rn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Pr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Pa,serverMsUntil:()=>Ca,serverNow:()=>Yr,setAnchor:()=>xn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ga,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>As,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>hi,subscribeArtifactStream:()=>Ms,subscribeMounts:()=>Wr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>cs,subscribeToScope:()=>Mn,trackAction:()=>Ku,trackEvent:()=>Gt,trackPageView:()=>Uu,unmountRealtimeScope:()=>ws,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Is,useAnswerInput:()=>pl,useArrangement:()=>Dn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Es,useChannelMessages:()=>hu,useChannels:()=>vu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Pu,useDmChannels:()=>bu,useEdges:()=>Hc,useEventStream:()=>Tu,useFileUpload:()=>bl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Cu,useMutation:()=>Iu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Tl,usePinnedItems:()=>Cl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Pl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Cs,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>C,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,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 Un=Y(ue(),1);var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Ct,at,Jt,fo,Hl=(fo=class extends Ee{constructor(){super();I(this,Ct);I(this,at);I(this,Jt);S(this,Jt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Jt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Jt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,Ct)!==t&&(S(this,Ct,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,Ct)=="boolean"?d(this,Ct):globalThis.document?.visibilityState!=="hidden"}},Ct=new WeakMap,at=new WeakMap,Jt=new WeakMap,fo),Yt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){I(this,ct,jl);I(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Vn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Or(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Wn(o,t.options))return!1}else if(!Et(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function Fr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Et(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Wn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Et(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Et(e[n],t[n])):!1}var $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=go(e)&&go(t);if(!r&&!(Ks(e)&&Ks(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let f=r?l:o[l],m=e[f],p=t[f];if(m===p){c[f]=m,(r?l<i:$l.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let h=Hs(m,p,n+1);c[f]=h,h===m&&u++}return i===a&&u===i?e:c}function Zt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function go(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!ho(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ho(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ho(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function Gn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function vo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function bo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Xt=Symbol();function qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function en(e,t){return typeof e=="function"?e(...t):!!e}function wo(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function zn(){let e,t,n=new Promise((s,i)=>{e=s,t=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}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var So=mo;function Vl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=So,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=Vl();var tn,ut,nn,xo,Wl=(xo=class extends Ee{constructor(){super();I(this,tn,!0);I(this,ut);I(this,nn);S(this,nn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){d(this,ut)||this.setEventListener(d(this,nn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,nn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,tn)!==t&&(S(this,tn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,tn)}},tn=new WeakMap,ut=new WeakMap,nn=new WeakMap,xo),rn=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?rn.isOnline():!0}var Nr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Qr(e){let t=!1,n=0,r,s=zn(),i=()=>s.status!=="pending",o=_=>{if(!i()){let g=new Nr(_);m(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Yt.isFocused()&&(e.networkMode==="always"||rn.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=_=>{i()||(r?.(),s.resolve(_))},m=_=>{i()||(r?.(),s.reject(_))},p=()=>new Promise(_=>{r=g=>{(i()||u())&&_(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),h=()=>{if(i())return;let _,g=n===0?e.initialPromise:void 0;try{_=g??e.fn()}catch(y){_=Promise.reject(y)}Promise.resolve(_).then(f).catch(y=>{if(i())return;let b=e.retry??(Ke.isServer()?0:3),P=e.retryDelay??Gl,E=typeof P=="function"?P(n,y):P,w=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,y);if(t||!w){m(y);return}n++,e.onFail?.(n,y),_o(E).then(()=>u()?void 0:p()).then(()=>{t?m(y):h()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?h():p().then(h),s)}}var It,Ro,Dr=(Ro=class{constructor(){I(this,It)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vn(this.gcTime)&&S(this,It,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,It)!==void 0&&(De.clearTimeout(d(this,It)),S(this,It,void 0))}},It=new WeakMap,Ro);var Tt,sn,Ie,At,oe,Jn,kt,Se,To,We,Eo,Io=(Eo=class extends Dr{constructor(t){super();I(this,Se);I(this,Tt);I(this,sn);I(this,Ie);I(this,At);I(this,oe);I(this,Jn);I(this,kt);S(this,kt,!1),S(this,Jn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,At,t.client),S(this,Ie,d(this,At).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,Tt,Co(this.options)),this.state=t.state??d(this,Tt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Jn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Co(this.options);n.data!==void 0&&(this.setState(Po(n.data,n.dataUpdatedAt)),S(this,Tt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=Gn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,Tt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Mr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,kt)||F(this,Se,To).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,kt,!0),r.signal)})},i=()=>{let c=qr(this.options,n),l=(()=>{let f={client:d(this,At),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,kt,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,At),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,sn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Qr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Nr&&c.revert&&this.setState({...d(this,sn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Nr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Tt=new WeakMap,sn=new WeakMap,Ie=new WeakMap,At=new WeakMap,oe=new WeakMap,Jn=new WeakMap,kt=new WeakMap,Se=new WeakSet,To=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Po(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,sn,t.manual?s:void 0),s;case"error":let i=t.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,...t.state}}};this.state=n(this.state),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Po(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Co(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,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 _e,D,Zn,pe,Mt,on,Ge,lt,Xn,an,cn,Ot,Ft,dt,un,H,Yn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,er=(Mo=class extends Ee{constructor(t,n){super();I(this,H);I(this,_e);I(this,D);I(this,Zn);I(this,pe);I(this,Mt);I(this,on);I(this,Ge);I(this,lt);I(this,Xn);I(this,an);I(this,cn);I(this,Ot);I(this,Ft);I(this,dt);I(this,un,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,zn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,D).addObserver(this),Ao(d(this,D),this.options)?F(this,H,Yn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,D),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,D),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,D).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,D);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,D))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,D).setOptions(this.options),n._defaulted&&!Zt(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,D),observer:this});let s=this.hasListeners();s&&ko(d(this,D),r,this.options,n)&&F(this,H,Yn).call(this),this.updateResult(),s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||qe(this.options.staleTime,d(this,D))!==qe(n.staleTime,d(this,D)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,on,this.options),S(this,Mt,d(this,D).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,un).add(t)}getCurrentQuery(){return d(this,D)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Yn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,D),s=this.options,i=d(this,pe),o=d(this,Mt),a=d(this,on),u=t!==r?t.state:d(this,Zn),{state:l}=t,f={...l},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&Ao(t,n),T=A&&ko(t,r,n,s);(k||T)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:h,errorUpdatedAt:_,status:g}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,y=!0):A=typeof n.placeholderData=="function"?n.placeholderData(d(this,cn)?.state.data,d(this,cn)):n.placeholderData,A!==void 0&&(g="success",p=Gn(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===d(this,Xn))p=d(this,an);else try{S(this,Xn,n.select),p=n.select(p),p=Gn(i?.data,p,n),S(this,an,p),S(this,lt,null)}catch(A){S(this,lt,A)}d(this,lt)&&(h=d(this,lt),p=d(this,an),_=Date.now(),g="error");let b=f.fetchStatus==="fetching",P=g==="pending",E=g==="error",w=P&&b,O=p!==void 0,R={status:g,fetchStatus:f.fetchStatus,isPending:P,isSuccess:g==="success",isError:E,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:f.dataUpdatedAt,error:h,errorUpdatedAt:_,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!P,isLoadingError:E&&!O,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:E&&O,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=R.data!==void 0,k=R.status==="error"&&!A,T=U=>{k?U.reject(R.error):A&&U.resolve(R.data)},M=()=>{let U=S(this,Ge,R.promise=zn());T(U)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&T(q);break;case"fulfilled":(k||R.data!==q.value)&&M();break;case"rejected":(!k||R.error!==q.reason)&&M();break}}return R}updateResult(){let t=d(this,pe),n=this.createResult(d(this,D),this.options);if(S(this,Mt,d(this,D).state),S(this,on,this.options),d(this,Mt).data!==void 0&&S(this,cn,d(this,D)),Zt(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,un).size)return!0;let o=new Set(i??d(this,un));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,D=new WeakMap,Zn=new WeakMap,pe=new WeakMap,Mt=new WeakMap,on=new WeakMap,Ge=new WeakMap,lt=new WeakMap,Xn=new WeakMap,an=new WeakMap,cn=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,dt=new WeakMap,un=new WeakMap,H=new WeakSet,Yn=function(t){F(this,H,Ys).call(this);let n=d(this,D).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,D));if(Ke.isServer()||d(this,pe).isStale||!Vn(t))return;let r=Mr(d(this,pe).dataUpdatedAt,t)+1;S(this,Ot,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,D)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,D))===!1||!Vn(d(this,dt))||d(this,dt)===0)&&S(this,Ft,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Yt.isFocused())&&F(this,H,Yn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,Ot)!==void 0&&(De.clearTimeout(d(this,Ot)),S(this,Ot,void 0))},Js=function(){d(this,Ft)!==void 0&&(De.clearInterval(d(this,Ft)),S(this,Ft,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,D))return;let n=d(this,D);S(this,D,t),S(this,Zn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,D),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!Zt(e.getCurrentResult(),t)}function ln(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,f=h=>{wo(h,()=>t.signal,()=>l=!0)},m=qr(t.options,t.fetchOptions),p=async(h,_,g)=>{if(l)return Promise.reject();if(_==null&&h.pages.length)return Promise.resolve(h);let b=(()=>{let O={client:t.client,queryKey:t.queryKey,pageParam:_,direction:g?"backward":"forward",meta:t.options.meta};return f(O),O})(),P=await m(b),{maxPages:E}=t.options,w=g?bo:vo;return{pages:w(h.pages,P,E),pageParams:w(h.pageParams,_,E)}};if(s&&i.length){let h=s==="backward",_=h?Fo:ei,g={pages:i,pageParams:o},y=_(r,g);a=await p(g,y,h)}else{let h=e??i.length;do{let _=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&_==null)break;a=await p(a,_),c++}while(c<h)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ei(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends er{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:ln()})}getOptimisticResult(e){return e.behavior=ln(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",f=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!m}}};var tr,Le,le,qt,He,ft,Qo,Do=(Qo=class extends Dr{constructor(t){super();I(this,He);I(this,tr);I(this,Le);I(this,le);I(this,qt);S(this,tr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,tr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,qt,Qr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,le).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},tr=new WeakMap,Le=new WeakMap,le=new WeakMap,qt=new WeakMap,He=new WeakSet,ft=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,nr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();I(this,ze);I(this,Ne);I(this,nr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,nr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++$n(this,nr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Ur(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Ur(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){return this.getAll().filter(n=>Fr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,nr=new WeakMap,Uo);function Ur(e){return e.options.scope?.id}var Je,pt,ve,Ye,Ze,Kr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();I(this,Ze);I(this,Je);I(this,pt);I(this,ve);I(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Kr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),Zt(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,ve),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,ve)?.state.status==="pending"&&d(this,ve).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,ve)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,ve)?.removeObserver(this),S(this,ve,void 0),F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,ve)?.removeObserver(this),S(this,ve,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,ve).addObserver(this),d(this,ve).execute(t)}},Je=new WeakMap,pt=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Kr=function(){let t=d(this,ve)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Wn(s,n),o=this.get(i);return o||(o=new Io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Or(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Or(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,gt,dn,fn,ht,pn,mn,Bo,ii=(Bo=class{constructor(e={}){I(this,X);I(this,mt);I(this,gt);I(this,dn);I(this,fn);I(this,ht);I(this,pn);I(this,mn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,gt,e.defaultOptions||{}),S(this,dn,new Map),S(this,fn,new Map),S(this,ht,0)}mount(){$n(this,ht)._++,d(this,ht)===1&&(S(this,pn,Yt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,mn,rn.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;$n(this,ht)._--,d(this,ht)===0&&((e=d(this,pn))==null||e.call(this),S(this,pn,void 0),(t=d(this,mn))==null||t.call(this),S(this,mn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=ln(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=ln(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return rn.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,gt)}setDefaultOptions(e){S(this,gt,e)}setQueryDefaults(e,t){d(this,dn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,dn).values()],n={};return t.forEach(r=>{Et(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,fn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,fn).values()],n={};return t.forEach(r=>{Et(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...d(this,gt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Wn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,gt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,gt=new WeakMap,dn=new WeakMap,fn=new WeakMap,ht=new WeakMap,pn=new WeakMap,mn=new WeakMap,Bo);var gn=Y(ue(),1),Vo=Y(Lr(),1),oi=gn.createContext(void 0),L=e=>{let t=gn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rr=({client:e,children:t})=>(gn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var Hr=Y(ue(),1),Wo=Hr.createContext(!1),Go=()=>Hr.useContext(Wo),Nm=Wo.Provider;var sr=Y(ue(),1),Yl=Y(Lr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=sr.createContext(Zl()),zo=()=>sr.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?en(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||en(n,[e.error,r]));var ea=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function jr(e,t,n){let r=Go(),s=zo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(m=>{let p=f?u.subscribe(j.batchCalls(m)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return jr(e,er,t)}var Xe=Y(ue(),1);function te(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&en(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function ir(e,t){return jr(e,ti,t)}var ia=Y(sa(),1),hn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Nt=Array.isArray(hn.sources)?hn.sources:[],et=hn.hostSession===!0,ed=hn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=hn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=hn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var or=null,Br=0,oa,di,$r=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(or=t.access_token,Br=t.expires_at??Math.floor(Date.now()/1e3)+3600):(or=null,Br=0),$r||($r=!0,di())});setTimeout(()=>{$r||($r=!0,di())},5e3);function aa(e,t){or=e,Br=t??Math.floor(Date.now()/1e3)+3600}function fi(){or=null,Br=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,or}var bn=null,wn=null,ca=0,ci=new Set,pi,ar,Sn=!1;pi=new Promise(e=>{ar=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function xn(e){let t=typeof e=="string"?e:e.path,n=bn!==t||wn?.id!==(typeof e=="string"?void 0:e.id);bn=t,wn=typeof e=="string"?null:e,typeof e!="string"&&!Qt.some(r=>r.id===e.id)&&(Qt=[...Qt,e],_i()),Sn||(Sn=!0,ar()),n&&mi()}function _t(){return bn}function de(){return wn}function gi(){return ca}function hi(e){return ci.add(e),()=>{ci.delete(e)}}function cr(){return pi}function yi(){return Sn}var Vr=null;function Dt(e,t={}){if(Vr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Vr=e,t.activate!==!1&&xn(e)}function me(){return Vr}var Qt=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Qt}function ur(){return ua}function Wr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Qt)!==JSON.stringify(e),r=bn!==t.path||wn?.id!==t.id;Qt=e,bn=t.path,wn=t,Sn||(Sn=!0,ar()),n&&_i(),r&&mi()}var _n=null,yn=null,vn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return vn}function vi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(_n)return _n;if(yn)return yn;let e=vn;return yn=(async()=>{let t=Ut(),n=await tt();if(e!==vn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==vn)throw new Error("Session changed during initialization");let o=i.entry||i;return _n={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},fa(),_n})().catch(t=>{throw e===vn&&(yn=null),t}),yn}function vt(){return _n}function bi(){vn++,_n=null,yn=null,bn=null,wn=null,Vr=null,Qt=[],fa()}var ma=[];function se(e){ma.push(e)}function Rn(){bi(),fi(),ar(),Sn=!1,pi=new Promise(e=>{ar=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ut(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ga=xn,W=_t,ne=gi,xe=hi,ha=cr,Gr=yi;var Lt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===Lt&&typeof e.kind=="string"}var Kt=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},zr=null,rd=0,Jr=new Map;function ya(){return zr||(zr=new Promise((e,t)=>{if(!et){t(new Kt("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Kt("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Kt("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&xn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Jr.get(a.id);c&&(Jr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:Lt,kind:"hello"},"*")}),zr)}async function _a(){let{item:e}=await ya();return{item:e}}async function va(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Jr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Jr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:Lt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,ba=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),ba=!0,wa=Date.now())}function Yr(){return Date.now()+Si}function Sa(){return ba}function xa(){return Si}function Ra(){return wa}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Yr()>=t}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Yr())}var Pn,ke=new Map,Ht=[],Ri=0,Pi={foreground:0,normal:1,background:2},Zr=()=>performance.now(),Ci=()=>new DOMException("Read cancelled","AbortError");function Ia(e={}){Pn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},es()}function Ta(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ci());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Ht.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Xr(e){return Array.isArray(e)?`[${e.map(Xr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Xr(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ci());if(!Pn)return r(n.signal);let s=ke.get(e);if(s)Pi[n.priority??"normal"]<Pi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Zr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Ht.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},Pn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ci()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return es(),o}function Ea(e){let t=Ht.indexOf(e);t>=0&&(Ht.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),es()}function es(){if(Pn)for(;Ri<Pn.concurrency&&Ht.length;){let e=r=>Pi[r.priority]-Math.floor((Zr()-r.queuedAt)/2e3);Ht.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ht.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Zr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{Pn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Zr()-t.startedAt),outcome:n})}catch{}es()})}}se(Ta);var sd=new Set(["list-memberships","init"]),ge=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Ut(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(cr(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=vt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let h=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),_=await h.text();if(r!==ae())throw new Error("Session changed during gateway request");let g=null;if(_)try{g=JSON.parse(_)}catch{}if(!h.ok||!g)throw new ge({method:e,status:h.status,statusText:h.statusText,payload:g,responseBody:_});if(g.success===!1){let y=g.error||"",b=g.denied_by||g.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new Fe(g):new ge({method:e,status:h.status,statusText:h.statusText,payload:g,responseBody:_})}return g&&g.server_now!==void 0&&xi(g.server_now),g};return Aa(e,u)?ka(Xr([r,i,c,e,u]),e,n,m):m(n.signal)}async function id(e,t,n){let r=await va(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new ge({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var v=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Lr(),1);var qa=new WeakMap;function be(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function he(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ts=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ts.get(e);r||(r=new Map,ts.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&be(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&rt(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ts.get(e)?.forEach(clearTimeout),ts.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var ns=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function ad(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function cd(e,t,n){if(od(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!he(n.path,r)&&!he(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ha(e,t){let n=ns.get(e);n||(n=new Map,ns.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!Ei(t))&&be(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var rs=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new rs}function bt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function Cn(e){return e instanceof rs||e instanceof Fe||e instanceof ge&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var C={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(bt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,En=null,Tn=null,lr=0,ld=3e4,Wa=1e4,kn=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,ss=0,is=null,za=!1;function fd(){fr(),ss=Date.now(),is=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-ss>dd){J("ping: no inbound traffic for",Date.now()-ss,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function fr(){is&&(clearInterval(is),is=null)}function pd(){typeof document>"u"||(document.hidden?fr():dr()&&(J("Tab visible, reconnecting..."),jt()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ti(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var An=[],it=new Map,In=new Map,Me=new Map;function gd(e){let t=In.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=gd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ii="disconnected",os=[];function as(e){if(Ii!==e){Ii=e;for(let t of[...os])try{t(e)}catch{}}}function hd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||An.length>0}function dr(){return it.size>0||Me.size>0}async function jt(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!dr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(En)return J("ensureConnection: connection already in flight, waiting..."),En;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return kn=!1,En=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),as("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,lr=0,as("connected"),vd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&bd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,fr(),yd(),as("disconnected"),!kn&&dr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{En=null}})(),En}function Za(){if(Tn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,lr)+Math.random()*1e3,ld);lr++,J("scheduleReconnect: attempt",lr,"in",Math.round(e),"ms"),Tn=setTimeout(()=>{Tn=null,dr()&&jt()},e)}function vd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:C.item(n.path)}),t.invalidateQueries({queryKey:C.children(n.path)});J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function bd(e){ss=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&hd(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ti(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of An)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(kn=!0,fr(),Q.close(),Q=null,kn=!1)}function cs(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),jt(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return An.push(...s),dr()&&jt(),()=>{for(let i of s){let o=An.indexOf(i);o!==-1&&An.splice(o,1)}ki()}}function Mn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=In.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),In.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),jt();let a=!0;return()=>{if(!a)return;a=!1;let c=In.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)In.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),kn=!0,fr(),Q&&(Q.close(),Q=null),Tn&&(clearTimeout(Tn),Tn=null),En=null,kn=!1,lr=0;for(let e of Object.keys(Re))delete Re[e];An.length=0,it.clear(),In.clear(),Me.clear(),Be.clear(),wt.clear(),as("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):(jt(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),jt())}function us(e){os.push(e);try{e(Ii)}catch{}return()=>{let t=os.indexOf(e);t!==-1&&os.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||oc(),updated_at:e.updated_at||oc(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function mr(e){return(e.content?.items||e.items||[]).map(Oe)}async function gr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(C.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(C.item(r.path),r),r}return null}catch{return null}}async function hr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function yr(e){try{let t=await x("list",{path:e,limit:200}),n=mr(t);for(let r of n)N().setQueryData(C.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Bt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function ds(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=mr(r);for(let i of s)N().setQueryData(C.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 ${e}:`,r),{items:[],total_hint:0}}}async function fs(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ps(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),source_item_id:e,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||ac(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function ms(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=mr(i);for(let a of o)N().setQueryData(C.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function gs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function _r(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,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 ${e}:`,i),{versions:[],total:0}}}async function hs(e,t=50,n=0){return _r(e,{limit:t,offset:n})}async function ys(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=mr(s);for(let o of i)N().setQueryData(C.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function vr(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("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}}function On(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Sd=["catalog","parent_only","internal"];function uc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Sd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return On(s)?{...s,...t}:null}async function Bt(e,t={}){if(e=bt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=mr(s);for(let o of i)N().setQueryData(C.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function xd(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function lc(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.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:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.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,origin:xd(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function pr(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_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((t,n)=>t.seq-n.seq)}async function dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return pr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function _s(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=pr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:pr(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function br(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:pr(i),activityMessages:pr(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ls(e){N().invalidateQueries({queryKey:C.children(e)})}function Oi(e){N().invalidateQueries({queryKey:C.item(e)})}function fc(e,t){Oi(e),ls(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ls(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:C.all()})}function gc(e){N().invalidateQueries({queryKey:C.types(e)})}function hc(e,t){e?N().invalidateQueries({queryKey:C.channelMessages(e,t)}):N().invalidateQueries({queryKey:C.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:C.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:C.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function vs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Fn=new Map,Sr=null,bs=null,St=new Map,_c=250,wr=new Map;function $t(e){if(Sr){qn(e);return}qn(e),Sr=ie("vfs_change",t=>Rd(t)),bs=ie("ccm_change",t=>Pd(t))}function qn(e){if(Fn.has(e))return;let t=Mn(e,["vfs_change","ccm_change"]);Fn.set(e,t)}function ws(e){let t=Fn.get(e);t&&(t(),Fn.delete(e))}function Fi(){for(let[,e]of Fn)e();Fn.clear(),Sr&&(Sr(),Sr=null),bs&&(bs(),bs=null),St.forEach(e=>clearTimeout(e)),St.clear(),wr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=wr.get(s);i||(i=new Map,wr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=wr.get(s);wr.delete(s),c&&Cd(s,c)},_c);St.set(s,a)}function Pd(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:C.edges(t)}),n&&N().invalidateQueries({queryKey:C.edges(n)})},_c);St.set(s,o)}function Cd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:C.item(s)}),n.removeQueries({queryKey:C.children(s)}),n.removeQueries({queryKey:C.tree(s)})):be(n,C.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:C.itemById(i.itemId)});n.invalidateQueries({queryKey:C.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Nn=null;se(()=>{Nn=null});function xt(e){if(e!==Nn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof ge&&e.payload?.error==="item_not_found"}function xr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function Rr(e){let t=me();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function vc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function bc(e,t,n){xt(e);let r=vc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();$t(me().id);for(let r of n)e.some(s=>s.id===r.id)||ws(r.id);for(let r of e)qn(r.id);la(e,t)}async function Vt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Nn&&Nn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Nn??(Nn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.loading?i.loading:i.ready?Ae():(i.resolve=t,i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?xr(i,n.initialAnchor):r,c=Rr(o?o.mounts.map(t).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=vc(c,u):n.initialAnchor&&await bc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function Ss(e){let t=Nn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await bc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return Ss(t=>({refs:Rr([...Ae(),xr(t,e)]),anchor:de()}))}function Sc(e){return Ss(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Rr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Pr(e){return Ss(t=>{let n=xr(t,e);return{refs:Rr([...Ae(),n]),anchor:n}})}function xs(e,t){return Ss(n=>{let r=Rr(e.map(i=>xr(n,i))),s=xr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Id,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Td,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Id(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Td(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Rs(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>he(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!he(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&he(e.path,i)})}var Rc=new WeakMap;function Pc(e,t,n){let r=Rc.get(e);r||(r=new Map,Rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,f=new Set,m=new Set,p=()=>e.getQueryData(t)??[],h=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,_()},250))},_=async()=>{if(a)return;u=!0;let E=l;l=!1;let w=[...f],O=new Set(m);m.clear(),f.clear();try{if(E)await be(e,t,{exact:!0});else{let R=(await Promise.allSettled(w.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let T=await x("read",{id:A});if(T.success===!1)throw new Error("Channel refresh failed");if(a||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let M=Oe(T.item??T);if(M.id!==A||M.item_type!=="channel")return;let q=p().find(Pe=>Pe.id===A);if(!q)return;let U=n({...M}),$={...q,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};O.has(A)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Pe=>Pe?.map(re=>re.id===A?$:re))}))).find(A=>A.status==="rejected");if(R?.status==="rejected")throw R.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(l||f.size)&&h()}},g=E=>p().some(w=>w.id===E.item_id||w.path===E.path)?!0:Rs(E),y=E=>{if(!g(E))return;let w=String(E.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(w))l=!0;else if(w==="update"){let O=p().find(K=>K.id===E.item_id||K.path===E.path);O&&(f.add(O.id),m.add(O.id))}(l||f.size)&&h()},b=E=>{let w=p().find(O=>O.id===E.parent_id);w&&(f.add(w.id),h())},P=["vfs_change","ccm_change"].flatMap(E=>[ie(E,y,w=>w.item_type==="channel"),ie(E,b,w=>w.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),P.forEach(E=>E())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function ee(){return(0,v.useSyncExternalStore)(xe,ne,ne)}function Mc(){return ee(),Gr()}function Oc(e){return ee(),B({queryKey:C.item(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return ee(),B({queryKey:C.itemById(e),queryFn:()=>gr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return ee(),B({queryKey:C.children(e),queryFn:()=>yr(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return ee(),B({queryKey:C.tree(e,t),queryFn:()=>ms(e,t),enabled:!!e})}function Qc(e,t){return ee(),B({queryKey:C.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){ee();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){ee();let t=bt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:C.items(n?.type??"",n),queryFn:({signal:s})=>Bt(n,{signal:s,throwOnError:!0}),enabled:On(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!Cn(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&Cn(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=ee(),{realtime:r=!1}=t,s=bt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=ir({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>Bt({...o,limit:i,offset:f},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,m,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:On(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!Cn(m)&&Mu(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&Cn(c.error))return[];if(!c.data?.pages)return[];let f=new Set,m=[];for(let p of c.data.pages)for(let h of p.items)h.id&&!f.has(h.id)&&(f.add(h.id),m.push(h));return m},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&Cn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Cc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!he(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function Kc(e,t={}){let n=Cc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),bt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),h=new Set(p.map(b=>b.id)),_=[...p,...r.allItems.filter(b=>!h.has(b.id))].filter(b=>!c.deleted.has(b.path)),g=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((b,P)=>y*String(b[g]??"").localeCompare(String(P[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,v.useRef)(u);l.current=u;let f=(0,v.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!Cc(e))return;let p=e,h=!1,_=!1,g=!1,y=0,b=new Map,P=()=>{let R=y;m.current().then(A=>{!h&&!A.isError&&y===R&&a({identity:i,upserts:{},deleted:new Set})})},E=R=>{y++,a(k=>{let T=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},M={...T.upserts};return delete M[R],{identity:i,upserts:M,deleted:new Set(T.deleted).add(R)}});let A=b.get("__reconcile__");A&&clearTimeout(A),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),P()},250))},w=R=>{let A=b.get(R);A&&clearTimeout(A),b.set(R,setTimeout(()=>{b.delete(R),s.fetchQuery({queryKey:C.item(R),queryFn:()=>hr(R),staleTime:0}).then(k=>{if(!h){if(!k||!Jd(k,p)){let T=l.current.find(M=>M.path===R||M.id===k?.id);T&&E(T.path);return}a(T=>{let M=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},q=new Set(M.deleted);return q.delete(R),{identity:i,upserts:{...M.upserts,[R]:k},deleted:q}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},O=ie("vfs_change",R=>{if(!R||typeof R.path!="string"&&typeof R.old_path!="string")return;let A=typeof R.path=="string"?R.path:R.old_path,k=l.current.find(M=>M.path===A||M.path===R.old_path||R.item_id&&M.id===R.item_id),T=!!k;if(!(!he(A,p.scope)&&!he(R.old_path,p.scope)&&!T)&&!(R.item_type&&R.item_type!==p.type&&!T)&&!(p.parent_id&&R.parent_id&&R.parent_id!==p.parent_id&&!T)){if(k&&(A!==k.path||R.old_path&&R.old_path!==A||R.parent_id&&R.parent_id!==k.parent_id||R.item_type&&R.item_type!==p.type)){E(k.path);return}if(!k&&R.old_path&&R.old_path!==A&&he(A,p.scope)){y++,w(A);return}if(R.action==="insert")y++,w(A);else if(R.action==="move")y++,w(A);else if(R.action==="update"){if(!f.current?.(R,l.current))return;y++,w(A)}else R.action==="delete"&&E(k?.path??R.old_path??A)}}),K=us(R=>{if(R!=="connected"){_&&(g=!0);return}_=!0,g&&(g=!1,P())});return()=>{h=!0,O(),K(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){ee();let t=20,n=ir({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>ds(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));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 Hc(e){return ee(),B({queryKey:C.edges(e),queryFn:()=>ps(e),enabled:!!e})}function Cs(e){return ee(),B({queryKey:C.types(e),queryFn:()=>fs(e)})}function jc(e,t){let n=Cs(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){ee();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...C.openEnvelope(e,s),i],queryFn:async()=>{let o=await vr(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Ec={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 $c(e){let t=Cs(e),n=t.data??new Map;return(0,v.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(Ec).map(([p,h])=>({key:p,label:h})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return ee(),B({queryKey:C.memberFocus(e),queryFn:()=>ys(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:C.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>_r(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:C.itemHistory(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return ee(),B({queryKey:C.recentActivity(e,String(t),String(n)),queryFn:()=>gs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return nt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Yd=[];function Ic(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Yc(){let{user:e}=Es(),t=(0,v.useSyncExternalStore)(pa,vi,vi),n=vt()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Ic()){a(null);return}let b=!1;return nt().then(P=>{b||P.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(P=>{b||a(P instanceof Error?P:new Error(String(P)))}),()=>{b=!0}},[n,e?.id,t]);let c=B({queryKey:C.memberships(n??"anonymous"),queryFn:vs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,v.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),f=(0,v.useMemo)(()=>{let b=new Set(l.map(E=>E.accountId)),P=E=>!E.subordinateTo||!b.has(E.subordinateTo);return[...l].sort((E,w)=>Number(P(w))-Number(P(E)))},[l]),m=(0,v.useSyncExternalStore)(xe,ne,ne),p=(0,v.useMemo)(()=>{let b=de();return b?u.find(P=>P.accountId===b.id)??null:null},[m,u]),h=(0,v.useMemo)(()=>Zd(l),[l]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let b=f[0];me()||Dt($e(b)),$t(b.accountId),b.personalSpacePath&&Vt(b.personalSpacePath,P=>{let E=u.find(w=>w.accountId===P);return E?$e(E):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,v.useCallback)(async b=>{let P=u.find(O=>O.path===b);if(!P)throw new Error("Account membership is unavailable");let E=$e(P);me()||Dt(E);let w=u.find(O=>O.accountId===me()?.id);if(!w?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Vt(w.personalSpacePath,O=>{let K=u.find(R=>R.accountId===O);return K?$e(K):null}),await Pr(E),i(null),$t(P.accountId)},[u]),g=(0,v.useCallback)(async b=>{let P=u.find(E=>E.path===b);if(!P)throw new Error("Scope membership is unavailable");await qi($e(P))},[u]),y=(!!e?.id||Ic())&&!n&&!o;return{accounts:f,switcherAccounts:h,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:_,mountScope:g,loading:y||c.isLoading,error:o??c.error??s}}function Zc(){ee();let e=(0,v.useSyncExternalStore)(Wr,ur,ur),t=(0,v.useMemo)(()=>Ae(),[e]),n=de(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Pr,replaceMounts:xs,mount:qi,unmount:Sc}}function Es(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{V.auth.getSession().then(({data:p,error:h})=>{if(h){console.warn("[useAuth] getSession error, clearing stale session:",h.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=V.auth.onAuthStateChange((p,h)=>{if(p==="TOKEN_REFRESHED"&&!h){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(h),t(h?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let a=(0,v.useCallback)(async m=>m.provider?V.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:m.email,password:m.password}),[]),c=(0,v.useCallback)(async m=>V.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await V.auth.signOut(),Rn(),N().clear()},[]),l=(0,v.useCallback)(async m=>{let{error:p}=await V.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,v.useCallback)(async(m,p)=>{let{error:h}=await V.auth.signInWithOtp({email:m,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(h)throw h},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e){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(e))s(!0),x("resolve-asset",{asset_id:e}).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}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Ps={};se(()=>{for(let e of Object.keys(Ps))delete Ps[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;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}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Er={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Er[e];n||(n=Er[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Er[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Er[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Er[e]))}function ru(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-13T16:50:42.408Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var jn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?jn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)jn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&jn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?jn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(jn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var $n=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=Bn((Qf,lo)=>{lo.exports=React});var Lr=Bn((Fm,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=Bn((dg,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=Bn((Tg,Oa)=>{Oa.exports=ReactDOM});var Ju=Bn((Iy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>Hn,GatewayRequestError:()=>ge,HostSessionUnavailableError:()=>Kt,InteractionTrackingError:()=>Kn,KernelProvider:()=>gu,QueryClientProvider:()=>rr,acceptInvitation:()=>wf,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>cr,awaitScopeReady:()=>ha,callTool:()=>rl,cancelInvitation:()=>xf,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>bi,configureGatewayReads:()=>Ia,connectHostSession:()=>_a,createAgent:()=>Zi,createInvitation:()=>vf,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Dt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>br,fetchChannelMessagesWithCards:()=>_s,fetchEdgesForItem:()=>ps,fetchItemHistory:()=>hs,fetchItemVersions:()=>_r,fetchItems:()=>Bt,fetchMemberFocus:()=>ys,fetchOpenEnvelope:()=>vr,fetchRecentActivity:()=>gs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>fs,fetchVfsChildren:()=>yr,fetchVfsChildrenPage:()=>ds,fetchVfsItem:()=>hr,fetchVfsItemById:()=>gr,fetchVfsTree:()=>ms,gatewayCall:()=>x,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>gi,getAssetUrl:()=>il,getDefaultSort:()=>gl,getHomeAnchor:()=>me,getInvitation:()=>bf,getMountVersion:()=>ur,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>hl,getScope:()=>W,getScopeVersion:()=>ne,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>vt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>$t,initializeFsaos:()=>ju,initializeWorkspace:()=>ks,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>hc,invalidateChildren:()=>ls,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>gc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>he,isListableItemsFilter:()=>On,isScopeReady:()=>Gr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,listInvitations:()=>Pf,loadMounts:()=>Vt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>us,pathSubscriptionMatches:()=>Ti,personalSectionsKey:()=>kr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>be,registerCleanup:()=>se,rejectInvitation:()=>Sf,replaceMounts:()=>xs,resendInvitation:()=>Rf,resetAllSdkState:()=>Rn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Pr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Pa,serverMsUntil:()=>Ca,serverNow:()=>Yr,setAnchor:()=>xn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ga,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>As,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>hi,subscribeArtifactStream:()=>Ms,subscribeMounts:()=>Wr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>cs,subscribeToScope:()=>Mn,trackAction:()=>Ku,trackEvent:()=>Gt,trackPageView:()=>Uu,unmountRealtimeScope:()=>ws,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Is,useAnswerInput:()=>pl,useArrangement:()=>Dn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Es,useChannelMessages:()=>hu,useChannels:()=>vu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Pu,useDmChannels:()=>bu,useEdges:()=>Hc,useEventStream:()=>Tu,useFileUpload:()=>bl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Cu,useMutation:()=>Iu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Tl,usePinnedItems:()=>Cl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Pl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Cs,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>C,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,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 Un=Y(ue(),1);var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Ct,at,Jt,fo,Hl=(fo=class extends Ee{constructor(){super();I(this,Ct);I(this,at);I(this,Jt);S(this,Jt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Jt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Jt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,Ct)!==t&&(S(this,Ct,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,Ct)=="boolean"?d(this,Ct):globalThis.document?.visibilityState!=="hidden"}},Ct=new WeakMap,at=new WeakMap,Jt=new WeakMap,fo),Yt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){I(this,ct,jl);I(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Vn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Or(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Wn(o,t.options))return!1}else if(!Et(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function Fr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Et(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Wn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Et(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Et(e[n],t[n])):!1}var $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=go(e)&&go(t);if(!r&&!(Ks(e)&&Ks(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let f=r?l:o[l],m=e[f],p=t[f];if(m===p){c[f]=m,(r?l<i:$l.call(e,f))&&u++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[f]=p;continue}let h=Hs(m,p,n+1);c[f]=h,h===m&&u++}return i===a&&u===i?e:c}function Zt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function go(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!ho(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ho(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ho(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function Gn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function vo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function bo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Xt=Symbol();function qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function en(e,t){return typeof e=="function"?e(...t):!!e}function wo(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function zn(){let e,t,n=new Promise((s,i)=>{e=s,t=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}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var So=mo;function Vl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=So,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=Vl();var tn,ut,nn,xo,Wl=(xo=class extends Ee{constructor(){super();I(this,tn,!0);I(this,ut);I(this,nn);S(this,nn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){d(this,ut)||this.setEventListener(d(this,nn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,nn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,tn)!==t&&(S(this,tn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,tn)}},tn=new WeakMap,ut=new WeakMap,nn=new WeakMap,xo),rn=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?rn.isOnline():!0}var Nr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Qr(e){let t=!1,n=0,r,s=zn(),i=()=>s.status!=="pending",o=_=>{if(!i()){let g=new Nr(_);m(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Yt.isFocused()&&(e.networkMode==="always"||rn.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=_=>{i()||(r?.(),s.resolve(_))},m=_=>{i()||(r?.(),s.reject(_))},p=()=>new Promise(_=>{r=g=>{(i()||u())&&_(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),h=()=>{if(i())return;let _,g=n===0?e.initialPromise:void 0;try{_=g??e.fn()}catch(y){_=Promise.reject(y)}Promise.resolve(_).then(f).catch(y=>{if(i())return;let b=e.retry??(Ke.isServer()?0:3),P=e.retryDelay??Gl,E=typeof P=="function"?P(n,y):P,w=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,y);if(t||!w){m(y);return}n++,e.onFail?.(n,y),_o(E).then(()=>u()?void 0:p()).then(()=>{t?m(y):h()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?h():p().then(h),s)}}var It,Ro,Dr=(Ro=class{constructor(){I(this,It)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vn(this.gcTime)&&S(this,It,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,It)!==void 0&&(De.clearTimeout(d(this,It)),S(this,It,void 0))}},It=new WeakMap,Ro);var Tt,sn,Ie,At,oe,Jn,kt,Se,To,We,Eo,Io=(Eo=class extends Dr{constructor(t){super();I(this,Se);I(this,Tt);I(this,sn);I(this,Ie);I(this,At);I(this,oe);I(this,Jn);I(this,kt);S(this,kt,!1),S(this,Jn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,At,t.client),S(this,Ie,d(this,At).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,Tt,Co(this.options)),this.state=t.state??d(this,Tt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Jn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Co(this.options);n.data!==void 0&&(this.setState(Po(n.data,n.dataUpdatedAt)),S(this,Tt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=Gn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,Tt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Mr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,kt)||F(this,Se,To).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,kt,!0),r.signal)})},i=()=>{let c=qr(this.options,n),l=(()=>{let f={client:d(this,At),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,kt,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,At),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,sn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Qr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Nr&&c.revert&&this.setState({...d(this,sn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Nr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Tt=new WeakMap,sn=new WeakMap,Ie=new WeakMap,At=new WeakMap,oe=new WeakMap,Jn=new WeakMap,kt=new WeakMap,Se=new WeakSet,To=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Po(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,sn,t.manual?s:void 0),s;case"error":let i=t.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,...t.state}}};this.state=n(this.state),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Po(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Co(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,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 _e,D,Zn,pe,Mt,on,Ge,lt,Xn,an,cn,Ot,Ft,dt,un,H,Yn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,er=(Mo=class extends Ee{constructor(t,n){super();I(this,H);I(this,_e);I(this,D);I(this,Zn);I(this,pe);I(this,Mt);I(this,on);I(this,Ge);I(this,lt);I(this,Xn);I(this,an);I(this,cn);I(this,Ot);I(this,Ft);I(this,dt);I(this,un,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,zn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,D).addObserver(this),Ao(d(this,D),this.options)?F(this,H,Yn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,D),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,D),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,D).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,D);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,D))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,D).setOptions(this.options),n._defaulted&&!Zt(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,D),observer:this});let s=this.hasListeners();s&&ko(d(this,D),r,this.options,n)&&F(this,H,Yn).call(this),this.updateResult(),s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||qe(this.options.staleTime,d(this,D))!==qe(n.staleTime,d(this,D)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,D)!==r||ye(this.options.enabled,d(this,D))!==ye(n.enabled,d(this,D))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,on,this.options),S(this,Mt,d(this,D).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,un).add(t)}getCurrentQuery(){return d(this,D)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Yn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,D),s=this.options,i=d(this,pe),o=d(this,Mt),a=d(this,on),u=t!==r?t.state:d(this,Zn),{state:l}=t,f={...l},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),k=!A&&Ao(t,n),T=A&&ko(t,r,n,s);(k||T)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:h,errorUpdatedAt:_,status:g}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,y=!0):A=typeof n.placeholderData=="function"?n.placeholderData(d(this,cn)?.state.data,d(this,cn)):n.placeholderData,A!==void 0&&(g="success",p=Gn(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===o?.data&&n.select===d(this,Xn))p=d(this,an);else try{S(this,Xn,n.select),p=n.select(p),p=Gn(i?.data,p,n),S(this,an,p),S(this,lt,null)}catch(A){S(this,lt,A)}d(this,lt)&&(h=d(this,lt),p=d(this,an),_=Date.now(),g="error");let b=f.fetchStatus==="fetching",P=g==="pending",E=g==="error",w=P&&b,O=p!==void 0,R={status:g,fetchStatus:f.fetchStatus,isPending:P,isSuccess:g==="success",isError:E,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:f.dataUpdatedAt,error:h,errorUpdatedAt:_,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!P,isLoadingError:E&&!O,isPaused:f.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:E&&O,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=R.data!==void 0,k=R.status==="error"&&!A,T=U=>{k?U.reject(R.error):A&&U.resolve(R.data)},M=()=>{let U=S(this,Ge,R.promise=zn());T(U)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&T(q);break;case"fulfilled":(k||R.data!==q.value)&&M();break;case"rejected":(!k||R.error!==q.reason)&&M();break}}return R}updateResult(){let t=d(this,pe),n=this.createResult(d(this,D),this.options);if(S(this,Mt,d(this,D).state),S(this,on,this.options),d(this,Mt).data!==void 0&&S(this,cn,d(this,D)),Zt(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,un).size)return!0;let o=new Set(i??d(this,un));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,D=new WeakMap,Zn=new WeakMap,pe=new WeakMap,Mt=new WeakMap,on=new WeakMap,Ge=new WeakMap,lt=new WeakMap,Xn=new WeakMap,an=new WeakMap,cn=new WeakMap,Ot=new WeakMap,Ft=new WeakMap,dt=new WeakMap,un=new WeakMap,H=new WeakSet,Yn=function(t){F(this,H,Ys).call(this);let n=d(this,D).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,D));if(Ke.isServer()||d(this,pe).isStale||!Vn(t))return;let r=Mr(d(this,pe).dataUpdatedAt,t)+1;S(this,Ot,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,D)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,D))===!1||!Vn(d(this,dt))||d(this,dt)===0)&&S(this,Ft,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Yt.isFocused())&&F(this,H,Yn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,Ot)!==void 0&&(De.clearTimeout(d(this,Ot)),S(this,Ot,void 0))},Js=function(){d(this,Ft)!==void 0&&(De.clearInterval(d(this,Ft)),S(this,Ft,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,D))return;let n=d(this,D);S(this,D,t),S(this,Zn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,D),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!Zt(e.getCurrentResult(),t)}function ln(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,f=h=>{wo(h,()=>t.signal,()=>l=!0)},m=qr(t.options,t.fetchOptions),p=async(h,_,g)=>{if(l)return Promise.reject();if(_==null&&h.pages.length)return Promise.resolve(h);let b=(()=>{let O={client:t.client,queryKey:t.queryKey,pageParam:_,direction:g?"backward":"forward",meta:t.options.meta};return f(O),O})(),P=await m(b),{maxPages:E}=t.options,w=g?bo:vo;return{pages:w(h.pages,P,E),pageParams:w(h.pageParams,_,E)}};if(s&&i.length){let h=s==="backward",_=h?Fo:ei,g={pages:i,pageParams:o},y=_(r,g);a=await p(g,y,h)}else{let h=e??i.length;do{let _=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&_==null)break;a=await p(a,_),c++}while(c<h)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ei(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends er{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:ln()})}getOptimisticResult(e){return e.behavior=ln(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",f=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:m,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!m}}};var tr,Le,le,qt,He,ft,Qo,Do=(Qo=class extends Dr{constructor(t){super();I(this,He);I(this,tr);I(this,Le);I(this,le);I(this,qt);S(this,tr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,tr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,qt,Qr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,le).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},tr=new WeakMap,Le=new WeakMap,le=new WeakMap,qt=new WeakMap,He=new WeakSet,ft=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,nr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();I(this,ze);I(this,Ne);I(this,nr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,nr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++$n(this,nr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Ur(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Ur(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Ur(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){return this.getAll().filter(n=>Fr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,nr=new WeakMap,Uo);function Ur(e){return e.options.scope?.id}var Je,pt,ve,Ye,Ze,Kr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();I(this,Ze);I(this,Je);I(this,pt);I(this,ve);I(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Kr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),Zt(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,ve),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,ve)?.state.status==="pending"&&d(this,ve).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,ve)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,ve)?.removeObserver(this),S(this,ve,void 0),F(this,Ze,Kr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,ve)?.removeObserver(this),S(this,ve,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,ve).addObserver(this),d(this,ve).execute(t)}},Je=new WeakMap,pt=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Kr=function(){let t=d(this,ve)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Wn(s,n),o=this.get(i);return o||(o=new Io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Or(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Or(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,gt,dn,fn,ht,pn,mn,Bo,ii=(Bo=class{constructor(e={}){I(this,X);I(this,mt);I(this,gt);I(this,dn);I(this,fn);I(this,ht);I(this,pn);I(this,mn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,gt,e.defaultOptions||{}),S(this,dn,new Map),S(this,fn,new Map),S(this,ht,0)}mount(){$n(this,ht)._++,d(this,ht)===1&&(S(this,pn,Yt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,mn,rn.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;$n(this,ht)._--,d(this,ht)===0&&((e=d(this,pn))==null||e.call(this),S(this,pn,void 0),(t=d(this,mn))==null||t.call(this),S(this,mn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=ln(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=ln(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return rn.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,gt)}setDefaultOptions(e){S(this,gt,e)}setQueryDefaults(e,t){d(this,dn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,dn).values()],n={};return t.forEach(r=>{Et(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,fn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,fn).values()],n={};return t.forEach(r=>{Et(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...d(this,gt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Wn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,gt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,gt=new WeakMap,dn=new WeakMap,fn=new WeakMap,ht=new WeakMap,pn=new WeakMap,mn=new WeakMap,Bo);var gn=Y(ue(),1),Vo=Y(Lr(),1),oi=gn.createContext(void 0),L=e=>{let t=gn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rr=({client:e,children:t})=>(gn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var Hr=Y(ue(),1),Wo=Hr.createContext(!1),Go=()=>Hr.useContext(Wo),Nm=Wo.Provider;var sr=Y(ue(),1),Yl=Y(Lr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=sr.createContext(Zl()),zo=()=>sr.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?en(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||en(n,[e.error,r]));var ea=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function jr(e,t,n){let r=Go(),s=zo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(m=>{let p=f?u.subscribe(j.batchCalls(m)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return jr(e,er,t)}var Xe=Y(ue(),1);function te(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&en(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function ir(e,t){return jr(e,ti,t)}var ia=Y(sa(),1),hn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Nt=Array.isArray(hn.sources)?hn.sources:[],et=hn.hostSession===!0,ed=hn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=hn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=hn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var or=null,Br=0,oa,di,$r=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(or=t.access_token,Br=t.expires_at??Math.floor(Date.now()/1e3)+3600):(or=null,Br=0),$r||($r=!0,di())});setTimeout(()=>{$r||($r=!0,di())},5e3);function aa(e,t){or=e,Br=t??Math.floor(Date.now()/1e3)+3600}function fi(){or=null,Br=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,or}var bn=null,wn=null,ca=0,ci=new Set,pi,ar,Sn=!1;pi=new Promise(e=>{ar=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function xn(e){let t=typeof e=="string"?e:e.path,n=bn!==t||wn?.id!==(typeof e=="string"?void 0:e.id);bn=t,wn=typeof e=="string"?null:e,typeof e!="string"&&!Qt.some(r=>r.id===e.id)&&(Qt=[...Qt,e],_i()),Sn||(Sn=!0,ar()),n&&mi()}function _t(){return bn}function de(){return wn}function gi(){return ca}function hi(e){return ci.add(e),()=>{ci.delete(e)}}function cr(){return pi}function yi(){return Sn}var Vr=null;function Dt(e,t={}){if(Vr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Vr=e,t.activate!==!1&&xn(e)}function me(){return Vr}var Qt=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Qt}function ur(){return ua}function Wr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Qt)!==JSON.stringify(e),r=bn!==t.path||wn?.id!==t.id;Qt=e,bn=t.path,wn=t,Sn||(Sn=!0,ar()),n&&_i(),r&&mi()}var _n=null,yn=null,vn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return vn}function vi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(_n)return _n;if(yn)return yn;let e=vn;return yn=(async()=>{let t=Ut(),n=await tt();if(e!==vn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==vn)throw new Error("Session changed during initialization");let o=i.entry||i;return _n={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},fa(),_n})().catch(t=>{throw e===vn&&(yn=null),t}),yn}function vt(){return _n}function bi(){vn++,_n=null,yn=null,bn=null,wn=null,Vr=null,Qt=[],fa()}var ma=[];function se(e){ma.push(e)}function Rn(){bi(),fi(),ar(),Sn=!1,pi=new Promise(e=>{ar=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ut(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ga=xn,W=_t,ne=gi,xe=hi,ha=cr,Gr=yi;var Lt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===Lt&&typeof e.kind=="string"}var Kt=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},zr=null,rd=0,Jr=new Map;function ya(){return zr||(zr=new Promise((e,t)=>{if(!et){t(new Kt("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Kt("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Kt("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&xn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Jr.get(a.id);c&&(Jr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:Lt,kind:"hello"},"*")}),zr)}async function _a(){let{item:e}=await ya();return{item:e}}async function va(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Jr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Jr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:Lt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,ba=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),ba=!0,wa=Date.now())}function Yr(){return Date.now()+Si}function Sa(){return ba}function xa(){return Si}function Ra(){return wa}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Yr()>=t}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Yr())}var Pn,ke=new Map,Ht=[],Ri=0,Pi={foreground:0,normal:1,background:2},Zr=()=>performance.now(),Ci=()=>new DOMException("Read cancelled","AbortError");function Ia(e={}){Pn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},es()}function Ta(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ci());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Ht.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Xr(e){return Array.isArray(e)?`[${e.map(Xr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Xr(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ci());if(!Pn)return r(n.signal);let s=ke.get(e);if(s)Pi[n.priority??"normal"]<Pi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Zr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Ht.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},Pn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ci()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return es(),o}function Ea(e){let t=Ht.indexOf(e);t>=0&&(Ht.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),es()}function es(){if(Pn)for(;Ri<Pn.concurrency&&Ht.length;){let e=r=>Pi[r.priority]-Math.floor((Zr()-r.queuedAt)/2e3);Ht.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ht.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Zr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{Pn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Zr()-t.startedAt),outcome:n})}catch{}es()})}}se(Ta);var sd=new Set(["list-memberships","init"]),ge=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Ut(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(cr(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=vt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let m=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let h=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),_=await h.text();if(r!==ae())throw new Error("Session changed during gateway request");let g=null;if(_)try{g=JSON.parse(_)}catch{}if(!h.ok||!g)throw new ge({method:e,status:h.status,statusText:h.statusText,payload:g,responseBody:_});if(g.success===!1){let y=g.error||"",b=g.denied_by||g.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new Fe(g):new ge({method:e,status:h.status,statusText:h.statusText,payload:g,responseBody:_})}return g&&g.server_now!==void 0&&xi(g.server_now),g};return Aa(e,u)?ka(Xr([r,i,c,e,u]),e,n,m):m(n.signal)}async function id(e,t,n){let r=await va(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new ge({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var v=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Lr(),1);var qa=new WeakMap;function be(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function he(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ts=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ts.get(e);r||(r=new Map,ts.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&be(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&rt(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ts.get(e)?.forEach(clearTimeout),ts.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var ns=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function ad(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function cd(e,t,n){if(od(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!he(n.path,r)&&!he(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ha(e,t){let n=ns.get(e);n||(n=new Map,ns.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!Ei(t))&&be(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var rs=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new rs}function bt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function Cn(e){return e instanceof rs||e instanceof Fe||e instanceof ge&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var C={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(bt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,En=null,Tn=null,lr=0,ld=3e4,Wa=1e4,kn=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,ss=0,is=null,za=!1;function fd(){fr(),ss=Date.now(),is=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-ss>dd){J("ping: no inbound traffic for",Date.now()-ss,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function fr(){is&&(clearInterval(is),is=null)}function pd(){typeof document>"u"||(document.hidden?fr():dr()&&(J("Tab visible, reconnecting..."),jt()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ti(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var An=[],it=new Map,In=new Map,Me=new Map;function gd(e){let t=In.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=gd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ii="disconnected",os=[];function as(e){if(Ii!==e){Ii=e;for(let t of[...os])try{t(e)}catch{}}}function hd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||An.length>0}function dr(){return it.size>0||Me.size>0}async function jt(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!dr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(En)return J("ensureConnection: connection already in flight, waiting..."),En;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return kn=!1,En=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),as("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,lr=0,as("connected"),vd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&bd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,fr(),yd(),as("disconnected"),!kn&&dr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{En=null}})(),En}function Za(){if(Tn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,lr)+Math.random()*1e3,ld);lr++,J("scheduleReconnect: attempt",lr,"in",Math.round(e),"ms"),Tn=setTimeout(()=>{Tn=null,dr()&&jt()},e)}function vd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:C.item(n.path)}),t.invalidateQueries({queryKey:C.children(n.path)});t.invalidateQueries({queryKey:C.allChannelMessages()}),J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths and the transcripts on screen")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function bd(e){ss=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&hd(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ti(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of An)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(kn=!0,fr(),Q.close(),Q=null,kn=!1)}function cs(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),jt(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return An.push(...s),dr()&&jt(),()=>{for(let i of s){let o=An.indexOf(i);o!==-1&&An.splice(o,1)}ki()}}function Mn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=In.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),In.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),jt();let a=!0;return()=>{if(!a)return;a=!1;let c=In.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)In.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),kn=!0,fr(),Q&&(Q.close(),Q=null),Tn&&(clearTimeout(Tn),Tn=null),En=null,kn=!1,lr=0;for(let e of Object.keys(Re))delete Re[e];An.length=0,it.clear(),In.clear(),Me.clear(),Be.clear(),wt.clear(),as("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):(jt(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),jt())}function us(e){os.push(e);try{e(Ii)}catch{}return()=>{let t=os.indexOf(e);t!==-1&&os.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||oc(),updated_at:e.updated_at||oc(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function mr(e){return(e.content?.items||e.items||[]).map(Oe)}async function gr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(C.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(C.item(r.path),r),r}return null}catch{return null}}async function hr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function yr(e){try{let t=await x("list",{path:e,limit:200}),n=mr(t);for(let r of n)N().setQueryData(C.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Bt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function ds(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=mr(r);for(let i of s)N().setQueryData(C.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 ${e}:`,r),{items:[],total_hint:0}}}async function fs(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ps(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),source_item_id:e,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||ac(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function ms(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await x("tree",s),o=mr(i);for(let a of o)N().setQueryData(C.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function gs(e,t=50,n=0){try{let r=await x("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function _r(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("item-versions",{id:e,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 ${e}:`,i),{versions:[],total:0}}}async function hs(e,t=50,n=0){return _r(e,{limit:t,offset:n})}async function ys(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=mr(s);for(let o of i)N().setQueryData(C.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function vr(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await x("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}}function On(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Sd=["catalog","parent_only","internal"];function uc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Sd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return On(s)?{...s,...t}:null}async function Bt(e,t={}){if(e=bt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=mr(s);for(let o of i)N().setQueryData(C.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function xd(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function lc(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.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:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.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,origin:xd(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function pr(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_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((t,n)=>t.seq-n.seq)}async function dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return pr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function _s(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=pr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:pr(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function br(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:pr(i),activityMessages:pr(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ls(e){N().invalidateQueries({queryKey:C.children(e)})}function Oi(e){N().invalidateQueries({queryKey:C.item(e)})}function fc(e,t){Oi(e),ls(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ls(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:C.all()})}function gc(e){N().invalidateQueries({queryKey:C.types(e)})}function hc(e,t){e?N().invalidateQueries({queryKey:C.channelMessages(e,t)}):N().invalidateQueries({queryKey:C.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:C.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:C.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function vs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Fn=new Map,Sr=null,bs=null,St=new Map,_c=250,wr=new Map;function $t(e){if(Sr){qn(e);return}qn(e),Sr=ie("vfs_change",t=>Rd(t)),bs=ie("ccm_change",t=>Pd(t))}function qn(e){if(Fn.has(e))return;let t=Mn(e,["vfs_change","ccm_change"]);Fn.set(e,t)}function ws(e){let t=Fn.get(e);t&&(t(),Fn.delete(e))}function Fi(){for(let[,e]of Fn)e();Fn.clear(),Sr&&(Sr(),Sr=null),bs&&(bs(),bs=null),St.forEach(e=>clearTimeout(e)),St.clear(),wr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=wr.get(s);i||(i=new Map,wr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=wr.get(s);wr.delete(s),c&&Cd(s,c)},_c);St.set(s,a)}function Pd(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:C.edges(t)}),n&&N().invalidateQueries({queryKey:C.edges(n)})},_c);St.set(s,o)}function Cd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:C.item(s)}),n.removeQueries({queryKey:C.children(s)}),n.removeQueries({queryKey:C.tree(s)})):be(n,C.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:C.itemById(i.itemId)});n.invalidateQueries({queryKey:C.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Nn=null;se(()=>{Nn=null});function xt(e){if(e!==Nn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof ge&&e.payload?.error==="item_not_found"}function xr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function Rr(e){let t=me();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function vc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function bc(e,t,n){xt(e);let r=vc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();$t(me().id);for(let r of n)e.some(s=>s.id===r.id)||ws(r.id);for(let r of e)qn(r.id);la(e,t)}async function Vt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Nn&&Nn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Nn??(Nn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.resolve=t,i.loading?i.loading:i.ready?Ae():(i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?xr(i,n.initialAnchor):r,c=Rr(o?o.mounts.map(l=>i.resolve(l)).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=vc(c,u):n.initialAnchor&&await bc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function Ss(e){let t=Nn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await bc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return Ss(t=>({refs:Rr([...Ae(),xr(t,e)]),anchor:de()}))}function Sc(e){return Ss(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Rr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Pr(e){return Ss(t=>{let n=xr(t,e);return{refs:Rr([...Ae(),n]),anchor:n}})}function xs(e,t){return Ss(n=>{let r=Rr(e.map(i=>xr(n,i))),s=xr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Id,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Td,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Id(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Td(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Rs(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>he(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!he(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&he(e.path,i)})}var Rc=new WeakMap;function Pc(e,t,n){let r=Rc.get(e);r||(r=new Map,Rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,f=new Set,m=new Set,p=()=>e.getQueryData(t)??[],h=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,_()},250))},_=async()=>{if(a)return;u=!0;let E=l;l=!1;let w=[...f],O=new Set(m);m.clear(),f.clear();try{if(E)await be(e,t,{exact:!0});else{let R=(await Promise.allSettled(w.map(async A=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let T=await x("read",{id:A});if(T.success===!1)throw new Error("Channel refresh failed");if(a||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let M=Oe(T.item??T);if(M.id!==A||M.item_type!=="channel")return;let q=p().find(Pe=>Pe.id===A);if(!q)return;let U=n({...M}),$={...q,path:U.path,name:U.name,displayName:U.displayName,messageCount:U.messageCount,aiMode:U.aiMode,activeAgentIds:U.activeAgentIds,isPrivate:U.isPrivate,isDm:U.isDm,autoPilot:U.autoPilot,isArchived:U.isArchived,updatedAt:U.updatedAt};O.has(A)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Pe=>Pe?.map(re=>re.id===A?$:re))}))).find(A=>A.status==="rejected");if(R?.status==="rejected")throw R.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(l||f.size)&&h()}},g=E=>p().some(w=>w.id===E.item_id||w.path===E.path)?!0:Rs(E),y=E=>{if(!g(E))return;let w=String(E.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(w))l=!0;else if(w==="update"){let O=p().find(K=>K.id===E.item_id||K.path===E.path);O&&(f.add(O.id),m.add(O.id))}(l||f.size)&&h()},b=E=>{let w=p().find(O=>O.id===E.parent_id);w&&(f.add(w.id),h())},P=["vfs_change","ccm_change"].flatMap(E=>[ie(E,y,w=>w.item_type==="channel"),ie(E,b,w=>w.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),P.forEach(E=>E())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function ee(){return(0,v.useSyncExternalStore)(xe,ne,ne)}function Mc(){return ee(),Gr()}function Oc(e){return ee(),B({queryKey:C.item(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return ee(),B({queryKey:C.itemById(e),queryFn:()=>gr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return ee(),B({queryKey:C.children(e),queryFn:()=>yr(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return ee(),B({queryKey:C.tree(e,t),queryFn:()=>ms(e,t),enabled:!!e})}function Qc(e,t){return ee(),B({queryKey:C.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){ee();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){ee();let t=bt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:C.items(n?.type??"",n),queryFn:({signal:s})=>Bt(n,{signal:s,throwOnError:!0}),enabled:On(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!Cn(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&Cn(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=ee(),{realtime:r=!1}=t,s=bt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=ir({queryKey:a,queryFn:async({pageParam:f=0,signal:m})=>Bt({...o,limit:i,offset:f},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,m,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:On(o),...o?.spaceIds!==void 0?{retry:(f,m)=>!Cn(m)&&Mu(f,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&Cn(c.error))return[];if(!c.data?.pages)return[];let f=new Set,m=[];for(let p of c.data.pages)for(let h of p.items)h.id&&!f.has(h.id)&&(f.add(h.id),m.push(h));return m},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&Cn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Cc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!he(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function Kc(e,t={}){let n=Cc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),bt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),h=new Set(p.map(b=>b.id)),_=[...p,...r.allItems.filter(b=>!h.has(b.id))].filter(b=>!c.deleted.has(b.path)),g=e.sort_by??"updated_at",y=e.sort_dir==="asc"?1:-1;return _.sort((b,P)=>y*String(b[g]??"").localeCompare(String(P[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,v.useRef)(u);l.current=u;let f=(0,v.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!Cc(e))return;let p=e,h=!1,_=!1,g=!1,y=0,b=new Map,P=()=>{let R=y;m.current().then(A=>{!h&&!A.isError&&y===R&&a({identity:i,upserts:{},deleted:new Set})})},E=R=>{y++,a(k=>{let T=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},M={...T.upserts};return delete M[R],{identity:i,upserts:M,deleted:new Set(T.deleted).add(R)}});let A=b.get("__reconcile__");A&&clearTimeout(A),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),P()},250))},w=R=>{let A=b.get(R);A&&clearTimeout(A),b.set(R,setTimeout(()=>{b.delete(R),s.fetchQuery({queryKey:C.item(R),queryFn:()=>hr(R),staleTime:0}).then(k=>{if(!h){if(!k||!Jd(k,p)){let T=l.current.find(M=>M.path===R||M.id===k?.id);T&&E(T.path);return}a(T=>{let M=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},q=new Set(M.deleted);return q.delete(R),{identity:i,upserts:{...M.upserts,[R]:k},deleted:q}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},O=ie("vfs_change",R=>{if(!R||typeof R.path!="string"&&typeof R.old_path!="string")return;let A=typeof R.path=="string"?R.path:R.old_path,k=l.current.find(M=>M.path===A||M.path===R.old_path||R.item_id&&M.id===R.item_id),T=!!k;if(!(!he(A,p.scope)&&!he(R.old_path,p.scope)&&!T)&&!(R.item_type&&R.item_type!==p.type&&!T)&&!(p.parent_id&&R.parent_id&&R.parent_id!==p.parent_id&&!T)){if(k&&(A!==k.path||R.old_path&&R.old_path!==A||R.parent_id&&R.parent_id!==k.parent_id||R.item_type&&R.item_type!==p.type)){E(k.path);return}if(!k&&R.old_path&&R.old_path!==A&&he(A,p.scope)){y++,w(A);return}if(R.action==="insert")y++,w(A);else if(R.action==="move")y++,w(A);else if(R.action==="update"){if(!f.current?.(R,l.current))return;y++,w(A)}else R.action==="delete"&&E(k?.path??R.old_path??A)}}),K=us(R=>{if(R!=="connected"){_&&(g=!0);return}_=!0,g&&(g=!1,P())});return()=>{h=!0,O(),K(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){ee();let t=20,n=ir({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>ds(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));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 Hc(e){return ee(),B({queryKey:C.edges(e),queryFn:()=>ps(e),enabled:!!e})}function Cs(e){return ee(),B({queryKey:C.types(e),queryFn:()=>fs(e)})}function jc(e,t){let n=Cs(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){ee();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...C.openEnvelope(e,s),i],queryFn:async()=>{let o=await vr(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Ec={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 $c(e){let t=Cs(e),n=t.data??new Map;return(0,v.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(Ec).map(([p,h])=>({key:p,label:h})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return ee(),B({queryKey:C.memberFocus(e),queryFn:()=>ys(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:C.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>_r(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:C.itemHistory(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return ee(),B({queryKey:C.recentActivity(e,String(t),String(n)),queryFn:()=>gs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return nt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Yd=[];function Ic(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Yc(){let{user:e}=Es(),t=(0,v.useSyncExternalStore)(pa,vi,vi),n=vt()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Ic()){a(null);return}let b=!1;return nt().then(P=>{b||P.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(P=>{b||a(P instanceof Error?P:new Error(String(P)))}),()=>{b=!0}},[n,e?.id,t]);let c=B({queryKey:C.memberships(n??"anonymous"),queryFn:vs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,v.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),f=(0,v.useMemo)(()=>{let b=new Set(l.map(E=>E.accountId)),P=E=>!E.subordinateTo||!b.has(E.subordinateTo);return[...l].sort((E,w)=>Number(P(w))-Number(P(E)))},[l]),m=(0,v.useSyncExternalStore)(xe,ne,ne),p=(0,v.useMemo)(()=>{let b=de();return b?u.find(P=>P.accountId===b.id)??null:null},[m,u]),h=(0,v.useMemo)(()=>Zd(l),[l]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let b=f[0];me()||Dt($e(b)),$t(b.accountId),b.personalSpacePath&&Vt(b.personalSpacePath,P=>{let E=u.find(w=>w.accountId===P);return E?$e(E):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let _=(0,v.useCallback)(async b=>{let P=u.find(O=>O.path===b);if(!P)throw new Error("Account membership is unavailable");let E=$e(P);me()||Dt(E);let w=u.find(O=>O.accountId===me()?.id);if(!w?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Vt(w.personalSpacePath,O=>{let K=u.find(R=>R.accountId===O);return K?$e(K):null}),await Pr(E),i(null),$t(P.accountId)},[u]),g=(0,v.useCallback)(async b=>{let P=u.find(E=>E.path===b);if(!P)throw new Error("Scope membership is unavailable");await qi($e(P))},[u]),y=(!!e?.id||Ic())&&!n&&!o;return{accounts:f,switcherAccounts:h,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:_,mountScope:g,loading:y||c.isLoading,error:o??c.error??s}}function Zc(){ee();let e=(0,v.useSyncExternalStore)(Wr,ur,ur),t=(0,v.useMemo)(()=>Ae(),[e]),n=de(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Pr,replaceMounts:xs,mount:qi,unmount:Sc}}function Es(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{V.auth.getSession().then(({data:p,error:h})=>{if(h){console.warn("[useAuth] getSession error, clearing stale session:",h.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=V.auth.onAuthStateChange((p,h)=>{if(p==="TOKEN_REFRESHED"&&!h){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(h),t(h?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let a=(0,v.useCallback)(async m=>m.provider?V.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:m.email,password:m.password}),[]),c=(0,v.useCallback)(async m=>V.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await V.auth.signOut(),Rn(),N().clear()},[]),l=(0,v.useCallback)(async m=>{let{error:p}=await V.auth.resetPasswordForEmail(m);if(p)throw p},[]),f=(0,v.useCallback)(async(m,p)=>{let{error:h}=await V.auth.signInWithOtp({email:m,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(h)throw h},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e){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(e))s(!0),x("resolve-asset",{asset_id:e}).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}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Ps={};se(()=>{for(let e of Object.keys(Ps))delete Ps[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;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}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Er={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Er[e];n||(n=Er[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Er[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Er[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Er[e]))}function ru(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
3
  `),i=new Function(r)(Xd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Hi(e,t){let[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),[o,a]=(0,v.useState)(null),c=(0,v.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,v.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null,r(null),i(!0));let m=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let p=null;try{let h=1,_=e+"@v1",g=m+e+"/__bundle.js";if(u!==null)h=u,_=e+"@v"+h,g=m+e+"/__bundle.v"+h+".js";else try{let w=await fetch(m+e+"/__meta",{cache:"no-store"});w.ok&&(h=(await w.json()).version||1,_=e+"@v"+h,g=m+e+"/__bundle.v"+h+".js")}catch{g=m+e+"/__bundle.js?v="+Date.now()}if(l)return;let y=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");p=y;let b=nu(y),P=Ps[_];if(!P){let w=await fetch(g);if(!w.ok)throw new Error(`Failed to fetch bundle: ${w.status} ${w.statusText} (${g})`);let O=await w.text();if(P=ru(O),!P)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof P!="function")throw new Error(`Bundle export is not a React component (got ${typeof P})`);Ps[_]=P}if(await b,l){Ve(y);return}let E=c.current?.cssUrl??null;c.current={path:e,cssUrl:y},p=null,r(()=>P),i(!1),E&&Ve(E)}catch(h){p&&Ve(p),l||(a(h instanceof Error?h:new Error(String(h))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,v.useEffect)(()=>()=>{c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var tf=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,nf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Tc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=Rt(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Cr=new Map,Di=new Map;se(()=>{Cr.clear(),Di.clear()});function Rt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function su(e){let t=Rt(Rt(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Ac(e,t,n){let r=await vr(e.path,{mode:"render"}),s=Rt(Rt(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function rf(e,t,n){let r=await gr(t);if(!r)throw new Error("The published release could not be read.");let s=Rt(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=Rt(s.artifacts),o=Tc(i,tf,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Tc(i,nf,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Bt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),f=g=>l.find(y=>Rt(y.type_data).package_path===g),m=f(o.path),p=a?f(a.path):void 0;if(!m||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[h,_]=await Promise.all([Ac(m,o.sha256,"script"),p&&a?Ac(p,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:h,stylesheet:_?.trim()?_:null}}function iu(e,t,n){let r=Cr.get(t);return r||(r=rf(e,t,n),Cr.set(t,r),r.catch(()=>{Cr.get(t)===r&&Cr.delete(t)})),r}function ou(e){let t=su(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):iu(e.id,t.releaseItemId,t.version)}function au(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)("loading"),[i,o]=(0,v.useState)(null),a=(0,v.useRef)(null),c=e!=null,u=e?.id||null,l=e?su(e):null,f=l?.releaseItemId??null,m=l?.version??null;return(0,v.useEffect)(()=>{if(!c)return;let p=()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null,n(null)};if(!u||!f||m===null){p(),o(null),s("unpublished");return}let h=!1;return o(null),a.current&&a.current.componentId!==u&&p(),a.current||s("loading"),(async()=>{let _=null;try{let g=await iu(u,f,m);if(h)return;if(g.status!=="ready"){p(),s(g.status);return}let y=Di.get(f);if(!y){if(y=ru(g.script),!y)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof y!="function")throw new Error(`The published script handed over something that is not a React component (${typeof y}).`);Di.set(f,y)}let b=g.stylesheet?`release:${f}`:null;if(b&&(_=b,await nu(b,async()=>g.stylesheet)),h){_&&Ve(_);return}let P=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:f,cssKey:b},_=null,n({Component:y,version:m}),s("ready"),P&&Ve(P)}catch(g){if(_&&Ve(_),h)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{h=!0}},[c,u,f,m]),(0,v.useEffect)(()=>()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var sf=["--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 cu(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return sf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function uu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function lu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var fe=null,Qn=null,Ui=new Set;function of(){Ui.forEach(e=>e())}se(()=>{fe=null,Qn=null});async function du(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=vt()?.principal_id??null;if(n){if(fe&&fe.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await V.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(fe&&fe.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Qn||(Qn=(async()=>{try{let{data:s,error:i}=await V.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await V.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(f=>f.path);a=l.find(f=>f.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return fe={authUserId:r,...c},c}finally{Qn=null}})(),Qn)}async function fu(e){return(await du(e)).principalId}function pu(){let e=Es(),t=e.user,n=fe?.authUserId===t?.id?fe:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let a=fe;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ui.add(o),()=>{Ui.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,du(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function mu(e){let{path:t,...n}=e,r=Hi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function gu(e){return e.children}function hu(e){let t=ee(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,v.useMemo)(()=>C.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,v.useRef)(null),l=B({queryKey:a,queryFn:()=>_s(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let _=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(c,a,{exact:!0})},500)},g=>{let y=c.getQueryData(a);return Qi(g,n,r,[...y?.messages??[],...y?.activityMessages??[]])});return()=>{_(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let f=l.data,m=f?.messages??[],p=f?.messageCards??new Map,h=f?.siblingCards??[];return{messages:m,activityMessages:f?.activityMessages??[],messageCards:p,siblingCards:h,threads:(0,v.useMemo)(()=>m.filter(_=>_.reply_count>0),[m]),breakouts:(0,v.useMemo)(()=>m.filter(_=>_.member_count>0),[m]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function yu(e){ee();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,l=ir({queryKey:[...C.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:y})=>br(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:y?.before_seq,after_seq:y?.after_seq}),initialPageParam:void 0,getPreviousPageParam:y=>{if(!c||y.messages.length<r)return;let b=y.messages[y.messages.length-1]?.seq;return b==null?void 0:{after_seq:b}},getNextPageParam:y=>{if(y.messages.length<r)return;let b=y.messages[0]?.seq;return b==null?void 0:{before_seq:b}},enabled:u}),f=(0,v.useMemo)(()=>{if(!l.data?.pages)return[];let y=new Set,b=[];for(let P of l.data.pages)for(let E of P.messages)y.has(E.id)||(y.add(E.id),b.push(E));return b.sort((P,E)=>P.seq-E.seq)},[l.data?.pages]),{messageCards:m,siblingCards:p}=(0,v.useMemo)(()=>{let y=new Map,b=[];if(!l.data?.pages)return{messageCards:y,siblingCards:b};let P=new Set;for(let E of l.data.pages){for(let[w,O]of E.messageCards)for(let K of O){if(P.has(K.id))continue;P.add(K.id);let R=y.get(w)||[];R.push(K),y.set(w,R)}for(let w of E.siblingCards)P.has(w.id)||(P.add(w.id),b.push(w))}return{messageCards:y,siblingCards:b}},[l.data?.pages]),h=L(),_=(0,v.useRef)(null),g=(0,v.useMemo)(()=>[...C.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,v.useEffect)(()=>{if(!s||!t||!u)return;let y=()=>void be(h,g,{exact:!0}),b=!1,P=!1,E=!1,w=async()=>{if(o||a){y();return}let R=h.getQueryData(g);if(!R?.pages?.length){y();return}let A=0;for(let k of R.pages)for(let T of k.messages)T.seq>A&&(A=T.seq);if(A===0){y();return}try{let k=await br(t,{parentMessageId:n,limit:r,after_seq:A});if(k.messages.length===0&&k.siblingCards.length===0){y();return}if(k.messages.length>0){let T=Math.min(...k.messages.map(M=>M.seq));if(T>A+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${A}, minNewSeq=${T}. Triggering full refetch.`),y();return}}h.setQueryData(g,T=>{if(!T)return T;let M=[...T.pages],q=0,U=M[q],$=new Set(U.messages.map(Ce=>Ce.id)),Pe=k.messages.filter(Ce=>!$.has(Ce.id)),re=[...U.messages,...Pe].sort((Ce,Ns)=>Ce.seq-Ns.seq),Pt=new Map(U.messageCards);for(let[Ce,Ns]of k.messageCards){let oo=Pt.get(Ce)||[],Ol=new Set(oo.map(Qs=>Qs.id)),Fl=Ns.filter(Qs=>!Ol.has(Qs.id));Pt.set(Ce,[...oo,...Fl])}let Al=new Set(U.siblingCards.map(Ce=>Ce.id)),kl=k.siblingCards.filter(Ce=>!Al.has(Ce.id)),Ml=[...U.siblingCards,...kl];return M[q]={...U,activityMessages:k.activityMessages??[],messages:re,messageCards:Pt,siblingCards:Ml},{...T,pages:M}})}catch(k){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",k),y()}},O=async()=>{if(b){P=!0;return}b=!0;try{do P=!1,await w();while(P&&!E)}finally{b=!1}},K=ie("vfs_change",()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{O()},500)},R=>(o||a)&&R?.item_type==="message"&&(h.getQueryData(g)?.pages??[]).some(A=>A.messages.some(k=>k.id===R.parent_id))||Qi(R,t,n,h.getQueryData(g)?.pages.flatMap(A=>A.messages)??[]));return()=>{E=!0,K(),_.current&&clearTimeout(_.current)}},[s,t,u,g,h,n,r,o,a]),{messages:f,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:m,siblingCards:p,threads:f.filter(y=>y.reply_count>0),breakouts:f.filter(y=>y.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var _u=["open","active","strict","hand_raise"];function af(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function cf(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function kc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:af(t.ai_mode),activeAgentIds:cf(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function Is(e={}){let t=ee(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,v.useMemo)(()=>C.channels("all"),[t]),a=B({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(kc),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return Pc(i,o,kc)},[n,r,o,i]),{channels:(0,v.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function vu(e={}){let t=Is(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function bu(e={}){let t=Is(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function ji(e={}){let t=ee(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,v.useRef)(null),c=(0,v.useMemo)(()=>C.notifications(n,r),[n,r,t]),u=B({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await x("get-notifications",f)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(m=>ie(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&Rs(p)));return()=>{f.forEach(m=>m()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function wu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=ji({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,v.useMemo)(()=>{let p=new Map;for(let h of s)h.is_unread&&h.channel_id&&p.set(h.channel_id,(p.get(h.channel_id)||0)+1);return p},[s]),l=(0,v.useMemo)(()=>{let p=0;return u.forEach(h=>{p+=h}),p},[u]),{dmUnread:f,channelUnread:m}=(0,v.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),h=0,_=0;return u.forEach((g,y)=>{p.has(y)?h+=g:_+=g}),{dmUnread:h,channelUnread:_}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:f,channelUnread:m,isLoading:i,isFetching:o,error:a,refetch:c}}function Su(){let e=L();return te({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:C.children(r)})}})}function xu(){let e=L();return te({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:C.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:C.children(i)})}}})}function Ru(){return te({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!fe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...fe.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};fe={...fe,displayName:typeof t.display_name=="string"?t.display_name:fe.displayName,metadata:n},of()}})}function Pu(){let e=L();return te({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:C.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:C.children(i)})}}})}function Cu(){let e=L();return te({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:C.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:C.children(o)})}s&&e.invalidateQueries({queryKey:C.children(s)})}})}function Eu(){let e=L();return te({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:C.edges(r)}),s&&e.invalidateQueries({queryKey:C.edges(s)})}})}function Iu(e,t){let n=L(),{optimistic:r,...s}=t??{};return te({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Tu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,v.useRef)(s),c=(0,v.useRef)(i);(0,v.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,v.useEffect)(()=>o?ie(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Au(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,v.useRef)(s);c.current=s;let u=(0,v.useRef)(null),l=B({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let f=ie(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(a,t,{exact:!0})},o)},m=>c.current?.(m)??!0);return()=>{f(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Dn(e){ee();let t=W(),n=(0,v.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=B({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await x("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),a=o.data??null,c=(0,v.useMemo)(()=>a?.resolved_children??[],[a]),u=a?.resolution_level??null,l=(0,v.useMemo)(()=>{let p=(a?.type_data??null)?.order;return Array.isArray(p)?p:null},[a]),f=(0,v.useCallback)(m=>{if(!l||!m?.length)return m??[];let p=y=>y.id??y.name??"",h=new Map(l.map((y,b)=>[y,b])),_=[],g=[];for(let y of m)(h.has(p(y))?_:g).push(y);return _.sort((y,b)=>h.get(p(y))-h.get(p(b))),[..._,...g]},[l]);return{...o,arrangement:a,resolvedChildren:c,resolutionLevel:u,order:l,sourceScopeId:a?.scope_item_id??null,arrangementQueryKey:i,applyTo:f}}function ku(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=ee(),c=vt(),u=i??c?.scope_id??null,l=(0,v.useMemo)(()=>{if(!t)return null;let w="/accounts/",O=t.indexOf(w);if(O===-1)return null;let K=t.indexOf("/",O+w.length);return K===-1?t:t.slice(0,K)},[t]),f=o??l??c?.scope_path??null,m=n?.trim()||null,p=`${a}
4
4
  ${u??""}
5
5
  ${f??""}