@ai4b-team/fsaos-gateway-sdk 3.1.0 → 3.2.0

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