@ai4b-team/fsaos-gateway-sdk 3.21.0 → 3.21.1

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-08-27T18:10:22.746Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var Ka=Object.create;var Xt=Object.defineProperty;var La=Object.getOwnPropertyDescriptor;var ja=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var Ms=e=>{throw TypeError(e)};var Wa=(e,t,n)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Zt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$a=(e,t)=>{for(var n in t)Xt(e,n,{get:t[n],enumerable:!0})},ks=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ja(t))!Ha.call(e,s)&&s!==n&&Xt(e,s,{get:()=>t[s],enumerable:!(r=La(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?Ka(Va(e)):{},ks(t||!e||!e.__esModule?Xt(n,"default",{value:e,enumerable:!0}):n,e)),Ba=e=>ks(Xt({},"__esModule",{value:!0}),e);var se=(e,t,n)=>Wa(e,typeof t!="symbol"?t+"":t,n),kr=(e,t,n)=>t.has(e)||Ms("Cannot "+n);var u=(e,t,n)=>(kr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?Ms("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(kr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),P=(e,t,n)=>(kr(e,t,"access private method"),n);var en=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return u(e,t,r)}});var qs=Zt((nu,Fs)=>{Fs.exports={createClient:window.supabase.createClient}});var oe=Zt((_d,Fi)=>{Fi.exports=React});var sr=Zt((vd,qi)=>{qi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var mo=Zt((hf,ho)=>{ho.exports=ReactDOM});var Io=Zt((wf,To)=>{To.exports=ReactDOM});var Os={};$a(Os,{ComponentRenderer:()=>da,EnforcementDeniedError:()=>mt,FormSubmissionError:()=>Rt,InteractionTrackingError:()=>wt,KernelProvider:()=>fa,QueryClientProvider:()=>Cn,auth:()=>Po,awaitAnchorReady:()=>an,awaitScopeReady:()=>$s,callTool:()=>So,clearCachedToken:()=>Ur,clearSession:()=>Hr,createItem:()=>vo,disconnectSSE:()=>bs,disposeVfsRealtimeWs:()=>Er,electHomeAnchor:()=>cn,emitEvent:()=>uo,fetchChannelMessages:()=>Xi,fetchChannelMessagesPage:()=>An,fetchChannelMessagesWithCards:()=>vr,fetchEdgesForItem:()=>pr,fetchItemHistory:()=>gr,fetchItemVersions:()=>Tn,fetchItems:()=>In,fetchMemberFocus:()=>yr,fetchOpenEnvelope:()=>_r,fetchRecentActivity:()=>mr,fetchResolvedItems:()=>Is,fetchTimelineHistory:()=>As,fetchTypeDefinitions:()=>fr,fetchVfsChildren:()=>lr,fetchVfsChildrenPage:()=>dr,fetchVfsItem:()=>ur,fetchVfsItemById:()=>cr,fetchVfsTree:()=>hr,gatewayCall:()=>R,getAccessToken:()=>xe,getAnchor:()=>on,getAnchorRef:()=>Ze,getAnchorVersion:()=>Kr,getAssetUrl:()=>Co,getDefaultSort:()=>Ia,getHomeAnchor:()=>Qe,getMountVersion:()=>ln,getMounts:()=>_t,getQueryClient:()=>E,getRequiredFormFields:()=>Aa,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>$n,initSession:()=>vt,initVfsRealtimeWs:()=>qn,initializeFsaos:()=>Zs,interpretSchema:()=>Ts,invalidateAllVfs:()=>to,invalidateChannelMessages:()=>ro,invalidateChildren:()=>ar,invalidateItem:()=>_s,invalidateOpenEnvelope:()=>so,invalidatePathAndParent:()=>Zi,invalidateSubtree:()=>eo,invalidateTypes:()=>no,isAnchorReady:()=>jr,isScopeReady:()=>Bn,listChildren:()=>_o,mount:()=>Eo,mountRealtimeScope:()=>Dn,normalizeItem:()=>me,ping:()=>lo,pushChanges:()=>wo,queryClient:()=>Gi,readItem:()=>yo,registerCleanup:()=>Te,resetAllSdkState:()=>bt,resolvePrincipalId:()=>ca,setAnchor:()=>Ne,setCachedToken:()=>Ns,setQueryClient:()=>Bi,setScope:()=>Ws,setupRequireShim:()=>xo,signal:()=>Ro,startTracking:()=>Gn,submitForm:()=>ei,subscribeAnchor:()=>Lr,subscribeArtifactStream:()=>Ar,subscribeMounts:()=>Wn,subscribeScope:()=>tt,subscribeToEvents:()=>J,subscribeToPath:()=>Sr,subscribeToScope:()=>Rr,trackAction:()=>Ys,trackEvent:()=>nt,trackPageView:()=>Js,unmountRealtimeScope:()=>po,updateItem:()=>bo,uploadFile:()=>Oa,useAccounts:()=>Zo,useAgentTimeline:()=>Ua,useAllChannels:()=>Ir,useArrangement:()=>xa,useArtifactStream:()=>Da,useAsset:()=>ta,useAuth:()=>Tr,useChannelMessages:()=>pa,useChannels:()=>ma,useChildren:()=>Uo,useComponent:()=>Es,useCreate:()=>_a,useDelete:()=>wa,useDmChannels:()=>ga,useEdges:()=>Ho,useEventStream:()=>Pa,useFileUpload:()=>ka,useInfiniteChannelMessages:()=>ha,useInfiniteChildren:()=>Vo,useInfiniteItems:()=>jo,useItem:()=>qo,useItemById:()=>Do,useItemHistory:()=>Jo,useItemVersions:()=>zo,useItems:()=>Lo,useLink:()=>Ra,useList:()=>Ps,useMemberFocus:()=>Go,useMounts:()=>ea,useMove:()=>Sa,useMutation:()=>Ca,useNotifications:()=>xs,useOpen:()=>$o,usePermission:()=>ia,usePermissions:()=>oa,usePrincipal:()=>ua,useRealtimeQuery:()=>Ea,useRecentActivity:()=>Yo,useResolve:()=>Ko,useResolvedItems:()=>qa,useScope:()=>Xo,useScopeReady:()=>Fo,useSearch:()=>Qo,useTheme:()=>sa,useTimelineHistory:()=>Na,useTool:()=>la,useTree:()=>No,useType:()=>Wo,useTypeHelpers:()=>Bo,useTypes:()=>xr,useUnreadCounts:()=>ya,useUpdate:()=>va,useUpdatePrincipal:()=>ba,vfsKeys:()=>w});var mt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);se(this,"name","EnforcementDeniedError");se(this,"deniedBy");se(this,"ruleKey");se(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Ds=j(qs(),1),tn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},nn=Array.isArray(tn.sources)?tn.sources:[],Ga=tn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",za=tn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=tn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,Ds.createClient)(Ga,za,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var sn=null,Kn=0,Us,Dr,Ln=!1;Us=new Promise(e=>{Dr=e});k.auth.onAuthStateChange((e,t)=>{t?.access_token?(sn=t.access_token,Kn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(sn=null,Kn=0),Ln||(Ln=!0,Dr())});setTimeout(()=>{Ln||(Ln=!0,Dr())},5e3);function Ns(e,t){sn=e,Kn=t??Math.floor(Date.now()/1e3)+3600}function Ur(){sn=null,Kn=0}async function xe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Us,sn}var jn=null,Hn=null,Qs=0,Fr=new Set,Nr,Qr,Vn=!1;Nr=new Promise(e=>{Qr=e});function Ks(){Qs++,Fr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Ne(e){let t=typeof e=="string"?e:e.path,n=jn!==t;jn=t,Hn=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],un()),Vn||(Vn=!0,Qr()),n&&Ks()}function on(){return jn}function Ze(){return Hn}function Kr(){return Qs}function Lr(e){return Fr.add(e),()=>{Fr.delete(e)}}function an(){return Nr}function jr(){return Vn}var yt=null;function cn(e){if(yt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}yt=e,Ne(e)}function Qe(){return yt}var ue=[],qr=new Set,Ls=0;function un(){Ls++,qr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function _t(){return ue}function ln(){return Ls}function Wn(e){return qr.add(e),()=>{qr.delete(e)}}function Vr(e){ue=e,un()}function js(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],un())}function Vs(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),un(),Hn?.id===e&&yt&&Ne(yt))}var gt=null,rn=null;async function vt(){return gt||rn||(rn=(async()=>{let e=et(),t=await xe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${ce}/d/${e}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return gt={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},gt})(),rn)}function $n(){return gt}function Hr(){gt=null,rn=null,jn=null,Hn=null,yt=null,ue=[]}var Hs=[];function Te(e){Hs.push(e)}function bt(){Hr(),Ur(),Vn=!1,Nr=new Promise(e=>{Qr=e}),Ks(),un();for(let e of Hs)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function et(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ws=Ne,fe=on,be=Kr,tt=Lr,$s=an,Bn=jr;var Wr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ja=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Bs=new Map,Gs=new Map,wt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function fn(e){let t=e?nn.find(n=>n.id===e):nn.find(n=>n.default===!0)??(nn.length===1?nn[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function $r(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function Ya(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Xa(e,t){if(!Ya(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Br(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Za(e){try{let t=Br(e)?.getItem(e.key)??void 0;return t&&Wr.test(t)?t:void 0}catch{return}}function zs(e,t){try{Br(e)?.setItem(e.key,t)}catch{}}function ec(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Za(t)??Bs.get(e.id);if(n)return n;let r=crypto.randomUUID();return Bs.set(e.id,r),zs(t,r),r}function tc(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let l=Br(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=Gs.get(e.id),i=r&&typeof r.id=="string"&&Wr.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,a=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<a?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Gs.set(e.id,c),zs(n,JSON.stringify(c)),c.id}function nc(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,a=Object.fromEntries(n.flatMap(o=>{if(typeof o!="string"||o.length===0||o.length>128)return[];let c=r.searchParams.get(o);return c?[[o,c.slice(0,i)]]:[]}));return Object.keys(a).length>0?a:void 0}async function nt(e,t={},n={}){let r=fn(n.source);if(Xa(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??ec(r),a=n.sessionId??tc(r);if(![s,i,a].every(g=>Wr.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let o=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!o)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=nc(r,o),h=d?{...t,source_keys:d}:t,f=et(),p=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:o,visitor_id:i,session_id:a,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:h}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new wt(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let m=null;try{m=await y.json()}catch{}if(!y.ok||m?.success!==!0){let g=m;throw new wt(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return m}function Js(e={},t={}){let n=fn(t.source),r=$r("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return nt(r.observation,{...s,...e},{...t,source:n.id})}function Ys(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=fn(n.source),s=$r("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return nt(s.observation,{...t,...i},{...n,source:r.id})}function Xs(e,t={}){let n=fn(t.source),r=$r("form_receipt",n);return nt(r.observation,e,{...t,source:n.id})}var dn;function Gn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(dn)return dn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=fn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(f=>f.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(f=>f.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let f of n){let p=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};nt(f.observation,p,{source:t.id,keepalive:!0}).catch(()=>{})}}},a=f=>{if(f.target instanceof Element)for(let p of r){let y=p.attribute;if(!y||!Ja.test(y))continue;let m=f.target.closest(`[${y}]`);if(!m)continue;let g=m.getAttribute(y)?.trim();if(!g||g.length>128)continue;let S={};p.id_property&&(S[p.id_property]=g),p.element_property&&(S[p.element_property]=m.tagName.toLowerCase()),nt(p.observation,S,{source:t.id,keepalive:!0}).catch(()=>{})}},o=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),h=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...p){o.apply(this,p),l()},window.history.replaceState=function(...p){c.apply(this,p),l()},window.addEventListener("popstate",i)),h&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",a,{capture:!0}),n.length>0&&queueMicrotask(i),dn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",a,{capture:!0}),d&&(window.history.pushState=o,window.history.replaceState=c),dn=void 0},dn}var St;function Zs(e={}){return St||(St=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Gn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await vt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),St=void 0)}}}catch(r){throw n(),St=void 0,r}})(),St)}var rc=new Set(["list-memberships","init"]);async function R(e,t={}){let n=et(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await xe();i&&(s.Authorization=`Bearer ${i}`),!rc.has(e)&&!t._scope_path&&await an();let a={...t},o=$n();!a.domain_scope_id&&o?.scope_id&&(a.domain_scope_id=o.scope_id);let c=on();!a._scope_path&&c&&(a._scope_path=c);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let d=await l.json();if(d.success===!1){let h=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||h==="RULE_DENIED"||h==="ACCESS_DENIED"||h==="PERMISSION_DENIED"||h==="ENTITLEMENT_REQUIRED"?new mt(d):new Error(d.message||d.error||`Gateway call ${e} failed`)}return d}var sc=/^[a-z][a-z0-9_-]{0,63}$/,ic=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Rt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function ei(e,t,n={}){if(!sc.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!ic.test(r))throw new TypeError("fillId must be a UUID");let s=et(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let a=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t}),signal:n.signal,credentials:"omit"})}catch(l){throw new Rt(l instanceof Error?l.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let c=null;try{c=await o.json()}catch{}if(!o.ok||c?.success!==!0){let l=c;throw new Rt(l?.message||l?.error||`Form submission failed (${o.status})`,l?.error||"FORM_SUBMISSION_FAILED",o.status,r)}try{await Xs({fill_id:r,action_id:e,release_id:c.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0})}catch{}return c}var le=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var rt,Ke,Ct,ti,oc=(ti=class extends le{constructor(){super();b(this,rt);b(this,Ke);b(this,Ct);v(this,Ct,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,Ke)||this.setEventListener(u(this,Ct))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,Ke))==null||t.call(this),v(this,Ke,void 0))}setEventListener(t){var n;v(this,Ct,t),(n=u(this,Ke))==null||n.call(this),v(this,Ke,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,rt)!==t&&(v(this,rt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,rt)=="boolean"?u(this,rt):globalThis.document?.visibilityState!=="hidden"}},rt=new WeakMap,Ke=new WeakMap,Ct=new WeakMap,ti),Pt=new oc;var ac={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Le,Gr,ni,cc=(ni=class{constructor(){b(this,Le,ac);b(this,Gr,!1)}setTimeoutProvider(e){v(this,Le,e)}setTimeout(e,t){return u(this,Le).setTimeout(e,t)}clearTimeout(e){u(this,Le).clearTimeout(e)}setInterval(e,t){return u(this,Le).setInterval(e,t)}clearInterval(e){u(this,Le).clearInterval(e)}},Le=new WeakMap,Gr=new WeakMap,ni),we=new cc;function ri(e){setTimeout(e,0)}var Jr=typeof window>"u"||"Deno"in globalThis;function q(){}function oi(e,t){return typeof e=="function"?e(t):e}function pn(e){return typeof e=="number"&&e>=0&&e!==1/0}function zn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function pe(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Jn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:o}=e;if(a){if(r){if(t.queryHash!==hn(a,t.options))return!1}else if(!st(t.queryKey,a))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||s&&s!==t.state.fetchStatus||i&&!i(t))}function Yn(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Se(t.options.mutationKey)!==Se(i))return!1}else if(!st(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function hn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>zr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function st(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>st(e[n],t[n])):!1}var uc=Object.prototype.hasOwnProperty;function Yr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=si(e)&&si(t);if(!r&&!(zr(e)&&zr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,c=r?new Array(o):{},l=0;for(let d=0;d<o;d++){let h=r?d:a[d],f=e[h],p=t[h];if(f===p){c[h]=f,(r?d<i:uc.call(e,h))&&l++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}let y=Yr(f,p,n+1);c[h]=y,y===f&&l++}return i===o&&l===i?e:c}function Et(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function si(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function zr(e){if(!ii(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ii(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ii(e){return Object.prototype.toString.call(e)==="[object Object]"}function ai(e){return new Promise(t=>{we.setTimeout(t,e)})}function mn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Yr(e,t):t}function ci(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ui(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xt=Symbol();function Xn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Tt(e,t){return typeof e=="function"?e(...t):!!e}function li(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Re=(()=>{let e=()=>Jr;return{isServer(){return e()},setIsServer(t){e=t}}})();function gn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var di=ri;function lc(){let e=[],t=0,n=o=>{o()},r=o=>{o()},s=di,i=o=>{t?e.push(o):s(()=>{n(o)})},a=()=>{let o=e;e=[],o.length&&s(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{s=o}}}var M=lc();var It,je,At,fi,dc=(fi=class extends le{constructor(){super();b(this,It,!0);b(this,je);b(this,At);v(this,At,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){u(this,je)||this.setEventListener(u(this,At))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,At,t),(n=u(this,je))==null||n.call(this),v(this,je,t(this.setOnline.bind(this)))}setOnline(t){u(this,It)!==t&&(v(this,It,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,It)}},It=new WeakMap,je=new WeakMap,At=new WeakMap,fi),Ot=new dc;function fc(e){return Math.min(1e3*2**e,3e4)}function Xr(e){return(e??"online")==="online"?Ot.isOnline():!0}var Zn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function er(e){let t=!1,n=0,r,s=gn(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new Zn(m);f(g),e.onCancel?.(g)}},o=()=>{t=!0},c=()=>{t=!1},l=()=>Pt.isFocused()&&(e.networkMode==="always"||Ot.isOnline())&&e.canRun(),d=()=>Xr(e.networkMode)&&e.canRun(),h=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},p=()=>new Promise(m=>{r=g=>{(i()||l())&&m(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let m,g=n===0?e.initialPromise:void 0;try{m=g??e.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(h).catch(S=>{if(i())return;let C=e.retry??(Re.isServer()?0:3),x=e.retryDelay??fc,U=typeof x=="function"?x(n,S):x,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),ai(U).then(()=>l()?void 0:p()).then(()=>{t?f(S):y()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():p().then(y),s)}}var it,pi,tr=(pi=class{constructor(){b(this,it)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pn(this.gcTime)&&v(this,it,we.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Re.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,it)!==void 0&&(we.clearTimeout(u(this,it)),v(this,it,void 0))}},it=new WeakMap,pi);var ot,Mt,de,at,V,yn,ct,ie,_i,Ie,gi,yi=(gi=class extends tr{constructor(t){super();b(this,ie);b(this,ot);b(this,Mt);b(this,de);b(this,at);b(this,V);b(this,yn);b(this,ct);v(this,ct,!1),v(this,yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,at,t.client),v(this,de,u(this,at).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,ot,mi(this.options)),this.state=t.state??u(this,ot),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,V)?.promise}setOptions(t){if(this.options={...u(this,yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=mi(this.options);n.data!==void 0&&(this.setState(hi(n.data,n.dataUpdatedAt)),v(this,ot,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,de).remove(this)}setData(t,n){let r=mn(this.state.data,t,this.options);return P(this,ie,Ie).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){P(this,ie,Ie).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,V)?.promise;return u(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,ot)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>pe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!zn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(this,de).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(u(this,V)&&(u(this,ct)||P(this,ie,_i).call(this)?u(this,V).cancel({revert:!0}):u(this,V).cancelRetry()),this.scheduleGc()),u(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,ie,Ie).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,V))return u(this,V).continueRetry(),u(this,V).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(v(this,ct,!0),r.signal)})},i=()=>{let c=Xn(this.options,n),d=(()=>{let h={client:u(this,at),queryKey:this.queryKey,meta:this.meta};return s(h),h})();return v(this,ct,!1),this.options.persister?this.options.persister(c,d,this):c(d)},o=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,at),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(o,this),v(this,Mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&P(this,ie,Ie).call(this,{type:"fetch",meta:o.fetchOptions?.meta}),v(this,V,er({initialPromise:n?.initialPromise,fn:o.fetchFn,onCancel:c=>{c instanceof Zn&&c.revert&&this.setState({...u(this,Mt),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{P(this,ie,Ie).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{P(this,ie,Ie).call(this,{type:"pause"})},onContinue:()=>{P(this,ie,Ie).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{let c=await u(this,V).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),u(this,de).config.onSuccess?.(c,this),u(this,de).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Zn){if(c.silent)return u(this,V).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw P(this,ie,Ie).call(this,{type:"error",error:c}),u(this,de).config.onError?.(c,this),u(this,de).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},ot=new WeakMap,Mt=new WeakMap,de=new WeakMap,at=new WeakMap,V=new WeakMap,yn=new WeakMap,ct=new WeakMap,ie=new WeakSet,_i=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ie=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Zr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...hi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Mt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),M.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,de).notify({query:this,type:"updated",action:t})})},gi);function Zr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function mi(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Z,T,vn,z,ut,kt,Ae,Ve,bn,Ft,qt,lt,dt,He,Dt,O,_n,es,ts,ns,rs,ss,is,os,Si,wi,wn=(wi=class extends le{constructor(t,n){super();b(this,O);b(this,Z);b(this,T);b(this,vn);b(this,z);b(this,ut);b(this,kt);b(this,Ae);b(this,Ve);b(this,bn);b(this,Ft);b(this,qt);b(this,lt);b(this,dt);b(this,He);b(this,Dt,new Set);this.options=n,v(this,Z,t),v(this,Ve,null),v(this,Ae,gn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,T).addObserver(this),vi(u(this,T),this.options)?P(this,O,_n).call(this):this.updateResult(),P(this,O,rs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return as(u(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return as(u(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,O,ss).call(this),P(this,O,is).call(this),u(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,T);if(this.options=u(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,u(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,O,os).call(this),u(this,T).setOptions(this.options),n._defaulted&&!Et(this.options,n)&&u(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,T),observer:this});let s=this.hasListeners();s&&bi(u(this,T),r,this.options,n)&&P(this,O,_n).call(this),this.updateResult(),s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||pe(this.options.staleTime,u(this,T))!==pe(n.staleTime,u(this,T)))&&P(this,O,es).call(this);let i=P(this,O,ts).call(this);s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||i!==u(this,He))&&P(this,O,ns).call(this,i)}getOptimisticResult(t){let n=u(this,Z).getQueryCache().build(u(this,Z),t),r=this.createResult(n,t);return hc(this,r)&&(v(this,z,r),v(this,kt,this.options),v(this,ut,u(this,T).state)),r}getCurrentResult(){return u(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&u(this,Ae).status==="pending"&&u(this,Ae).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Dt).add(t)}getCurrentQuery(){return u(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,Z).defaultQueryOptions(t),r=u(this,Z).getQueryCache().build(u(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return P(this,O,_n).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,z)))}createResult(t,n){let r=u(this,T),s=this.options,i=u(this,z),a=u(this,ut),o=u(this,kt),l=t!==r?t.state:u(this,vn),{state:d}=t,h={...d},f=!1,p;if(n._optimisticResults){let Q=this.hasListeners(),Y=!Q&&vi(t,n),ye=Q&&bi(t,r,n,s);(Y||ye)&&(h={...h,...Zr(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:g}=h;p=h.data;let S=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===o?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(u(this,qt)?.state.data,u(this,qt)):n.placeholderData,Q!==void 0&&(g="success",p=mn(i?.data,Q,n),f=!0)}if(n.select&&p!==void 0&&!S)if(i&&p===a?.data&&n.select===u(this,bn))p=u(this,Ft);else try{v(this,bn,n.select),p=n.select(p),p=mn(i?.data,p,n),v(this,Ft,p),v(this,Ve,null)}catch(Q){v(this,Ve,Q)}u(this,Ve)&&(y=u(this,Ve),p=u(this,Ft),m=Date.now(),g="error");let C=h.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&C,$=p!==void 0,re={status:g,fetchStatus:h.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:p,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!x,isLoadingError:U&&!$,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&$,isStale:cs(t,n),refetch:this.refetch,promise:u(this,Ae),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let Q=re.data!==void 0,Y=re.status==="error"&&!Q,ye=I=>{Y?I.reject(re.error):Q&&I.resolve(re.data)},_e=()=>{let I=v(this,Ae,re.promise=gn());ye(I)},ve=u(this,Ae);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(Y||re.data!==ve.value)&&_e();break;case"rejected":(!Y||re.error!==ve.reason)&&_e();break}}return re}updateResult(){let t=u(this,z),n=this.createResult(u(this,T),this.options);if(v(this,ut,u(this,T).state),v(this,kt,this.options),u(this,ut).data!==void 0&&v(this,qt,u(this,T)),Et(n,t))return;v(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Dt).size)return!0;let a=new Set(i??u(this,Dt));return this.options.throwOnError&&a.add("error"),Object.keys(u(this,z)).some(o=>{let c=o;return u(this,z)[c]!==t[c]&&a.has(c)})};P(this,O,Si).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,O,rs).call(this)}},Z=new WeakMap,T=new WeakMap,vn=new WeakMap,z=new WeakMap,ut=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Ve=new WeakMap,bn=new WeakMap,Ft=new WeakMap,qt=new WeakMap,lt=new WeakMap,dt=new WeakMap,He=new WeakMap,Dt=new WeakMap,O=new WeakSet,_n=function(t){P(this,O,os).call(this);let n=u(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},es=function(){P(this,O,ss).call(this);let t=pe(this.options.staleTime,u(this,T));if(Re.isServer()||u(this,z).isStale||!pn(t))return;let r=zn(u(this,z).dataUpdatedAt,t)+1;v(this,lt,we.setTimeout(()=>{u(this,z).isStale||this.updateResult()},r))},ts=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,T)):this.options.refetchInterval)??!1},ns=function(t){P(this,O,is).call(this),v(this,He,t),!(Re.isServer()||X(this.options.enabled,u(this,T))===!1||!pn(u(this,He))||u(this,He)===0)&&v(this,dt,we.setInterval(()=>{(this.options.refetchIntervalInBackground||Pt.isFocused())&&P(this,O,_n).call(this)},u(this,He)))},rs=function(){P(this,O,es).call(this),P(this,O,ns).call(this,P(this,O,ts).call(this))},ss=function(){u(this,lt)!==void 0&&(we.clearTimeout(u(this,lt)),v(this,lt,void 0))},is=function(){u(this,dt)!==void 0&&(we.clearInterval(u(this,dt)),v(this,dt,void 0))},os=function(){let t=u(this,Z).getQueryCache().build(u(this,Z),this.options);if(t===u(this,T))return;let n=u(this,T);v(this,T,t),v(this,vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Si=function(t){M.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,z))}),u(this,Z).getQueryCache().notify({query:u(this,T),type:"observerResultsUpdated"})})},wi);function pc(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function vi(e,t){return pc(e,t)||e.state.data!==void 0&&as(e,t,t.refetchOnMount)}function as(e,t,n){if(X(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&cs(e,t)}return!1}function bi(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&cs(e,n)}function cs(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function hc(e,t){return!Et(e.getCurrentResult(),t)}function Ut(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[],o={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,h=y=>{li(y,()=>t.signal,()=>d=!0)},f=Xn(t.options,t.fetchOptions),p=async(y,m,g)=>{if(d)return Promise.reject();if(m==null&&y.pages.length)return Promise.resolve(y);let C=(()=>{let $={client:t.client,queryKey:t.queryKey,pageParam:m,direction:g?"backward":"forward",meta:t.options.meta};return h($),$})(),x=await f(C),{maxPages:U}=t.options,L=g?ui:ci;return{pages:L(y.pages,x,U),pageParams:L(y.pageParams,m,U)}};if(s&&i.length){let y=s==="backward",m=y?Ri:us,g={pages:i,pageParams:a},S=m(r,g);o=await p(g,S,y)}else{let y=e??i.length;do{let m=c===0?a[0]??r.initialPageParam:us(r,o);if(c>0&&m==null)break;o=await p(o,m),c++}while(c<y)}return o};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function us(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ri(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ci(e,t){return t?us(e,t)!=null:!1}function Pi(e,t){return!t||!e.getPreviousPageParam?!1:Ri(e,t)!=null}var ls=class extends wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Ut()})}getOptimisticResult(e){return e.behavior=Ut(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:o}=r,c=n.fetchMeta?.fetchMore?.direction,l=a&&c==="forward",d=s&&c==="forward",h=a&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ci(t,n.data),hasPreviousPage:Pi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:h,isFetchingPreviousPage:f,isRefetchError:o&&!l&&!h,isRefetching:i&&!d&&!f}}};var Sn,Ce,G,ft,Pe,We,Ei,xi=(Ei=class extends tr{constructor(t){super();b(this,Pe);b(this,Sn);b(this,Ce);b(this,G);b(this,ft);v(this,Sn,t.client),this.mutationId=t.mutationId,v(this,G,t.mutationCache),v(this,Ce,[]),this.state=t.state||ds(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,Ce).includes(t)||(u(this,Ce).push(t),this.clearGcTimeout(),u(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Ce,u(this,Ce).filter(n=>n!==t)),this.scheduleGc(),u(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Ce).length||(this.state.status==="pending"?this.scheduleGc():u(this,G).remove(this))}continue(){return u(this,ft)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{P(this,Pe,We).call(this,{type:"continue"})},r={client:u(this,Sn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,ft,er({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{P(this,Pe,We).call(this,{type:"failed",failureCount:a,error:o})},onPause:()=>{P(this,Pe,We).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,G).canRun(this)}));let s=this.state.status==="pending",i=!u(this,ft).canStart();try{if(s)n();else{P(this,Pe,We).call(this,{type:"pending",variables:t,isPaused:i}),u(this,G).config.onMutate&&await u(this,G).config.onMutate(t,this,r);let o=await this.options.onMutate?.(t,r);o!==this.state.context&&P(this,Pe,We).call(this,{type:"pending",context:o,variables:t,isPaused:i})}let a=await u(this,ft).start();return await u(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await u(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),P(this,Pe,We).call(this,{type:"success",data:a}),a}catch(a){try{await u(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(o){Promise.reject(o)}try{await u(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(o){Promise.reject(o)}throw P(this,Pe,We).call(this,{type:"error",error:a}),a}finally{u(this,G).runNext(this)}}},Sn=new WeakMap,Ce=new WeakMap,G=new WeakMap,ft=new WeakMap,Pe=new WeakSet,We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),M.batch(()=>{u(this,Ce).forEach(r=>{r.onMutationUpdate(t)}),u(this,G).notify({mutation:this,type:"updated",action:t})})},Ei);function ds(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oe,he,Rn,Ti,Ii=(Ti=class extends le{constructor(t={}){super();b(this,Oe);b(this,he);b(this,Rn);this.config=t,v(this,Oe,new Set),v(this,he,new Map),v(this,Rn,0)}build(t,n,r){let s=new xi({client:t,mutationCache:this,mutationId:++en(this,Rn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,Oe).add(t);let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);r?r.push(t):u(this,he).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,Oe).delete(t)){let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,he).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=nr(t);if(typeof n=="string"){let s=u(this,he).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=nr(t);return typeof n=="string"?u(this,he).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{u(this,Oe).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,Oe).clear(),u(this,he).clear()})}getAll(){return Array.from(u(this,Oe))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Yn(n,r))}findAll(t={}){return this.getAll().filter(n=>Yn(t,n))}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Oe=new WeakMap,he=new WeakMap,Rn=new WeakMap,Ti);function nr(e){return e.options.scope?.id}var Me,$e,ee,ke,Fe,rr,fs,Ai,ps=(Ai=class extends le{constructor(t,n){super();b(this,Fe);b(this,Me);b(this,$e);b(this,ee);b(this,ke);v(this,Me,t),this.setOptions(n),this.bindMethods(),P(this,Fe,rr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,Me).defaultMutationOptions(t),Et(this.options,n)||u(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():u(this,ee)?.state.status==="pending"&&u(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,ee)?.removeObserver(this)}onMutationUpdate(t){P(this,Fe,rr).call(this),P(this,Fe,fs).call(this,t)}getCurrentResult(){return u(this,$e)}reset(){u(this,ee)?.removeObserver(this),v(this,ee,void 0),P(this,Fe,rr).call(this),P(this,Fe,fs).call(this)}mutate(t,n){return v(this,ke,n),u(this,ee)?.removeObserver(this),v(this,ee,u(this,Me).getMutationCache().build(u(this,Me),this.options)),u(this,ee).addObserver(this),u(this,ee).execute(t)}},Me=new WeakMap,$e=new WeakMap,ee=new WeakMap,ke=new WeakMap,Fe=new WeakSet,rr=function(){let t=u(this,ee)?.state??ds();v(this,$e,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},fs=function(t){M.batch(()=>{if(u(this,ke)&&this.hasListeners()){let n=u(this,$e).variables,r=u(this,$e).context,s={client:u(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,ke).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,ke).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,$e))})})},Ai);var Ee,Oi,Mi=(Oi=class extends le{constructor(t={}){super();b(this,Ee);this.config=t,v(this,Ee,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??hn(s,n),a=this.get(i);return a||(a=new yi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){u(this,Ee).has(t.queryHash)||(u(this,Ee).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Ee).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Ee).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Ee).get(t)}getAll(){return[...u(this,Ee).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Jn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Jn(t,r)):n}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){M.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ee=new WeakMap,Oi);var D,Be,Ge,Nt,Qt,ze,Kt,Lt,ki,hs=(ki=class{constructor(e={}){b(this,D);b(this,Be);b(this,Ge);b(this,Nt);b(this,Qt);b(this,ze);b(this,Kt);b(this,Lt);v(this,D,e.queryCache||new Mi),v(this,Be,e.mutationCache||new Ii),v(this,Ge,e.defaultOptions||{}),v(this,Nt,new Map),v(this,Qt,new Map),v(this,ze,0)}mount(){en(this,ze)._++,u(this,ze)===1&&(v(this,Kt,Pt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onFocus())})),v(this,Lt,Ot.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onOnline())})))}unmount(){var e,t;en(this,ze)._--,u(this,ze)===0&&((e=u(this,Kt))==null||e.call(this),v(this,Kt,void 0),(t=u(this,Lt))==null||t.call(this),v(this,Lt,void 0))}isFetching(e){return u(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(pe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(this,D).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=u(this,D).get(r.queryHash)?.state.data,a=oi(t,i);if(a!==void 0)return u(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return M.batch(()=>u(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state}removeQueries(e){let t=u(this,D);M.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,D);return M.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=M.batch(()=>u(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return M.batch(()=>(u(this,D).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=M.batch(()=>u(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=u(this,D).build(this,t);return n.isStaleByTime(pe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Ut(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Ut(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ot.isOnline()?u(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,D)}getMutationCache(){return u(this,Be)}getDefaultOptions(){return u(this,Ge)}setDefaultOptions(e){v(this,Ge,e)}setQueryDefaults(e,t){u(this,Nt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Nt).values()],n={};return t.forEach(r=>{st(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Qt).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Qt).values()],n={};return t.forEach(r=>{st(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,Ge).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=hn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,Ge).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,D).clear(),u(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,Ge=new WeakMap,Nt=new WeakMap,Qt=new WeakMap,ze=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,ki);var jt=j(oe(),1),Di=j(sr(),1),ms=jt.createContext(void 0),N=e=>{let t=jt.useContext(ms);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Cn=({client:e,children:t})=>(jt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Di.jsx)(ms.Provider,{value:e,children:t}));var ir=j(oe(),1),Ui=ir.createContext(!1),Ni=()=>ir.useContext(Ui),wd=Ui.Provider;var Pn=j(oe(),1),mc=j(sr(),1);function gc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var yc=Pn.createContext(gc()),Qi=()=>Pn.useContext(yc);var Ki=j(oe(),1);var Li=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Tt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},ji=e=>{Ki.useEffect(()=>{e.clearReset()},[e])},Vi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Tt(n,[e.error,r]));var Hi=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Wi=(e,t)=>e.isLoading&&e.isFetching&&!t,$i=(e,t)=>e?.suspense&&t.isPending,gs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Je=j(oe(),1);function or(e,t,n){let r=Ni(),s=Qi(),i=N(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let o=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",Hi(a),Li(a,s,o),ji(s);let c=!i.getQueryCache().get(a.queryHash),[l]=Je.useState(()=>new t(i,a)),d=l.getOptimisticResult(a),h=!r&&e.subscribed!==!1;if(Je.useSyncExternalStore(Je.useCallback(f=>{let p=h?l.subscribe(M.batchCalls(f)):q;return l.updateResult(),p},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Je.useEffect(()=>{l.setOptions(a)},[a,l]),$i(a,d))throw gs(a,l,s);if(Vi({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!Re.isServer()&&Wi(d,r)&&(c?gs(a,l,s):o?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return or(e,wn,t)}var qe=j(oe(),1);function De(e,t){let n=N(t),[r]=qe.useState(()=>new ps(n,e));qe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=qe.useSyncExternalStore(qe.useCallback(a=>r.subscribe(M.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=qe.useCallback((a,o)=>{r.mutate(a,o).catch(q)},[r]);if(s.error&&Tt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function En(e,t){return or(e,ls,t)}var Vt=null;function Bi(e){if(Vt&&Vt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Vt=e}function E(){return Vt||(Vt=new hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Vt}var Gi=new Proxy({},{get(e,t,n){let r=E(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return fe()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function zi(){return new Date().toISOString()}function Ji(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function me(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||zi(),updated_at:e.updated_at||zi(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function xn(e){return(e.content?.items||e.items||[]).map(me)}async function cr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=me(t);return r.path&&E().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=me(n);return r.path&&E().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function ur(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return me(t);let n=t.item;return n?me(n):null}catch{return null}}async function lr(e){try{let t=await R("list",{path:e,limit:200}),n=xn(t);for(let r of n)E().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function dr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=xn(r);for(let i of s)E().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function fr(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,o=i.type_data;!a||!o||s.set(a,{type_key:a,display_name:o.display_name||a,display_name_plural:o.display_name_plural||a+"s",icon:o.icon||"File",color:o.color||"gray",description:o.description||"",input_schema:o.input_schema||{},system_schema:o.system_schema||{},json_schema:o.input_schema||o.json_schema||{},default_data:o.default_data||{},field_defaults:o.field_defaults||{},renderer_config:o.renderer_config||{},is_system:o.is_system??!1,is_active:o.is_active??!0,is_container:o.is_container??!1,is_scope:o.is_scope??!1,render_mode:o.render_mode||"none",placement_mode:o.placement_mode,direct_parent_types:o.direct_parent_types,allowed_parent_types:o.allowed_parent_types,governed_create:o.governed_create,create_method:o.create_method,dedup:o.dedup,edges:o.edges,events:o.events})}return s}async function pr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Ji(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||Ji(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function hr(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await R("tree",s),a=xn(i);for(let o of a)E().setQueryData(w.item(o.path),o);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function mr(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function Tn(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function gr(e,t=50,n=0){return Tn(e,{limit:t,offset:n})}async function yr(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=xn(s);for(let a of i)E().setQueryData(w.item(a.path),a);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function _r(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}async function In(e){let t={item_type:e.type};e.scope&&(t.scope_path=e.scope);let n={};if(e.name&&(n.name=e.name),e.tag&&(n.tag=e.tag),e.parent_id&&(n.parent_id=e.parent_id),e.sort_by&&(n.sort_by=e.sort_by),e.sort_dir&&(n.sort_dir=e.sort_dir),e.offset!=null&&(n.offset=e.offset),e.fields)for(let[r,s]of Object.entries(e.fields))n[`field.${r}`]=String(s);Object.keys(n).length>0&&(t.filters=n),e.limit!=null&&(t.limit=e.limit);try{let r=await R("query",t),s=xn(r);for(let i of s)E().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch items of type ${e.type}:`,r),{items:[],total_hint:0}}}function _c(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function Yi(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:_c(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ys(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Xi(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ys(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function vr(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=ys(i),o=Yi(i),c=new Map,l=[];for(let d of o)if(d.parentMessagePath){let h=c.get(d.parentMessagePath)||[];h.push(d),c.set(d.parentMessagePath,h)}else l.push(d);return{messages:a,messageCards:c,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function An(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],a=Yi(i),o=new Map,c=[];for(let l of a)if(l.parentMessagePath){let d=o.get(l.parentMessagePath)||[];d.push(l),o.set(l.parentMessagePath,d)}else c.push(l);return{messages:ys(i),messageCards:o,siblingCards:c,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function ar(e){E().invalidateQueries({queryKey:w.children(e)})}function _s(e){E().invalidateQueries({queryKey:w.item(e)})}function Zi(e,t){_s(e),ar(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ar(r)}function eo(e){let t=e+"/";E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function to(){E().invalidateQueries({queryKey:w.all()})}function no(e){E().invalidateQueries({queryKey:w.types(e)})}function ro(e,t){e?E().invalidateQueries({queryKey:w.channelMessages(e,t)}):E().invalidateQueries({queryKey:w.allChannelMessages()})}function so(e,t){e&&t?E().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):E().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var vc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){vc&&console.log("[WS]",...e)}var A=null,Ht=null,Wt=null,On=0,bc=3e4,io=1e4,Bt=!1,co=3e4,wc=co*2+5e3,br=0,wr=null,oo=!1;function Sc(){kn(),br=Date.now(),wr=setInterval(()=>{if(A&&A.readyState===WebSocket.OPEN&&Date.now()-br>wc){W("ping: no inbound traffic for",Date.now()-br,"ms \u2014 closing half-open socket");try{A.close(4e3,"liveness timeout")}catch{}return}Ue({type:"ping"})},co)}function kn(){wr&&(clearInterval(wr),wr=null)}function Rc(){typeof document>"u"||(document.hidden?kn():Mn()&&(W("Tab visible, reconnecting..."),Fn()))}function Cc(){oo||typeof document>"u"||(document.addEventListener("visibilitychange",Rc),oo=!0)}var te={},$t=[],Gt=new Map,pt=new Map;function Pc(){return Object.keys(te).some(t=>te[t]&&te[t].length>0)||$t.length>0}function Mn(){return Gt.size>0||pt.size>0}async function Fn(){if(!Mn()){W("ensureConnection: no active subscriptions, skipping");return}if(A&&A.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Ht)return W("ensureConnection: connection already in flight, waiting..."),Ht;if(A){W("ensureConnection: killing stale WS in state",A.readyState);try{A.close()}catch{}A=null}return Bt=!1,Ht=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await xe();if(!n){W("ensureConnection: no token available, will retry"),ao();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),A=new WebSocket(i),await new Promise((a,o)=>{if(!A)return o(new Error("WebSocket not created"));let c=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",io,"ms"),A&&A.readyState!==WebSocket.OPEN){try{A.close()}catch{}A=null}o(new Error("WebSocket connection timeout"))},io);A.onopen=()=>{clearTimeout(c),W("ensureConnection: CONNECTED"),On=0,Ec(),(typeof document>"u"||!document.hidden)&&Sc(),Cc(),a()},A.onmessage=l=>{xc(l.data)},A.onerror=()=>{W("ensureConnection: WS error event")},A.onclose=l=>{clearTimeout(c),W("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),A=null,kn(),!Bt&&Mn()&&ao(),o(new Error(`WebSocket closed: ${l.code}`))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Ht=null}})(),Ht}function ao(){if(Wt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,On)+Math.random()*1e3,bc);On++,W("scheduleReconnect: attempt",On,"in",Math.round(e),"ms"),Wt=setTimeout(()=>{Wt=null,Mn()&&Fn()},e)}function Ec(){for(let e of Gt.values())W("resubscribeAll: scope",e.scope_id),Ue({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of pt.values())W("resubscribeAll: path",e.path),Ue({type:"subscribe_path",path:e.path,event_types:e.event_types})}function Ue(e){A&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify(e))}function xc(e){br=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed"||t.type==="subscribed_path"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;r.path&&te[r.path]&&te[r.path].forEach(s=>s(r)),te["*"]&&te["*"].forEach(s=>s(r));for(let s of $t)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function vs(){!Pc()&&Gt.size===0&&pt.size===0&&A&&(Bt=!0,kn(),A.close(),A=null,Bt=!1)}function Sr(e,t){return te[e]||(te[e]=[]),te[e].push(t),pt.has(e)||(pt.set(e,{path:e,event_types:["token_stream"]}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe_path",path:e,event_types:["token_stream"]})),Fn(),()=>{let n=te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete te[e],pt.delete(e),Ue({type:"unsubscribe_path",path:e}))}vs()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return $t.push(...s),Mn()&&Fn(),()=>{for(let i of s){let a=$t.indexOf(i);a!==-1&&$t.splice(a,1)}vs()}}function Rr(e,t=["vfs_change","ccm_change"]){return W("subscribeToScope:",e,t),Gt.set(e,{scope_id:e,event_types:t}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe",scope_id:e,event_types:t}),Fn(),()=>{Gt.delete(e),Ue({type:"unsubscribe",scope_id:e}),vs()}}function uo(e,t,n={}){Ue({type:"emit",scope_id:e,event_type:t,payload:n})}function bs(){W("disconnectSSE: tearing down"),Bt=!0,kn(),A&&(A.close(),A=null),Wt&&(clearTimeout(Wt),Wt=null),Ht=null,Bt=!1,On=0;for(let e of Object.keys(te))delete te[e];$t.length=0,Gt.clear(),pt.clear()}function lo(){Ue({type:"ping"})}Te(bs);var zt=new Map,Cr=null,Pr=null,Ye=new Map,fo=250;function qn(e){Er(),Dn(e),Cr=J("vfs_change",t=>Tc(t)),Pr=J("ccm_change",t=>Ic(t))}function Dn(e){if(zt.has(e))return;let t=Rr(e,["vfs_change","ccm_change"]);zt.set(e,t)}function po(e){let t=zt.get(e);t&&(t(),zt.delete(e))}function Er(){for(let[,e]of zt)e();zt.clear(),Cr&&(Cr(),Cr=null),Pr&&(Pr(),Pr=null),Ye.forEach(e=>clearTimeout(e)),Ye.clear()}Te(Er);function Tc(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),Ac(n,t,e,s)},fo);Ye.set(s,a)}function Ic(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),t&&E().invalidateQueries({queryKey:w.edges(t)}),n&&E().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&E().invalidateQueries({predicate:o=>o.queryKey[0]==="vfs"&&o.queryKey[1]==="edges"})},fo);Ye.set(s,a)}function Ac(e,t,n,r){if((e||"").toUpperCase()==="DELETE")E().removeQueries({queryKey:w.item(t)}),E().removeQueries({queryKey:w.children(t)}),E().removeQueries({queryKey:w.tree(t)});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=me(i);a&&a.id&&E().setQueryData(w.item(t),a)}catch{}E().invalidateQueries({queryKey:w.children(r)}),E().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let o=a[2];return t.startsWith(o+"/")||t===o}}),n.item_id&&E().invalidateQueries({queryKey:w.itemById(n.item_id)})}var ws=j(oe(),1),go=j(mo(),1);function yo(e){return R("read",{path:e})}function _o(e,t){return R("list",{path:e,...t})}function vo(e){return R("create",e)}function bo(e){return R("update",e)}function wo(e){return R("create",e)}function So(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Ro(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Co(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Po={signIn:e=>e.provider?k.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>k.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),bt(),E().clear()},getSession:()=>k.auth.getSession().then(e=>e.data.session),getUser:()=>k.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=k.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>k.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>k.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Eo(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.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=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,go.createRoot)(e).render((0,ws.createElement)(Cn,{client:E()},(0,ws.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function xo(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var _=j(oe(),1),Mc=j(Io(),1),kc=j(sr(),1);function Oc(e){return`${e}/settings/mounts`}var Un=null;async function Ss(e,t){Un=Oc(e);try{let s=((await R("read",{path:Un}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Qe();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Vr(s),s}catch{let n=Qe(),r=n?[n]:[];return Vr(r),r}}async function Ao(){if(!Un)return;let e=_t().map(n=>n.id),t=Ze()?.id??null;try{await R("update",{path:Un,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Un.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function Rs(e){js(e),await Ao()}async function Oo(e){Vs(e),await Ao()}function K(){return(0,_.useSyncExternalStore)(tt,be,be)}function Fo(){return K(),Bn()}function qo(e){return K(),F({queryKey:w.item(e),queryFn:()=>ur(e),enabled:!!e})}function Do(e){return K(),F({queryKey:w.itemById(e),queryFn:()=>cr(e),enabled:!!e})}function Ps(e){return K(),F({queryKey:w.children(e),queryFn:()=>lr(e),enabled:!!e})}function Uo(e){let t=Ps(e);return{...t,children:t.data??[]}}function No(e,t=1){return K(),F({queryKey:w.tree(e,t),queryFn:()=>hr(e,t),enabled:!!e})}function Qo(e,t){return K(),F({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||r.results||[]).map(me)},enabled:!!e&&e.length>0})}function Ko(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:["vfs",fe()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Lo(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>In(t),enabled:!!t?.type,select:n=>n.items})}function jo(e){K();let t=e?.limit??20,n=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),r=En({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>In({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,o)=>{if(!(i.items.length<t))return o+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let o of r.data.pages)for(let c of o.items)c.id&&!i.has(c.id)&&(i.add(c.id),a.push(c));return a},[r.data?.pages]),fetchNextPage:r.fetchNextPage,isFetchingNextPage:r.isFetchingNextPage,isExhausted:!r.hasNextPage,isLoading:r.isLoading,isFetching:r.isFetching,error:r.error,totalHint:r.data?.pages?.[0]?.total_hint}}function Vo(e){K();let t=20,n=En({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>dr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<t))return a+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let o of a.items)o.id&&!s.has(o.id)&&(s.add(o.id),i.push(o));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Ho(e){return K(),F({queryKey:w.edges(e),queryFn:()=>pr(e),enabled:!!e})}function xr(e){return K(),F({queryKey:w.types(e),queryFn:()=>fr(e)})}function Wo(e,t){let n=xr(t);return{...n,data:n.data?.get(e)??void 0}}function $o(e,t){K();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return F({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await _r(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let o=a.render.props.url,c=o.includes("?")?"&":"?";a.render.props.url=`${o}${c}w=${i}`}return a},enabled:!!e})}var Mo={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 Bo(e){let t=xr(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Mo).map(([p,y])=>({key:p,label:y})),getEdgeTypeLabel:p=>Mo[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Go(e,t,n){return K(),F({queryKey:w.memberFocus(e),queryFn:()=>yr(e,t,n),enabled:!!e})}function zo(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return F({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Tn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Jo(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>gr(e,t,n),enabled:!!e})}function Yo(e,t=50,n=0){return K(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>mr(e,t,n),enabled:!!e})}function Xo(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let a=!1;return vt().then(o=>{if(!a){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:o.scope_path,scope_id:o.scope_id,fractal_id:o.fractal_id,instance_name:o.instance_name,display_name:o.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(o=>{a||(i(o instanceof Error?o:new Error(String(o))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var Fc=[];function Nn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function Zo(){let{user:e}=Tr(),t=(0,_.useRef)(!1),n=F({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??Fc,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),h=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,p)=>Number(h(p))-Number(h(f)))},[s]),a=(0,_.useSyncExternalStore)(tt,be,be),o=(0,_.useMemo)(()=>{let d=Ze();return d?r.find(h=>h.accountId===d.id)??null:null},[a,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];cn(Nn(d)),qn(d.accountId),d.personalSpacePath&&Ss(d.personalSpacePath,h=>{let f=r.find(p=>p.accountId===h);return f?Nn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let h=r.find(p=>p.path===d);if(!h)return;let f=Nn(h);Qe()?Ne(f):(cn(f),h.personalSpacePath&&Ss(h.personalSpacePath,p=>{let y=r.find(m=>m.accountId===p);return y?Nn(y):null}).catch(()=>{})),qn(h.accountId)},[r]),l=(0,_.useCallback)(d=>{let h=r.find(f=>f.path===d);h&&(Rs(Nn(h)).catch(()=>{}),Dn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:o,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function ea(){let e=(0,_.useSyncExternalStore)(Wn,ln,ln);return{mounts:(0,_.useMemo)(()=>_t(),[e]),homeAnchor:Qe(),anchor:Ze(),setAnchor:Ne,mount:Rs,unmount:Oo}}function Tr(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{k.auth.getSession().then(({data:p,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=k.auth.onAuthStateChange((p,y)=>{if(p==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let o=(0,_.useCallback)(async f=>f.provider?k.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>k.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await k.auth.signOut(),bt(),E().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:p}=await k.auth.resetPasswordForEmail(f);if(p)throw p},[]),h=(0,_.useCallback)(async(f,p)=>{let{error:y}=await k.auth.signInWithOtp({email:f,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:o,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:h}}function ta(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):a(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{a(c instanceof Error?c:new Error(String(c))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Qn={},ko={};Te(()=>{for(let e of Object.keys(Qn))delete Qn[e]});var na=null;function ra(e){na=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function qc(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Mc;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}:kc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||na||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Dc(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Uc(e,t){if(!ko[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=Dc(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),ko[e]=s}catch{}}function Nc(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
- `),i=new Function(r)(qc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Es(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let o=!1;s(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,h=e+"@v1",f=l+e+"/__bundle.js";try{let S=await fetch(l+e+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,h=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(o)return;if(Qn[h]){n(()=>Qn[h]),s(!1);return}let p=await fetch(f);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${f})`);let y=await p.text();if(o)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Uc(m).catch(()=>{});let g=Nc(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);Qn[h]=g,o||(n(()=>g),s(!1))}catch(d){o||(a(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{o=!0}},[e]),{Component:t,loading:r,error:i}}var Qc=["--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 sa(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Qc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function ia(e,t){return{data:{allowed:!0},loading:!1,error:null}}function oa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,Jt=null,Cs=new Set;function Kc(){Cs.forEach(e=>e())}Te(()=>{ae=null,Jt=null});async function aa(e){let t=e;if(!t){let{data:r}=await k.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(ae&&ae.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}}return Jt||(Jt=(async()=>{try{let{data:r,error:s}=await k.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:c}=await k.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(c??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let o={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return ae={authUserId:t,...o},o}finally{Jt=null}})(),Jt)}async function ca(e){return(await aa(e)).principalId}function ua(){let e=Tr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let a=()=>{let o=ae;o&&o.authUserId===t?.id&&s({principalId:o.principalId,displayName:o.displayName,createdAt:o.createdAt,metadata:o.metadata,vfsPath:o.vfsPath})};return Cs.add(a),()=>{Cs.delete(a)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,aa(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function la(){return{data:null,loading:!1,error:null}}function da(e){let{path:t,...n}=e,r=Es(t),s=r.Component,{loading:i,error:a}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):a?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function fa(e){return e.children}function pa(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,o=(0,_.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),c=N(),l=(0,_.useRef)(null),d=F({queryKey:o,queryFn:()=>vr(n,r),enabled:a});(0,_.useEffect)(()=>{if(!s||!a)return;let m=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:o})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),l.current&&clearTimeout(l.current)}},[s,a,n,o,c]);let h=d.data,f=h?.messages??[],p=h?.messageCards??new Map,y=h?.siblingCards??[];return{messages:f,messageCards:p,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ha(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,o=i&&!!t,c=En({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:m})=>An(t,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:o}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let m=new Set,g=[];for(let S of c.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[c.data?.pages]),{messageCards:d,siblingCards:h}=(0,_.useMemo)(()=>{let m=new Map,g=[];if(!c.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of c.data.pages){for(let[x,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let $=m.get(x)||[];$.push(L),m.set(x,$)}for(let x of C.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:m,siblingCards:g}},[c.data?.pages]),f=N(),p=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!o)return;let m=J("vfs_change",()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(async()=>{let g=f.getQueryData(y);if(!g?.pages?.length){f.invalidateQueries({queryKey:y});return}let S=0;for(let C of g.pages)for(let x of C.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:y});return}try{let C=await An(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:y});return}if(C.messages.length>0){let x=Math.min(...C.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:y});return}}f.setQueryData(y,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,$=U[L],ht=new Set($.messages.map(I=>I.id)),re=C.messages.filter(I=>!ht.has(I.id)),Q=[...$.messages,...re].sort((I,Xe)=>I.seq-Xe.seq),Y=new Map($.messageCards);for(let[I,Xe]of C.messageCards){let B=Y.get(I)||[],Yt=new Set(B.map(Mr=>Mr.id)),Qa=Xe.filter(Mr=>!Yt.has(Mr.id));Y.set(I,[...B,...Qa])}let ye=new Set($.siblingCards.map(I=>I.id)),_e=C.siblingCards.filter(I=>!ye.has(I.id)),ve=[...$.siblingCards,..._e];return U[L]={...$,messages:Q,messageCards:Y,siblingCards:ve},{...x,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:y})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{m(),p.current&&clearTimeout(p.current)}},[s,t,o,y,f,n,r]),{messages:l,messageCards:d,siblingCards:h,threads:l.filter(m=>m.reply_count>0),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch,hasPreviousPage:c.hasPreviousPage??!1,fetchPreviousPage:c.fetchPreviousPage,isFetchingPreviousPage:c.isFetchingPreviousPage??!1,hasNextPage:c.hasNextPage??!1,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage??!1}}function Lc(e){return e==="on"||e==="auto"?"on":"off"}function jc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:Lc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function Ir(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=N(),i=(0,_.useRef)(null),a=(0,_.useMemo)(()=>w.channels("all"),[t]),o=F({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(jc),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message"),d=J("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function ma(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function ga(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function xs(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=N(),o=(0,_.useRef)(null),c=(0,_.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:c,queryFn:async()=>{let h={limit:r};return n==="unread"&&(h.filter="unread"),(await R("get-notifications",h)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let h=["vfs_change","ccm_change"].map(f=>J(f,()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"||p.item_type==="message"));return()=>{h.forEach(f=>f()),o.current&&clearTimeout(o.current)}},[s,i,c,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function ya(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:o,refetch:c}=xs({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let p=new Map;for(let y of s)y.is_unread&&y.channel_id&&p.set(y.channel_id,(p.get(y.channel_id)||0)+1);return p},[s]),d=(0,_.useMemo)(()=>{let p=0;return l.forEach(y=>{p+=y}),p},[l]),{dmUnread:h,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,m=0;return l.forEach((g,S)=>{p.has(S)?y+=g:m+=g}),{dmUnread:y,channelUnread:m}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:h,channelUnread:f,isLoading:i,isFetching:a,error:o,refetch:c}}function _a(){let e=N();return De({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function va(){let e=N();return De({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function ba(){return De({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ae)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ae.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ae={...ae,displayName:typeof t.display_name=="string"?t.display_name:ae.displayName,metadata:n},Kc()}})}function wa(){let e=N();return De({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function Sa(){let e=N();return De({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:w.item(r)});let i=r.split("/");i.pop();let a=i.join("/");a&&e.invalidateQueries({queryKey:w.children(a)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function Ra(){let e=N();return De({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:w.edges(r)}),s&&e.invalidateQueries({queryKey:w.edges(s)})}})}function Ca(e,t){let n=N(),{optimistic:r,...s}=t??{};return De({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,o=>r.update(o,i)),{previous:a}}:void 0,onError:(i,a,o)=>{r&&o?.previous!==void 0&&n.setQueryData(r.queryKey,o.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Pa(e,t,n){let r,s,i,a=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,a=l.enabled??!0}let o=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{o.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>a?J(r,d=>o.current(d),c.current?d=>c.current(d):void 0):void 0,[r,a])}function Ea(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,o=N(),c=(0,_.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=J(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:t})},a)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,a,o,JSON.stringify(t)]),l}function xa(e){K();let t=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=F({queryKey:["vfs",fe()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let d=await R("resolve-arrangement",t);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=s.data??null,a=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),o=i?.resolution_level??null,c=(0,_.useMemo)(()=>{let h=(i?.type_data??null)?.order;return Array.isArray(h)?h:null},[i]),l=(0,_.useCallback)(d=>{if(!c||!d?.length)return d??[];let h=m=>m.id??m.name??"",f=new Map(c.map((m,g)=>[m,g])),p=[],y=[];for(let m of d)(f.has(h(m))?p:y).push(m);return p.sort((m,g)=>f.get(h(m))-f.get(h(g))),[...p,...y]},[c]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:o,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function Vc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Hc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Wc(e,t){return!(e==="object"||e==="array")}function $c(e){return["string","number","integer","boolean"].includes(e)}function Bc(e){return e!=="object"&&e!=="array"}function Ta(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,o]of Object.entries(s)){let c=o.type||"string",l=o.enum,d=Wc(c,l),h=$c(c),f=Hc(c,l);i.push({key:a,label:o.title||Vc(a),type:c,description:o.description,enum_values:l,default_value:n[a]??r[a]??o.default,editable:t,filterable:d,sortable:h,filter_widget:f})}return i}function Ts(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ta(e.input_schema,!0,t,n),s=Ta(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(l=>Bc(l.type)),o=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:o,sortable:c,form_fields:r,system_fields:s}}function Ia(e){return{field:"updated_at",direction:"desc"}}function Aa(e){let t=Ts(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ne=j(oe(),1);var Gc=0;function zc(){return`upload_${Date.now()}_${++Gc}`}async function Oa(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",a=t.itemType||"file",o={parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(o.card_parent_path=t.cardParentPath);let l=await R("create",o);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,h=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:h,fileRef:l.file_ref};let f=l.storage_key,p=l.upload_token,y=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Jc(y,f,p,e,i,n,r);let m=await Ma(d,f,i);return{itemId:d,itemPath:h,fileRef:m}}function Jc(e,t,n,r,s,i,a){return new Promise((o,c)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?o():c(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>c(new Error("Storage upload network error")),l.ontimeout=()=>c(new Error("Storage upload timed out")),a){if(a.aborted){c(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),c(new Error("Upload cancelled"))})}l.send(r)})}async function Ma(e,t,n){let r=await xe(),s=await fetch(`${ce}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${a.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function ka(){let[e,t]=(0,ne.useState)([]),n=N(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((m,g)=>{t(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,ne.useCallback)(m=>{t(g=>[...g,m])},[]),a=(0,ne.useCallback)(async(m,g,S,C,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",$=S.itemType||"file",ht=x?.itemId||null,re=x?.itemPath||null,Q=x?.storageKey||null,Y=x?.uploadToken||null,ye=x?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let I=await R("create",{parent_path:S.parentPath,item_type:$,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!I.id)throw Object.assign(new Error(I.error||I.message||"Failed to create file item"),{_step:"create"});if(ht=I.id,re=I.path,s(m,{itemId:ht,itemPath:re}),I.storage_completed&&I.file_ref){s(m,{status:"complete",progress:100,fileRef:I.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=I.storage_key,Y=I.upload_token||"",ye=I.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:Q,_uploadToken:Y,_storageWorkerUrl:ye}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((I,Xe)=>{let B=new XMLHttpRequest;s(m,{_xhr:B}),B.open("PUT",`${ye}/upload`),B.setRequestHeader("X-Storage-Key",Q),B.setRequestHeader("Content-Type",L),Y&&B.setRequestHeader("X-Upload-Token",Y),B.upload.onprogress=Yt=>{Yt.lengthComputable&&s(m,{progress:Math.round(Yt.loaded/Yt.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?I():Xe(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>Xe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>Xe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let _e=await Ma(ht,Q,L);s(m,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),I=_e?._step||"create";s(m,{status:"error",error:ve,_failedAt:I,_xhr:null})}},[s,n]),o=(0,ne.useCallback)((m,g)=>{let S=zc();i({id:S,file:m,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,m,g)},[i,a]),c=(0,ne.useCallback)((m,g)=>{for(let S of m)o(S,g)},[o]),l=(0,ne.useCallback)(m=>{let g=r.current.find(x=>x.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(m,g.file,g.options,S,C)},[a]),d=(0,ne.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),h=(0,ne.useCallback)(m=>{t(g=>g.filter(S=>S.id!==m))},[]),f=(0,ne.useCallback)(()=>{t(m=>m.filter(g=>g.status!=="complete"))},[]),p=e.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),y=e.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:x,...U})=>U);return{upload:o,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:h,clearCompleted:f,isUploading:p}}var Fa=j(oe(),1);async function Is(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function qa(e,t){return(0,Fa.useSyncExternalStore)(tt,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Is(e,t),enabled:!!(e&&t)})}var ge=j(oe(),1);function Ar(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let c,l=a.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(a.artifact_id)c=a;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let h=r.get(c.tool_id);n.timeline[h].artifact_ids.push(c.artifact_id)}else{let h=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,h)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let h=r.get(c.tool_id);if(h!==void 0){let f=n.timeline[h];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return Sr(e,s)}function Da(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),a=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,h=>{a.current=h,r(new Map(h.artifacts)),i([...h.timeline])}),[e,t]);let o=(0,ge.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:l,reset:o}}function Ua(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Or=j(oe(),1);function Yc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function As(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let o=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return o?(o.rows??o.items??o.data??[]).map(Xc).sort((l,d)=>l.seq-d.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function Na(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},o=e?`${e}/datasets/agent-events`:null,c=N(),l=(0,Or.useRef)(null),d=o?Yc(o,n,r,s):["vfs","timeline-history","__disabled__"],h=F({queryKey:d,queryFn:()=>As(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Or.useEffect)(()=>{if(!o||!i)return;let f=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},a)},p=>{let y=p?.path;return y?y===o||y.startsWith(o+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[o,i,a,c,JSON.stringify(d)]),{events:h.data??[],isLoading:h.isLoading,error:h.error,isFetching:h.isFetching,refetch:()=>{h.refetch()}}}function Xc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}ra(Os);return Ba(Os);})();
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-28T18:37:27.293Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var La=Object.create;var Xt=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var Va=Object.getOwnPropertyNames;var Ha=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var ks=e=>{throw TypeError(e)};var $a=(e,t,n)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Zt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ba=(e,t)=>{for(var n in t)Xt(e,n,{get:t[n],enumerable:!0})},Fs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Va(t))!Wa.call(e,s)&&s!==n&&Xt(e,s,{get:()=>t[s],enumerable:!(r=ja(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?La(Ha(e)):{},Fs(t||!e||!e.__esModule?Xt(n,"default",{value:e,enumerable:!0}):n,e)),Ga=e=>Fs(Xt({},"__esModule",{value:!0}),e);var re=(e,t,n)=>$a(e,typeof t!="symbol"?t+"":t,n),kr=(e,t,n)=>t.has(e)||ks("Cannot "+n);var u=(e,t,n)=>(kr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?ks("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(kr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),P=(e,t,n)=>(kr(e,t,"access private method"),n);var en=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return u(e,t,r)}});var Ds=Zt((ru,qs)=>{qs.exports={createClient:window.supabase.createClient}});var ie=Zt((vd,qi)=>{qi.exports=React});var sr=Zt((bd,Di)=>{Di.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var go=Zt((mf,mo)=>{mo.exports=ReactDOM});var Ao=Zt((Sf,Io)=>{Io.exports=ReactDOM});var Ms={};Ba(Ms,{ComponentRenderer:()=>fa,EnforcementDeniedError:()=>mt,FormSubmissionError:()=>Rt,InteractionTrackingError:()=>wt,KernelProvider:()=>pa,QueryClientProvider:()=>Cn,auth:()=>Eo,awaitAnchorReady:()=>an,awaitScopeReady:()=>Bs,callTool:()=>Ro,clearCachedToken:()=>Ur,clearSession:()=>Hr,createItem:()=>bo,disconnectSSE:()=>ws,disposeVfsRealtimeWs:()=>Er,electHomeAnchor:()=>cn,emitEvent:()=>lo,fetchChannelMessages:()=>Zi,fetchChannelMessagesPage:()=>An,fetchChannelMessagesWithCards:()=>vr,fetchEdgesForItem:()=>pr,fetchItemHistory:()=>gr,fetchItemVersions:()=>Tn,fetchItems:()=>In,fetchMemberFocus:()=>yr,fetchOpenEnvelope:()=>_r,fetchRecentActivity:()=>mr,fetchResolvedItems:()=>As,fetchTimelineHistory:()=>Os,fetchTypeDefinitions:()=>fr,fetchVfsChildren:()=>lr,fetchVfsChildrenPage:()=>dr,fetchVfsItem:()=>ur,fetchVfsItemById:()=>cr,fetchVfsTree:()=>hr,gatewayCall:()=>R,getAccessToken:()=>xe,getAnchor:()=>on,getAnchorRef:()=>Ze,getAnchorVersion:()=>Kr,getAssetUrl:()=>Po,getDefaultSort:()=>Aa,getHomeAnchor:()=>Qe,getMountVersion:()=>ln,getMounts:()=>_t,getQueryClient:()=>E,getRequiredFormFields:()=>Oa,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>$n,initSession:()=>vt,initVfsRealtimeWs:()=>qn,initializeFsaos:()=>ei,interpretSchema:()=>Is,invalidateAllVfs:()=>no,invalidateChannelMessages:()=>so,invalidateChildren:()=>ar,invalidateItem:()=>_s,invalidateOpenEnvelope:()=>io,invalidatePathAndParent:()=>eo,invalidateSubtree:()=>to,invalidateTypes:()=>ro,isAnchorReady:()=>jr,isScopeReady:()=>Bn,listChildren:()=>vo,mount:()=>xo,mountRealtimeScope:()=>Dn,normalizeItem:()=>me,pathSubscriptionMatches:()=>vs,ping:()=>fo,pushChanges:()=>So,queryClient:()=>zi,readItem:()=>_o,registerCleanup:()=>Te,resetAllSdkState:()=>bt,resolvePrincipalId:()=>ua,setAnchor:()=>Ne,setCachedToken:()=>Qs,setQueryClient:()=>Gi,setScope:()=>$s,setupRequireShim:()=>To,signal:()=>Co,startTracking:()=>Gn,submitForm:()=>ti,subscribeAnchor:()=>Lr,subscribeArtifactStream:()=>Ar,subscribeMounts:()=>Wn,subscribeScope:()=>tt,subscribeToEvents:()=>J,subscribeToPath:()=>Sr,subscribeToScope:()=>Rr,trackAction:()=>Xs,trackEvent:()=>nt,trackPageView:()=>Ys,unmountRealtimeScope:()=>ho,updateItem:()=>wo,uploadFile:()=>Ma,useAccounts:()=>ea,useAgentTimeline:()=>Na,useAllChannels:()=>Ir,useArrangement:()=>Ta,useArtifactStream:()=>Ua,useAsset:()=>na,useAuth:()=>Tr,useChannelMessages:()=>ha,useChannels:()=>ga,useChildren:()=>No,useComponent:()=>xs,useCreate:()=>va,useDelete:()=>Sa,useDmChannels:()=>ya,useEdges:()=>Wo,useEventStream:()=>Ea,useFileUpload:()=>Fa,useInfiniteChannelMessages:()=>ma,useInfiniteChildren:()=>Ho,useInfiniteItems:()=>Vo,useItem:()=>Do,useItemById:()=>Uo,useItemHistory:()=>Yo,useItemVersions:()=>Jo,useItems:()=>jo,useLink:()=>Ca,useList:()=>Es,useMemberFocus:()=>zo,useMounts:()=>ta,useMove:()=>Ra,useMutation:()=>Pa,useNotifications:()=>Ts,useOpen:()=>Bo,usePermission:()=>oa,usePermissions:()=>aa,usePrincipal:()=>la,useRealtimeQuery:()=>xa,useRecentActivity:()=>Xo,useResolve:()=>Lo,useResolvedItems:()=>Da,useScope:()=>Zo,useScopeReady:()=>qo,useSearch:()=>Ko,useTheme:()=>ia,useTimelineHistory:()=>Qa,useTool:()=>da,useTree:()=>Qo,useType:()=>$o,useTypeHelpers:()=>Go,useTypes:()=>xr,useUnreadCounts:()=>_a,useUpdate:()=>ba,useUpdatePrincipal:()=>wa,vfsKeys:()=>w});var mt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);re(this,"name","EnforcementDeniedError");re(this,"deniedBy");re(this,"ruleKey");re(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Us=j(Ds(),1),tn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},nn=Array.isArray(tn.sources)?tn.sources:[],za=tn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Ja=tn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=tn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,Us.createClient)(za,Ja,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var sn=null,Kn=0,Ns,Dr,Ln=!1;Ns=new Promise(e=>{Dr=e});k.auth.onAuthStateChange((e,t)=>{t?.access_token?(sn=t.access_token,Kn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(sn=null,Kn=0),Ln||(Ln=!0,Dr())});setTimeout(()=>{Ln||(Ln=!0,Dr())},5e3);function Qs(e,t){sn=e,Kn=t??Math.floor(Date.now()/1e3)+3600}function Ur(){sn=null,Kn=0}async function xe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Ns,sn}var jn=null,Hn=null,Ks=0,Fr=new Set,Nr,Qr,Vn=!1;Nr=new Promise(e=>{Qr=e});function Ls(){Ks++,Fr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Ne(e){let t=typeof e=="string"?e:e.path,n=jn!==t;jn=t,Hn=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],un()),Vn||(Vn=!0,Qr()),n&&Ls()}function on(){return jn}function Ze(){return Hn}function Kr(){return Ks}function Lr(e){return Fr.add(e),()=>{Fr.delete(e)}}function an(){return Nr}function jr(){return Vn}var yt=null;function cn(e){if(yt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}yt=e,Ne(e)}function Qe(){return yt}var ue=[],qr=new Set,js=0;function un(){js++,qr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function _t(){return ue}function ln(){return js}function Wn(e){return qr.add(e),()=>{qr.delete(e)}}function Vr(e){ue=e,un()}function Vs(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],un())}function Hs(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),un(),Hn?.id===e&&yt&&Ne(yt))}var gt=null,rn=null;async function vt(){return gt||rn||(rn=(async()=>{let e=et(),t=await xe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${ce}/d/${e}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return gt={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},gt})(),rn)}function $n(){return gt}function Hr(){gt=null,rn=null,jn=null,Hn=null,yt=null,ue=[]}var Ws=[];function Te(e){Ws.push(e)}function bt(){Hr(),Ur(),Vn=!1,Nr=new Promise(e=>{Qr=e}),Ls(),un();for(let e of Ws)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function et(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var $s=Ne,fe=on,be=Kr,tt=Lr,Bs=an,Bn=jr;var Wr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ya=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Gs=new Map,zs=new Map,wt=class extends Error{constructor(n,r,s,i){super(n);re(this,"code");re(this,"status");re(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function fn(e){let t=e?nn.find(n=>n.id===e):nn.find(n=>n.default===!0)??(nn.length===1?nn[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function $r(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function Xa(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Za(e,t){if(!Xa(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Br(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function ec(e){try{let t=Br(e)?.getItem(e.key)??void 0;return t&&Wr.test(t)?t:void 0}catch{return}}function Js(e,t){try{Br(e)?.setItem(e.key,t)}catch{}}function tc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=ec(t)??Gs.get(e.id);if(n)return n;let r=crypto.randomUUID();return Gs.set(e.id,r),Js(t,r),r}function nc(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let l=Br(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=zs.get(e.id),i=r&&typeof r.id=="string"&&Wr.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,a=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<a?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return zs.set(e.id,c),Js(n,JSON.stringify(c)),c.id}function rc(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,a=Object.fromEntries(n.flatMap(o=>{if(typeof o!="string"||o.length===0||o.length>128)return[];let c=r.searchParams.get(o);return c?[[o,c.slice(0,i)]]:[]}));return Object.keys(a).length>0?a:void 0}async function nt(e,t={},n={}){let r=fn(n.source);if(Za(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??tc(r),a=n.sessionId??nc(r);if(![s,i,a].every(g=>Wr.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let o=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!o)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=rc(r,o),h=d?{...t,source_keys:d}:t,f=et(),p=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:o,visitor_id:i,session_id:a,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:h}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new wt(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let m=null;try{m=await y.json()}catch{}if(!y.ok||m?.success!==!0){let g=m;throw new wt(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return m}function Ys(e={},t={}){let n=fn(t.source),r=$r("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return nt(r.observation,{...s,...e},{...t,source:n.id})}function Xs(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=fn(n.source),s=$r("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return nt(s.observation,{...t,...i},{...n,source:r.id})}function Zs(e,t={}){let n=fn(t.source),r=$r("form_receipt",n);return nt(r.observation,e,{...t,source:n.id})}var dn;function Gn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(dn)return dn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=fn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(f=>f.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(f=>f.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let f of n){let p=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};nt(f.observation,p,{source:t.id,keepalive:!0}).catch(()=>{})}}},a=f=>{if(f.target instanceof Element)for(let p of r){let y=p.attribute;if(!y||!Ya.test(y))continue;let m=f.target.closest(`[${y}]`);if(!m)continue;let g=m.getAttribute(y)?.trim();if(!g||g.length>128)continue;let S={};p.id_property&&(S[p.id_property]=g),p.element_property&&(S[p.element_property]=m.tagName.toLowerCase()),nt(p.observation,S,{source:t.id,keepalive:!0}).catch(()=>{})}},o=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),h=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...p){o.apply(this,p),l()},window.history.replaceState=function(...p){c.apply(this,p),l()},window.addEventListener("popstate",i)),h&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",a,{capture:!0}),n.length>0&&queueMicrotask(i),dn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",a,{capture:!0}),d&&(window.history.pushState=o,window.history.replaceState=c),dn=void 0},dn}var St;function ei(e={}){return St||(St=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Gn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await vt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),St=void 0)}}}catch(r){throw n(),St=void 0,r}})(),St)}var sc=new Set(["list-memberships","init"]);async function R(e,t={}){let n=et(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await xe();i&&(s.Authorization=`Bearer ${i}`),!sc.has(e)&&!t._scope_path&&await an();let a={...t},o=$n();!a.domain_scope_id&&o?.scope_id&&(a.domain_scope_id=o.scope_id);let c=on();!a._scope_path&&c&&(a._scope_path=c);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let d=await l.json();if(d.success===!1){let h=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||h==="RULE_DENIED"||h==="ACCESS_DENIED"||h==="PERMISSION_DENIED"||h==="ENTITLEMENT_REQUIRED"?new mt(d):new Error(d.message||d.error||`Gateway call ${e} failed`)}return d}var ic=/^[a-z][a-z0-9_-]{0,63}$/,oc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Rt=class extends Error{constructor(n,r,s,i){super(n);re(this,"code");re(this,"status");re(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function ti(e,t,n={}){if(!ic.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!oc.test(r))throw new TypeError("fillId must be a UUID");let s=et(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let a=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t}),signal:n.signal,credentials:"omit"})}catch(l){throw new Rt(l instanceof Error?l.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let c=null;try{c=await o.json()}catch{}if(!o.ok||c?.success!==!0){let l=c;throw new Rt(l?.message||l?.error||`Form submission failed (${o.status})`,l?.error||"FORM_SUBMISSION_FAILED",o.status,r)}try{await Zs({fill_id:r,action_id:e,release_id:c.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0})}catch{}return c}var le=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var rt,Ke,Ct,ni,ac=(ni=class extends le{constructor(){super();b(this,rt);b(this,Ke);b(this,Ct);v(this,Ct,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,Ke)||this.setEventListener(u(this,Ct))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,Ke))==null||t.call(this),v(this,Ke,void 0))}setEventListener(t){var n;v(this,Ct,t),(n=u(this,Ke))==null||n.call(this),v(this,Ke,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,rt)!==t&&(v(this,rt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,rt)=="boolean"?u(this,rt):globalThis.document?.visibilityState!=="hidden"}},rt=new WeakMap,Ke=new WeakMap,Ct=new WeakMap,ni),Pt=new ac;var cc={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Le,Gr,ri,uc=(ri=class{constructor(){b(this,Le,cc);b(this,Gr,!1)}setTimeoutProvider(e){v(this,Le,e)}setTimeout(e,t){return u(this,Le).setTimeout(e,t)}clearTimeout(e){u(this,Le).clearTimeout(e)}setInterval(e,t){return u(this,Le).setInterval(e,t)}clearInterval(e){u(this,Le).clearInterval(e)}},Le=new WeakMap,Gr=new WeakMap,ri),we=new uc;function si(e){setTimeout(e,0)}var Jr=typeof window>"u"||"Deno"in globalThis;function q(){}function ai(e,t){return typeof e=="function"?e(t):e}function pn(e){return typeof e=="number"&&e>=0&&e!==1/0}function zn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function pe(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Jn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:o}=e;if(a){if(r){if(t.queryHash!==hn(a,t.options))return!1}else if(!st(t.queryKey,a))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||s&&s!==t.state.fetchStatus||i&&!i(t))}function Yn(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Se(t.options.mutationKey)!==Se(i))return!1}else if(!st(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function hn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>zr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function st(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>st(e[n],t[n])):!1}var lc=Object.prototype.hasOwnProperty;function Yr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ii(e)&&ii(t);if(!r&&!(zr(e)&&zr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,c=r?new Array(o):{},l=0;for(let d=0;d<o;d++){let h=r?d:a[d],f=e[h],p=t[h];if(f===p){c[h]=f,(r?d<i:lc.call(e,h))&&l++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}let y=Yr(f,p,n+1);c[h]=y,y===f&&l++}return i===o&&l===i?e:c}function Et(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function ii(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function zr(e){if(!oi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!oi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function oi(e){return Object.prototype.toString.call(e)==="[object Object]"}function ci(e){return new Promise(t=>{we.setTimeout(t,e)})}function mn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Yr(e,t):t}function ui(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function li(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xt=Symbol();function Xn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Tt(e,t){return typeof e=="function"?e(...t):!!e}function di(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Re=(()=>{let e=()=>Jr;return{isServer(){return e()},setIsServer(t){e=t}}})();function gn(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var fi=si;function dc(){let e=[],t=0,n=o=>{o()},r=o=>{o()},s=fi,i=o=>{t?e.push(o):s(()=>{n(o)})},a=()=>{let o=e;e=[],o.length&&s(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{s=o}}}var M=dc();var It,je,At,pi,fc=(pi=class extends le{constructor(){super();b(this,It,!0);b(this,je);b(this,At);v(this,At,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){u(this,je)||this.setEventListener(u(this,At))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,At,t),(n=u(this,je))==null||n.call(this),v(this,je,t(this.setOnline.bind(this)))}setOnline(t){u(this,It)!==t&&(v(this,It,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,It)}},It=new WeakMap,je=new WeakMap,At=new WeakMap,pi),Ot=new fc;function pc(e){return Math.min(1e3*2**e,3e4)}function Xr(e){return(e??"online")==="online"?Ot.isOnline():!0}var Zn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function er(e){let t=!1,n=0,r,s=gn(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new Zn(m);f(g),e.onCancel?.(g)}},o=()=>{t=!0},c=()=>{t=!1},l=()=>Pt.isFocused()&&(e.networkMode==="always"||Ot.isOnline())&&e.canRun(),d=()=>Xr(e.networkMode)&&e.canRun(),h=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},p=()=>new Promise(m=>{r=g=>{(i()||l())&&m(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let m,g=n===0?e.initialPromise:void 0;try{m=g??e.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(h).catch(S=>{if(i())return;let C=e.retry??(Re.isServer()?0:3),x=e.retryDelay??pc,U=typeof x=="function"?x(n,S):x,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),ci(U).then(()=>l()?void 0:p()).then(()=>{t?f(S):y()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():p().then(y),s)}}var it,hi,tr=(hi=class{constructor(){b(this,it)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pn(this.gcTime)&&v(this,it,we.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Re.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,it)!==void 0&&(we.clearTimeout(u(this,it)),v(this,it,void 0))}},it=new WeakMap,hi);var ot,Mt,de,at,V,yn,ct,se,vi,Ie,yi,_i=(yi=class extends tr{constructor(t){super();b(this,se);b(this,ot);b(this,Mt);b(this,de);b(this,at);b(this,V);b(this,yn);b(this,ct);v(this,ct,!1),v(this,yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,at,t.client),v(this,de,u(this,at).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,ot,gi(this.options)),this.state=t.state??u(this,ot),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,V)?.promise}setOptions(t){if(this.options={...u(this,yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=gi(this.options);n.data!==void 0&&(this.setState(mi(n.data,n.dataUpdatedAt)),v(this,ot,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,de).remove(this)}setData(t,n){let r=mn(this.state.data,t,this.options);return P(this,se,Ie).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){P(this,se,Ie).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,V)?.promise;return u(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,ot)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>pe(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!zn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(this,de).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(u(this,V)&&(u(this,ct)||P(this,se,vi).call(this)?u(this,V).cancel({revert:!0}):u(this,V).cancelRetry()),this.scheduleGc()),u(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,se,Ie).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,V))return u(this,V).continueRetry(),u(this,V).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(v(this,ct,!0),r.signal)})},i=()=>{let c=Xn(this.options,n),d=(()=>{let h={client:u(this,at),queryKey:this.queryKey,meta:this.meta};return s(h),h})();return v(this,ct,!1),this.options.persister?this.options.persister(c,d,this):c(d)},o=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,at),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(o,this),v(this,Mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&P(this,se,Ie).call(this,{type:"fetch",meta:o.fetchOptions?.meta}),v(this,V,er({initialPromise:n?.initialPromise,fn:o.fetchFn,onCancel:c=>{c instanceof Zn&&c.revert&&this.setState({...u(this,Mt),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{P(this,se,Ie).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{P(this,se,Ie).call(this,{type:"pause"})},onContinue:()=>{P(this,se,Ie).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{let c=await u(this,V).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),u(this,de).config.onSuccess?.(c,this),u(this,de).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Zn){if(c.silent)return u(this,V).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw P(this,se,Ie).call(this,{type:"error",error:c}),u(this,de).config.onError?.(c,this),u(this,de).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},ot=new WeakMap,Mt=new WeakMap,de=new WeakMap,at=new WeakMap,V=new WeakMap,yn=new WeakMap,ct=new WeakMap,se=new WeakSet,vi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ie=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Zr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...mi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Mt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),M.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,de).notify({query:this,type:"updated",action:t})})},yi);function Zr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function mi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function gi(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Z,T,vn,z,ut,kt,Ae,Ve,bn,Ft,qt,lt,dt,He,Dt,O,_n,es,ts,ns,rs,ss,is,os,Ri,Si,wn=(Si=class extends le{constructor(t,n){super();b(this,O);b(this,Z);b(this,T);b(this,vn);b(this,z);b(this,ut);b(this,kt);b(this,Ae);b(this,Ve);b(this,bn);b(this,Ft);b(this,qt);b(this,lt);b(this,dt);b(this,He);b(this,Dt,new Set);this.options=n,v(this,Z,t),v(this,Ve,null),v(this,Ae,gn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,T).addObserver(this),bi(u(this,T),this.options)?P(this,O,_n).call(this):this.updateResult(),P(this,O,rs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return as(u(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return as(u(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,O,ss).call(this),P(this,O,is).call(this),u(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,T);if(this.options=u(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,u(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,O,os).call(this),u(this,T).setOptions(this.options),n._defaulted&&!Et(this.options,n)&&u(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,T),observer:this});let s=this.hasListeners();s&&wi(u(this,T),r,this.options,n)&&P(this,O,_n).call(this),this.updateResult(),s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||pe(this.options.staleTime,u(this,T))!==pe(n.staleTime,u(this,T)))&&P(this,O,es).call(this);let i=P(this,O,ts).call(this);s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||i!==u(this,He))&&P(this,O,ns).call(this,i)}getOptimisticResult(t){let n=u(this,Z).getQueryCache().build(u(this,Z),t),r=this.createResult(n,t);return mc(this,r)&&(v(this,z,r),v(this,kt,this.options),v(this,ut,u(this,T).state)),r}getCurrentResult(){return u(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&u(this,Ae).status==="pending"&&u(this,Ae).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Dt).add(t)}getCurrentQuery(){return u(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,Z).defaultQueryOptions(t),r=u(this,Z).getQueryCache().build(u(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return P(this,O,_n).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,z)))}createResult(t,n){let r=u(this,T),s=this.options,i=u(this,z),a=u(this,ut),o=u(this,kt),l=t!==r?t.state:u(this,vn),{state:d}=t,h={...d},f=!1,p;if(n._optimisticResults){let Q=this.hasListeners(),Y=!Q&&bi(t,n),ye=Q&&wi(t,r,n,s);(Y||ye)&&(h={...h,...Zr(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:g}=h;p=h.data;let S=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===o?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(u(this,qt)?.state.data,u(this,qt)):n.placeholderData,Q!==void 0&&(g="success",p=mn(i?.data,Q,n),f=!0)}if(n.select&&p!==void 0&&!S)if(i&&p===a?.data&&n.select===u(this,bn))p=u(this,Ft);else try{v(this,bn,n.select),p=n.select(p),p=mn(i?.data,p,n),v(this,Ft,p),v(this,Ve,null)}catch(Q){v(this,Ve,Q)}u(this,Ve)&&(y=u(this,Ve),p=u(this,Ft),m=Date.now(),g="error");let C=h.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&C,$=p!==void 0,ne={status:g,fetchStatus:h.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:p,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!x,isLoadingError:U&&!$,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&$,isStale:cs(t,n),refetch:this.refetch,promise:u(this,Ae),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let Q=ne.data!==void 0,Y=ne.status==="error"&&!Q,ye=I=>{Y?I.reject(ne.error):Q&&I.resolve(ne.data)},_e=()=>{let I=v(this,Ae,ne.promise=gn());ye(I)},ve=u(this,Ae);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(Y||ne.data!==ve.value)&&_e();break;case"rejected":(!Y||ne.error!==ve.reason)&&_e();break}}return ne}updateResult(){let t=u(this,z),n=this.createResult(u(this,T),this.options);if(v(this,ut,u(this,T).state),v(this,kt,this.options),u(this,ut).data!==void 0&&v(this,qt,u(this,T)),Et(n,t))return;v(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Dt).size)return!0;let a=new Set(i??u(this,Dt));return this.options.throwOnError&&a.add("error"),Object.keys(u(this,z)).some(o=>{let c=o;return u(this,z)[c]!==t[c]&&a.has(c)})};P(this,O,Ri).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,O,rs).call(this)}},Z=new WeakMap,T=new WeakMap,vn=new WeakMap,z=new WeakMap,ut=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Ve=new WeakMap,bn=new WeakMap,Ft=new WeakMap,qt=new WeakMap,lt=new WeakMap,dt=new WeakMap,He=new WeakMap,Dt=new WeakMap,O=new WeakSet,_n=function(t){P(this,O,os).call(this);let n=u(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},es=function(){P(this,O,ss).call(this);let t=pe(this.options.staleTime,u(this,T));if(Re.isServer()||u(this,z).isStale||!pn(t))return;let r=zn(u(this,z).dataUpdatedAt,t)+1;v(this,lt,we.setTimeout(()=>{u(this,z).isStale||this.updateResult()},r))},ts=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,T)):this.options.refetchInterval)??!1},ns=function(t){P(this,O,is).call(this),v(this,He,t),!(Re.isServer()||X(this.options.enabled,u(this,T))===!1||!pn(u(this,He))||u(this,He)===0)&&v(this,dt,we.setInterval(()=>{(this.options.refetchIntervalInBackground||Pt.isFocused())&&P(this,O,_n).call(this)},u(this,He)))},rs=function(){P(this,O,es).call(this),P(this,O,ns).call(this,P(this,O,ts).call(this))},ss=function(){u(this,lt)!==void 0&&(we.clearTimeout(u(this,lt)),v(this,lt,void 0))},is=function(){u(this,dt)!==void 0&&(we.clearInterval(u(this,dt)),v(this,dt,void 0))},os=function(){let t=u(this,Z).getQueryCache().build(u(this,Z),this.options);if(t===u(this,T))return;let n=u(this,T);v(this,T,t),v(this,vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Ri=function(t){M.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,z))}),u(this,Z).getQueryCache().notify({query:u(this,T),type:"observerResultsUpdated"})})},Si);function hc(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function bi(e,t){return hc(e,t)||e.state.data!==void 0&&as(e,t,t.refetchOnMount)}function as(e,t,n){if(X(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&cs(e,t)}return!1}function wi(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&cs(e,n)}function cs(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function mc(e,t){return!Et(e.getCurrentResult(),t)}function Ut(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[],o={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,h=y=>{di(y,()=>t.signal,()=>d=!0)},f=Xn(t.options,t.fetchOptions),p=async(y,m,g)=>{if(d)return Promise.reject();if(m==null&&y.pages.length)return Promise.resolve(y);let C=(()=>{let $={client:t.client,queryKey:t.queryKey,pageParam:m,direction:g?"backward":"forward",meta:t.options.meta};return h($),$})(),x=await f(C),{maxPages:U}=t.options,L=g?li:ui;return{pages:L(y.pages,x,U),pageParams:L(y.pageParams,m,U)}};if(s&&i.length){let y=s==="backward",m=y?Ci:us,g={pages:i,pageParams:a},S=m(r,g);o=await p(g,S,y)}else{let y=e??i.length;do{let m=c===0?a[0]??r.initialPageParam:us(r,o);if(c>0&&m==null)break;o=await p(o,m),c++}while(c<y)}return o};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function us(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ci(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Pi(e,t){return t?us(e,t)!=null:!1}function Ei(e,t){return!t||!e.getPreviousPageParam?!1:Ci(e,t)!=null}var ls=class extends wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Ut()})}getOptimisticResult(e){return e.behavior=Ut(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:o}=r,c=n.fetchMeta?.fetchMore?.direction,l=a&&c==="forward",d=s&&c==="forward",h=a&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Pi(t,n.data),hasPreviousPage:Ei(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:h,isFetchingPreviousPage:f,isRefetchError:o&&!l&&!h,isRefetching:i&&!d&&!f}}};var Sn,Ce,G,ft,Pe,We,xi,Ti=(xi=class extends tr{constructor(t){super();b(this,Pe);b(this,Sn);b(this,Ce);b(this,G);b(this,ft);v(this,Sn,t.client),this.mutationId=t.mutationId,v(this,G,t.mutationCache),v(this,Ce,[]),this.state=t.state||ds(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,Ce).includes(t)||(u(this,Ce).push(t),this.clearGcTimeout(),u(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Ce,u(this,Ce).filter(n=>n!==t)),this.scheduleGc(),u(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Ce).length||(this.state.status==="pending"?this.scheduleGc():u(this,G).remove(this))}continue(){return u(this,ft)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{P(this,Pe,We).call(this,{type:"continue"})},r={client:u(this,Sn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,ft,er({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{P(this,Pe,We).call(this,{type:"failed",failureCount:a,error:o})},onPause:()=>{P(this,Pe,We).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,G).canRun(this)}));let s=this.state.status==="pending",i=!u(this,ft).canStart();try{if(s)n();else{P(this,Pe,We).call(this,{type:"pending",variables:t,isPaused:i}),u(this,G).config.onMutate&&await u(this,G).config.onMutate(t,this,r);let o=await this.options.onMutate?.(t,r);o!==this.state.context&&P(this,Pe,We).call(this,{type:"pending",context:o,variables:t,isPaused:i})}let a=await u(this,ft).start();return await u(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await u(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),P(this,Pe,We).call(this,{type:"success",data:a}),a}catch(a){try{await u(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(o){Promise.reject(o)}try{await u(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(o){Promise.reject(o)}throw P(this,Pe,We).call(this,{type:"error",error:a}),a}finally{u(this,G).runNext(this)}}},Sn=new WeakMap,Ce=new WeakMap,G=new WeakMap,ft=new WeakMap,Pe=new WeakSet,We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),M.batch(()=>{u(this,Ce).forEach(r=>{r.onMutationUpdate(t)}),u(this,G).notify({mutation:this,type:"updated",action:t})})},xi);function ds(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oe,he,Rn,Ii,Ai=(Ii=class extends le{constructor(t={}){super();b(this,Oe);b(this,he);b(this,Rn);this.config=t,v(this,Oe,new Set),v(this,he,new Map),v(this,Rn,0)}build(t,n,r){let s=new Ti({client:t,mutationCache:this,mutationId:++en(this,Rn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,Oe).add(t);let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);r?r.push(t):u(this,he).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,Oe).delete(t)){let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,he).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=nr(t);if(typeof n=="string"){let s=u(this,he).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=nr(t);return typeof n=="string"?u(this,he).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{u(this,Oe).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,Oe).clear(),u(this,he).clear()})}getAll(){return Array.from(u(this,Oe))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Yn(n,r))}findAll(t={}){return this.getAll().filter(n=>Yn(t,n))}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Oe=new WeakMap,he=new WeakMap,Rn=new WeakMap,Ii);function nr(e){return e.options.scope?.id}var Me,$e,ee,ke,Fe,rr,fs,Oi,ps=(Oi=class extends le{constructor(t,n){super();b(this,Fe);b(this,Me);b(this,$e);b(this,ee);b(this,ke);v(this,Me,t),this.setOptions(n),this.bindMethods(),P(this,Fe,rr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,Me).defaultMutationOptions(t),Et(this.options,n)||u(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():u(this,ee)?.state.status==="pending"&&u(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,ee)?.removeObserver(this)}onMutationUpdate(t){P(this,Fe,rr).call(this),P(this,Fe,fs).call(this,t)}getCurrentResult(){return u(this,$e)}reset(){u(this,ee)?.removeObserver(this),v(this,ee,void 0),P(this,Fe,rr).call(this),P(this,Fe,fs).call(this)}mutate(t,n){return v(this,ke,n),u(this,ee)?.removeObserver(this),v(this,ee,u(this,Me).getMutationCache().build(u(this,Me),this.options)),u(this,ee).addObserver(this),u(this,ee).execute(t)}},Me=new WeakMap,$e=new WeakMap,ee=new WeakMap,ke=new WeakMap,Fe=new WeakSet,rr=function(){let t=u(this,ee)?.state??ds();v(this,$e,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},fs=function(t){M.batch(()=>{if(u(this,ke)&&this.hasListeners()){let n=u(this,$e).variables,r=u(this,$e).context,s={client:u(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,ke).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,ke).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,$e))})})},Oi);var Ee,Mi,ki=(Mi=class extends le{constructor(t={}){super();b(this,Ee);this.config=t,v(this,Ee,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??hn(s,n),a=this.get(i);return a||(a=new _i({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){u(this,Ee).has(t.queryHash)||(u(this,Ee).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Ee).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Ee).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Ee).get(t)}getAll(){return[...u(this,Ee).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Jn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Jn(t,r)):n}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){M.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ee=new WeakMap,Mi);var D,Be,Ge,Nt,Qt,ze,Kt,Lt,Fi,hs=(Fi=class{constructor(e={}){b(this,D);b(this,Be);b(this,Ge);b(this,Nt);b(this,Qt);b(this,ze);b(this,Kt);b(this,Lt);v(this,D,e.queryCache||new ki),v(this,Be,e.mutationCache||new Ai),v(this,Ge,e.defaultOptions||{}),v(this,Nt,new Map),v(this,Qt,new Map),v(this,ze,0)}mount(){en(this,ze)._++,u(this,ze)===1&&(v(this,Kt,Pt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onFocus())})),v(this,Lt,Ot.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onOnline())})))}unmount(){var e,t;en(this,ze)._--,u(this,ze)===0&&((e=u(this,Kt))==null||e.call(this),v(this,Kt,void 0),(t=u(this,Lt))==null||t.call(this),v(this,Lt,void 0))}isFetching(e){return u(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(pe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(this,D).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=u(this,D).get(r.queryHash)?.state.data,a=ai(t,i);if(a!==void 0)return u(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return M.batch(()=>u(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state}removeQueries(e){let t=u(this,D);M.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,D);return M.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=M.batch(()=>u(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return M.batch(()=>(u(this,D).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=M.batch(()=>u(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=u(this,D).build(this,t);return n.isStaleByTime(pe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Ut(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Ut(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ot.isOnline()?u(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,D)}getMutationCache(){return u(this,Be)}getDefaultOptions(){return u(this,Ge)}setDefaultOptions(e){v(this,Ge,e)}setQueryDefaults(e,t){u(this,Nt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Nt).values()],n={};return t.forEach(r=>{st(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Qt).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Qt).values()],n={};return t.forEach(r=>{st(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,Ge).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=hn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,Ge).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,D).clear(),u(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,Ge=new WeakMap,Nt=new WeakMap,Qt=new WeakMap,ze=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,Fi);var jt=j(ie(),1),Ui=j(sr(),1),ms=jt.createContext(void 0),N=e=>{let t=jt.useContext(ms);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Cn=({client:e,children:t})=>(jt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Ui.jsx)(ms.Provider,{value:e,children:t}));var ir=j(ie(),1),Ni=ir.createContext(!1),Qi=()=>ir.useContext(Ni),Sd=Ni.Provider;var Pn=j(ie(),1),gc=j(sr(),1);function yc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var _c=Pn.createContext(yc()),Ki=()=>Pn.useContext(_c);var Li=j(ie(),1);var ji=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Tt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Vi=e=>{Li.useEffect(()=>{e.clearReset()},[e])},Hi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Tt(n,[e.error,r]));var Wi=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},$i=(e,t)=>e.isLoading&&e.isFetching&&!t,Bi=(e,t)=>e?.suspense&&t.isPending,gs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Je=j(ie(),1);function or(e,t,n){let r=Qi(),s=Ki(),i=N(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let o=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",Wi(a),ji(a,s,o),Vi(s);let c=!i.getQueryCache().get(a.queryHash),[l]=Je.useState(()=>new t(i,a)),d=l.getOptimisticResult(a),h=!r&&e.subscribed!==!1;if(Je.useSyncExternalStore(Je.useCallback(f=>{let p=h?l.subscribe(M.batchCalls(f)):q;return l.updateResult(),p},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Je.useEffect(()=>{l.setOptions(a)},[a,l]),Bi(a,d))throw gs(a,l,s);if(Hi({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!Re.isServer()&&$i(d,r)&&(c?gs(a,l,s):o?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return or(e,wn,t)}var qe=j(ie(),1);function De(e,t){let n=N(t),[r]=qe.useState(()=>new ps(n,e));qe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=qe.useSyncExternalStore(qe.useCallback(a=>r.subscribe(M.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=qe.useCallback((a,o)=>{r.mutate(a,o).catch(q)},[r]);if(s.error&&Tt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function En(e,t){return or(e,ls,t)}var Vt=null;function Gi(e){if(Vt&&Vt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Vt=e}function E(){return Vt||(Vt=new hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Vt}var zi=new Proxy({},{get(e,t,n){let r=E(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return fe()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function Ji(){return new Date().toISOString()}function Yi(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function me(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Ji(),updated_at:e.updated_at||Ji(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function xn(e){return(e.content?.items||e.items||[]).map(me)}async function cr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=me(t);return r.path&&E().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=me(n);return r.path&&E().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function ur(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return me(t);let n=t.item;return n?me(n):null}catch{return null}}async function lr(e){try{let t=await R("list",{path:e,limit:200}),n=xn(t);for(let r of n)E().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function dr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=xn(r);for(let i of s)E().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function fr(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,o=i.type_data;!a||!o||s.set(a,{type_key:a,display_name:o.display_name||a,display_name_plural:o.display_name_plural||a+"s",icon:o.icon||"File",color:o.color||"gray",description:o.description||"",input_schema:o.input_schema||{},system_schema:o.system_schema||{},json_schema:o.input_schema||o.json_schema||{},default_data:o.default_data||{},field_defaults:o.field_defaults||{},renderer_config:o.renderer_config||{},is_system:o.is_system??!1,is_active:o.is_active??!0,is_container:o.is_container??!1,is_scope:o.is_scope??!1,render_mode:o.render_mode||"none",placement_mode:o.placement_mode,direct_parent_types:o.direct_parent_types,allowed_parent_types:o.allowed_parent_types,governed_create:o.governed_create,create_method:o.create_method,dedup:o.dedup,edges:o.edges,events:o.events})}return s}async function pr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Yi(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||Yi(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function hr(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await R("tree",s),a=xn(i);for(let o of a)E().setQueryData(w.item(o.path),o);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function mr(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function Tn(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function gr(e,t=50,n=0){return Tn(e,{limit:t,offset:n})}async function yr(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=xn(s);for(let a of i)E().setQueryData(w.item(a.path),a);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function _r(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}async function In(e){let t={item_type:e.type};e.scope&&(t.scope_path=e.scope);let n={};if(e.name&&(n.name=e.name),e.tag&&(n.tag=e.tag),e.parent_id&&(n.parent_id=e.parent_id),e.sort_by&&(n.sort_by=e.sort_by),e.sort_dir&&(n.sort_dir=e.sort_dir),e.offset!=null&&(n.offset=e.offset),e.fields)for(let[r,s]of Object.entries(e.fields))n[`field.${r}`]=String(s);Object.keys(n).length>0&&(t.filters=n),e.limit!=null&&(t.limit=e.limit);try{let r=await R("query",t),s=xn(r);for(let i of s)E().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch items of type ${e.type}:`,r),{items:[],total_hint:0}}}function vc(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function Xi(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:vc(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ys(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Zi(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ys(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function vr(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=ys(i),o=Xi(i),c=new Map,l=[];for(let d of o)if(d.parentMessagePath){let h=c.get(d.parentMessagePath)||[];h.push(d),c.set(d.parentMessagePath,h)}else l.push(d);return{messages:a,messageCards:c,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function An(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],a=Xi(i),o=new Map,c=[];for(let l of a)if(l.parentMessagePath){let d=o.get(l.parentMessagePath)||[];d.push(l),o.set(l.parentMessagePath,d)}else c.push(l);return{messages:ys(i),messageCards:o,siblingCards:c,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function ar(e){E().invalidateQueries({queryKey:w.children(e)})}function _s(e){E().invalidateQueries({queryKey:w.item(e)})}function eo(e,t){_s(e),ar(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ar(r)}function to(e){let t=e+"/";E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function no(){E().invalidateQueries({queryKey:w.all()})}function ro(e){E().invalidateQueries({queryKey:w.types(e)})}function so(e,t){e?E().invalidateQueries({queryKey:w.channelMessages(e,t)}):E().invalidateQueries({queryKey:w.allChannelMessages()})}function io(e,t){e&&t?E().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):E().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var bc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){bc&&console.log("[WS]",...e)}var A=null,Ht=null,Wt=null,On=0,wc=3e4,oo=1e4,Bt=!1,uo=3e4,Sc=uo*2+5e3,br=0,wr=null,ao=!1;function Rc(){kn(),br=Date.now(),wr=setInterval(()=>{if(A&&A.readyState===WebSocket.OPEN&&Date.now()-br>Sc){W("ping: no inbound traffic for",Date.now()-br,"ms \u2014 closing half-open socket");try{A.close(4e3,"liveness timeout")}catch{}return}Ue({type:"ping"})},uo)}function kn(){wr&&(clearInterval(wr),wr=null)}function Cc(){typeof document>"u"||(document.hidden?kn():Mn()&&(W("Tab visible, reconnecting..."),Fn()))}function Pc(){ao||typeof document>"u"||(document.addEventListener("visibilitychange",Cc),ao=!0)}var oe={};function vs(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var $t=[],Gt=new Map,pt=new Map;function Ec(){return Object.keys(oe).some(t=>oe[t]&&oe[t].length>0)||$t.length>0}function Mn(){return Gt.size>0||pt.size>0}async function Fn(){if(!Mn()){W("ensureConnection: no active subscriptions, skipping");return}if(A&&A.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Ht)return W("ensureConnection: connection already in flight, waiting..."),Ht;if(A){W("ensureConnection: killing stale WS in state",A.readyState);try{A.close()}catch{}A=null}return Bt=!1,Ht=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await xe();if(!n){W("ensureConnection: no token available, will retry"),co();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),A=new WebSocket(i),await new Promise((a,o)=>{if(!A)return o(new Error("WebSocket not created"));let c=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",oo,"ms"),A&&A.readyState!==WebSocket.OPEN){try{A.close()}catch{}A=null}o(new Error("WebSocket connection timeout"))},oo);A.onopen=()=>{clearTimeout(c),W("ensureConnection: CONNECTED"),On=0,xc(),(typeof document>"u"||!document.hidden)&&Rc(),Pc(),a()},A.onmessage=l=>{Tc(l.data)},A.onerror=()=>{W("ensureConnection: WS error event")},A.onclose=l=>{clearTimeout(c),W("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),A=null,kn(),!Bt&&Mn()&&co(),o(new Error(`WebSocket closed: ${l.code}`))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Ht=null}})(),Ht}function co(){if(Wt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,On)+Math.random()*1e3,wc);On++,W("scheduleReconnect: attempt",On,"in",Math.round(e),"ms"),Wt=setTimeout(()=>{Wt=null,Mn()&&Fn()},e)}function xc(){for(let e of Gt.values())W("resubscribeAll: scope",e.scope_id),Ue({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of pt.values())W("resubscribeAll: path",e.path),Ue({type:"subscribe_path",path:e.path,event_types:e.event_types})}function Ue(e){A&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify(e))}function Tc(e){br=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed"||t.type==="subscribed_path"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(typeof r.path=="string")for(let[s,i]of Object.entries(oe))s!=="*"&&vs(s,r.path)&&i.forEach(a=>a(r));oe["*"]&&oe["*"].forEach(s=>s(r));for(let s of $t)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function bs(){!Ec()&&Gt.size===0&&pt.size===0&&A&&(Bt=!0,kn(),A.close(),A=null,Bt=!1)}function Sr(e,t){return oe[e]||(oe[e]=[]),oe[e].push(t),pt.has(e)||(pt.set(e,{path:e,event_types:["token_stream"]}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe_path",path:e,event_types:["token_stream"]})),Fn(),()=>{let n=oe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete oe[e],pt.delete(e),Ue({type:"unsubscribe_path",path:e}))}bs()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return $t.push(...s),Mn()&&Fn(),()=>{for(let i of s){let a=$t.indexOf(i);a!==-1&&$t.splice(a,1)}bs()}}function Rr(e,t=["vfs_change","ccm_change"]){return W("subscribeToScope:",e,t),Gt.set(e,{scope_id:e,event_types:t}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe",scope_id:e,event_types:t}),Fn(),()=>{Gt.delete(e),Ue({type:"unsubscribe",scope_id:e}),bs()}}function lo(e,t,n={}){Ue({type:"emit",scope_id:e,event_type:t,payload:n})}function ws(){W("disconnectSSE: tearing down"),Bt=!0,kn(),A&&(A.close(),A=null),Wt&&(clearTimeout(Wt),Wt=null),Ht=null,Bt=!1,On=0;for(let e of Object.keys(oe))delete oe[e];$t.length=0,Gt.clear(),pt.clear()}function fo(){Ue({type:"ping"})}Te(ws);var zt=new Map,Cr=null,Pr=null,Ye=new Map,po=250;function qn(e){Er(),Dn(e),Cr=J("vfs_change",t=>Ic(t)),Pr=J("ccm_change",t=>Ac(t))}function Dn(e){if(zt.has(e))return;let t=Rr(e,["vfs_change","ccm_change"]);zt.set(e,t)}function ho(e){let t=zt.get(e);t&&(t(),zt.delete(e))}function Er(){for(let[,e]of zt)e();zt.clear(),Cr&&(Cr(),Cr=null),Pr&&(Pr(),Pr=null),Ye.forEach(e=>clearTimeout(e)),Ye.clear()}Te(Er);function Ic(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),Oc(n,t,e,s)},po);Ye.set(s,a)}function Ac(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),t&&E().invalidateQueries({queryKey:w.edges(t)}),n&&E().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&E().invalidateQueries({predicate:o=>o.queryKey[0]==="vfs"&&o.queryKey[1]==="edges"})},po);Ye.set(s,a)}function Oc(e,t,n,r){if((e||"").toUpperCase()==="DELETE")E().removeQueries({queryKey:w.item(t)}),E().removeQueries({queryKey:w.children(t)}),E().removeQueries({queryKey:w.tree(t)});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=me(i);a&&a.id&&E().setQueryData(w.item(t),a)}catch{}E().invalidateQueries({queryKey:w.children(r)}),E().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let o=a[2];return t.startsWith(o+"/")||t===o}}),n.item_id&&E().invalidateQueries({queryKey:w.itemById(n.item_id)})}var Ss=j(ie(),1),yo=j(go(),1);function _o(e){return R("read",{path:e})}function vo(e,t){return R("list",{path:e,...t})}function bo(e){return R("create",e)}function wo(e){return R("update",e)}function So(e){return R("create",e)}function Ro(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Co(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Po(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Eo={signIn:e=>e.provider?k.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>k.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),bt(),E().clear()},getSession:()=>k.auth.getSession().then(e=>e.data.session),getUser:()=>k.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=k.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>k.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>k.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function xo(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.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=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,yo.createRoot)(e).render((0,Ss.createElement)(Cn,{client:E()},(0,Ss.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function To(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var _=j(ie(),1),kc=j(Ao(),1),Fc=j(sr(),1);function Mc(e){return`${e}/settings/mounts`}var Un=null;async function Rs(e,t){Un=Mc(e);try{let s=((await R("read",{path:Un}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Qe();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Vr(s),s}catch{let n=Qe(),r=n?[n]:[];return Vr(r),r}}async function Oo(){if(!Un)return;let e=_t().map(n=>n.id),t=Ze()?.id??null;try{await R("update",{path:Un,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Un.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function Cs(e){Vs(e),await Oo()}async function Mo(e){Hs(e),await Oo()}function K(){return(0,_.useSyncExternalStore)(tt,be,be)}function qo(){return K(),Bn()}function Do(e){return K(),F({queryKey:w.item(e),queryFn:()=>ur(e),enabled:!!e})}function Uo(e){return K(),F({queryKey:w.itemById(e),queryFn:()=>cr(e),enabled:!!e})}function Es(e){return K(),F({queryKey:w.children(e),queryFn:()=>lr(e),enabled:!!e})}function No(e){let t=Es(e);return{...t,children:t.data??[]}}function Qo(e,t=1){return K(),F({queryKey:w.tree(e,t),queryFn:()=>hr(e,t),enabled:!!e})}function Ko(e,t){return K(),F({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||r.results||[]).map(me)},enabled:!!e&&e.length>0})}function Lo(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:["vfs",fe()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function jo(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>In(t),enabled:!!t?.type,select:n=>n.items})}function Vo(e){K();let t=e?.limit??20,n=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),r=En({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>In({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,o)=>{if(!(i.items.length<t))return o+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let o of r.data.pages)for(let c of o.items)c.id&&!i.has(c.id)&&(i.add(c.id),a.push(c));return a},[r.data?.pages]),fetchNextPage:r.fetchNextPage,isFetchingNextPage:r.isFetchingNextPage,isExhausted:!r.hasNextPage,isLoading:r.isLoading,isFetching:r.isFetching,error:r.error,totalHint:r.data?.pages?.[0]?.total_hint}}function Ho(e){K();let t=20,n=En({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>dr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<t))return a+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let o of a.items)o.id&&!s.has(o.id)&&(s.add(o.id),i.push(o));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 Wo(e){return K(),F({queryKey:w.edges(e),queryFn:()=>pr(e),enabled:!!e})}function xr(e){return K(),F({queryKey:w.types(e),queryFn:()=>fr(e)})}function $o(e,t){let n=xr(t);return{...n,data:n.data?.get(e)??void 0}}function Bo(e,t){K();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return F({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await _r(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let o=a.render.props.url,c=o.includes("?")?"&":"?";a.render.props.url=`${o}${c}w=${i}`}return a},enabled:!!e})}var ko={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 Go(e){let t=xr(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(ko).map(([p,y])=>({key:p,label:y})),getEdgeTypeLabel:p=>ko[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function zo(e,t,n){return K(),F({queryKey:w.memberFocus(e),queryFn:()=>yr(e,t,n),enabled:!!e})}function Jo(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return F({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Tn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Yo(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>gr(e,t,n),enabled:!!e})}function Xo(e,t=50,n=0){return K(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>mr(e,t,n),enabled:!!e})}function Zo(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let a=!1;return vt().then(o=>{if(!a){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:o.scope_path,scope_id:o.scope_id,fractal_id:o.fractal_id,instance_name:o.instance_name,display_name:o.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(o=>{a||(i(o instanceof Error?o:new Error(String(o))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var qc=[];function Nn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function ea(){let{user:e}=Tr(),t=(0,_.useRef)(!1),n=F({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??qc,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),h=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,p)=>Number(h(p))-Number(h(f)))},[s]),a=(0,_.useSyncExternalStore)(tt,be,be),o=(0,_.useMemo)(()=>{let d=Ze();return d?r.find(h=>h.accountId===d.id)??null:null},[a,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];cn(Nn(d)),qn(d.accountId),d.personalSpacePath&&Rs(d.personalSpacePath,h=>{let f=r.find(p=>p.accountId===h);return f?Nn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let h=r.find(p=>p.path===d);if(!h)return;let f=Nn(h);Qe()?Ne(f):(cn(f),h.personalSpacePath&&Rs(h.personalSpacePath,p=>{let y=r.find(m=>m.accountId===p);return y?Nn(y):null}).catch(()=>{})),qn(h.accountId)},[r]),l=(0,_.useCallback)(d=>{let h=r.find(f=>f.path===d);h&&(Cs(Nn(h)).catch(()=>{}),Dn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:o,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function ta(){let e=(0,_.useSyncExternalStore)(Wn,ln,ln);return{mounts:(0,_.useMemo)(()=>_t(),[e]),homeAnchor:Qe(),anchor:Ze(),setAnchor:Ne,mount:Cs,unmount:Mo}}function Tr(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{k.auth.getSession().then(({data:p,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=k.auth.onAuthStateChange((p,y)=>{if(p==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let o=(0,_.useCallback)(async f=>f.provider?k.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>k.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await k.auth.signOut(),bt(),E().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:p}=await k.auth.resetPasswordForEmail(f);if(p)throw p},[]),h=(0,_.useCallback)(async(f,p)=>{let{error:y}=await k.auth.signInWithOtp({email:f,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:o,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:h}}function na(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):a(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{a(c instanceof Error?c:new Error(String(c))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Qn={},Fo={};Te(()=>{for(let e of Object.keys(Qn))delete Qn[e]});var ra=null;function sa(e){ra=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Dc(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||kc;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}:Fc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||ra||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Uc(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Nc(e,t){if(!Fo[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=Uc(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),Fo[e]=s}catch{}}function Qc(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
+ `),i=new Function(r)(Dc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function xs(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let o=!1;s(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,h=e+"@v1",f=l+e+"/__bundle.js";try{let S=await fetch(l+e+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,h=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(o)return;if(Qn[h]){n(()=>Qn[h]),s(!1);return}let p=await fetch(f);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${f})`);let y=await p.text();if(o)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Nc(m).catch(()=>{});let g=Qc(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);Qn[h]=g,o||(n(()=>g),s(!1))}catch(d){o||(a(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{o=!0}},[e]),{Component:t,loading:r,error:i}}var Kc=["--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 ia(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Kc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function oa(e,t){return{data:{allowed:!0},loading:!1,error:null}}function aa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,Jt=null,Ps=new Set;function Lc(){Ps.forEach(e=>e())}Te(()=>{ae=null,Jt=null});async function ca(e){let t=e;if(!t){let{data:r}=await k.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(ae&&ae.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}}return Jt||(Jt=(async()=>{try{let{data:r,error:s}=await k.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:c}=await k.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(c??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let o={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return ae={authUserId:t,...o},o}finally{Jt=null}})(),Jt)}async function ua(e){return(await ca(e)).principalId}function la(){let e=Tr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let a=()=>{let o=ae;o&&o.authUserId===t?.id&&s({principalId:o.principalId,displayName:o.displayName,createdAt:o.createdAt,metadata:o.metadata,vfsPath:o.vfsPath})};return Ps.add(a),()=>{Ps.delete(a)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,ca(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function da(){return{data:null,loading:!1,error:null}}function fa(e){let{path:t,...n}=e,r=xs(t),s=r.Component,{loading:i,error:a}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):a?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function pa(e){return e.children}function ha(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,o=(0,_.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),c=N(),l=(0,_.useRef)(null),d=F({queryKey:o,queryFn:()=>vr(n,r),enabled:a});(0,_.useEffect)(()=>{if(!s||!a)return;let m=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:o})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),l.current&&clearTimeout(l.current)}},[s,a,n,o,c]);let h=d.data,f=h?.messages??[],p=h?.messageCards??new Map,y=h?.siblingCards??[];return{messages:f,messageCards:p,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ma(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,o=i&&!!t,c=En({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:m})=>An(t,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:o}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let m=new Set,g=[];for(let S of c.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[c.data?.pages]),{messageCards:d,siblingCards:h}=(0,_.useMemo)(()=>{let m=new Map,g=[];if(!c.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of c.data.pages){for(let[x,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let $=m.get(x)||[];$.push(L),m.set(x,$)}for(let x of C.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:m,siblingCards:g}},[c.data?.pages]),f=N(),p=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!o)return;let m=J("vfs_change",()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(async()=>{let g=f.getQueryData(y);if(!g?.pages?.length){f.invalidateQueries({queryKey:y});return}let S=0;for(let C of g.pages)for(let x of C.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:y});return}try{let C=await An(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:y});return}if(C.messages.length>0){let x=Math.min(...C.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:y});return}}f.setQueryData(y,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,$=U[L],ht=new Set($.messages.map(I=>I.id)),ne=C.messages.filter(I=>!ht.has(I.id)),Q=[...$.messages,...ne].sort((I,Xe)=>I.seq-Xe.seq),Y=new Map($.messageCards);for(let[I,Xe]of C.messageCards){let B=Y.get(I)||[],Yt=new Set(B.map(Mr=>Mr.id)),Ka=Xe.filter(Mr=>!Yt.has(Mr.id));Y.set(I,[...B,...Ka])}let ye=new Set($.siblingCards.map(I=>I.id)),_e=C.siblingCards.filter(I=>!ye.has(I.id)),ve=[...$.siblingCards,..._e];return U[L]={...$,messages:Q,messageCards:Y,siblingCards:ve},{...x,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:y})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{m(),p.current&&clearTimeout(p.current)}},[s,t,o,y,f,n,r]),{messages:l,messageCards:d,siblingCards:h,threads:l.filter(m=>m.reply_count>0),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch,hasPreviousPage:c.hasPreviousPage??!1,fetchPreviousPage:c.fetchPreviousPage,isFetchingPreviousPage:c.isFetchingPreviousPage??!1,hasNextPage:c.hasNextPage??!1,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage??!1}}function jc(e){return e==="on"||e==="auto"?"on":"off"}function Vc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:jc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function Ir(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=N(),i=(0,_.useRef)(null),a=(0,_.useMemo)(()=>w.channels("all"),[t]),o=F({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Vc),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message"),d=J("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function ga(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function ya(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ts(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=N(),o=(0,_.useRef)(null),c=(0,_.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:c,queryFn:async()=>{let h={limit:r};return n==="unread"&&(h.filter="unread"),(await R("get-notifications",h)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let h=["vfs_change","ccm_change"].map(f=>J(f,()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"||p.item_type==="message"));return()=>{h.forEach(f=>f()),o.current&&clearTimeout(o.current)}},[s,i,c,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function _a(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:o,refetch:c}=Ts({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let p=new Map;for(let y of s)y.is_unread&&y.channel_id&&p.set(y.channel_id,(p.get(y.channel_id)||0)+1);return p},[s]),d=(0,_.useMemo)(()=>{let p=0;return l.forEach(y=>{p+=y}),p},[l]),{dmUnread:h,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,m=0;return l.forEach((g,S)=>{p.has(S)?y+=g:m+=g}),{dmUnread:y,channelUnread:m}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:h,channelUnread:f,isLoading:i,isFetching:a,error:o,refetch:c}}function va(){let e=N();return De({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function ba(){let e=N();return De({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function wa(){return De({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ae)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ae.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ae={...ae,displayName:typeof t.display_name=="string"?t.display_name:ae.displayName,metadata:n},Lc()}})}function Sa(){let e=N();return De({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function Ra(){let e=N();return De({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:w.item(r)});let i=r.split("/");i.pop();let a=i.join("/");a&&e.invalidateQueries({queryKey:w.children(a)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function Ca(){let e=N();return De({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:w.edges(r)}),s&&e.invalidateQueries({queryKey:w.edges(s)})}})}function Pa(e,t){let n=N(),{optimistic:r,...s}=t??{};return De({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,o=>r.update(o,i)),{previous:a}}:void 0,onError:(i,a,o)=>{r&&o?.previous!==void 0&&n.setQueryData(r.queryKey,o.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Ea(e,t,n){let r,s,i,a=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,a=l.enabled??!0}let o=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{o.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>a?J(r,d=>o.current(d),c.current?d=>c.current(d):void 0):void 0,[r,a])}function xa(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,o=N(),c=(0,_.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=J(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:t})},a)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,a,o,JSON.stringify(t)]),l}function Ta(e){K();let t=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=F({queryKey:["vfs",fe()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let d=await R("resolve-arrangement",t);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=s.data??null,a=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),o=i?.resolution_level??null,c=(0,_.useMemo)(()=>{let h=(i?.type_data??null)?.order;return Array.isArray(h)?h:null},[i]),l=(0,_.useCallback)(d=>{if(!c||!d?.length)return d??[];let h=m=>m.id??m.name??"",f=new Map(c.map((m,g)=>[m,g])),p=[],y=[];for(let m of d)(f.has(h(m))?p:y).push(m);return p.sort((m,g)=>f.get(h(m))-f.get(h(g))),[...p,...y]},[c]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:o,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function Hc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Wc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function $c(e,t){return!(e==="object"||e==="array")}function Bc(e){return["string","number","integer","boolean"].includes(e)}function Gc(e){return e!=="object"&&e!=="array"}function Ia(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,o]of Object.entries(s)){let c=o.type||"string",l=o.enum,d=$c(c,l),h=Bc(c),f=Wc(c,l);i.push({key:a,label:o.title||Hc(a),type:c,description:o.description,enum_values:l,default_value:n[a]??r[a]??o.default,editable:t,filterable:d,sortable:h,filter_widget:f})}return i}function Is(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ia(e.input_schema,!0,t,n),s=Ia(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(l=>Gc(l.type)),o=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:o,sortable:c,form_fields:r,system_fields:s}}function Aa(e){return{field:"updated_at",direction:"desc"}}function Oa(e){let t=Is(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var te=j(ie(),1);var zc=0;function Jc(){return`upload_${Date.now()}_${++zc}`}async function Ma(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",a=t.itemType||"file",o={parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(o.card_parent_path=t.cardParentPath);let l=await R("create",o);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,h=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:h,fileRef:l.file_ref};let f=l.storage_key,p=l.upload_token,y=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Yc(y,f,p,e,i,n,r);let m=await ka(d,f,i);return{itemId:d,itemPath:h,fileRef:m}}function Yc(e,t,n,r,s,i,a){return new Promise((o,c)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?o():c(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>c(new Error("Storage upload network error")),l.ontimeout=()=>c(new Error("Storage upload timed out")),a){if(a.aborted){c(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),c(new Error("Upload cancelled"))})}l.send(r)})}async function ka(e,t,n){let r=await xe(),s=await fetch(`${ce}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${a.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Fa(){let[e,t]=(0,te.useState)([]),n=N(),r=(0,te.useRef)(e);r.current=e;let s=(0,te.useCallback)((m,g)=>{t(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,te.useCallback)(m=>{t(g=>[...g,m])},[]),a=(0,te.useCallback)(async(m,g,S,C,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",$=S.itemType||"file",ht=x?.itemId||null,ne=x?.itemPath||null,Q=x?.storageKey||null,Y=x?.uploadToken||null,ye=x?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let I=await R("create",{parent_path:S.parentPath,item_type:$,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!I.id)throw Object.assign(new Error(I.error||I.message||"Failed to create file item"),{_step:"create"});if(ht=I.id,ne=I.path,s(m,{itemId:ht,itemPath:ne}),I.storage_completed&&I.file_ref){s(m,{status:"complete",progress:100,fileRef:I.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=I.storage_key,Y=I.upload_token||"",ye=I.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:Q,_uploadToken:Y,_storageWorkerUrl:ye}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((I,Xe)=>{let B=new XMLHttpRequest;s(m,{_xhr:B}),B.open("PUT",`${ye}/upload`),B.setRequestHeader("X-Storage-Key",Q),B.setRequestHeader("Content-Type",L),Y&&B.setRequestHeader("X-Upload-Token",Y),B.upload.onprogress=Yt=>{Yt.lengthComputable&&s(m,{progress:Math.round(Yt.loaded/Yt.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?I():Xe(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>Xe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>Xe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let _e=await ka(ht,Q,L);s(m,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),I=_e?._step||"create";s(m,{status:"error",error:ve,_failedAt:I,_xhr:null})}},[s,n]),o=(0,te.useCallback)((m,g)=>{let S=Jc();i({id:S,file:m,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,m,g)},[i,a]),c=(0,te.useCallback)((m,g)=>{for(let S of m)o(S,g)},[o]),l=(0,te.useCallback)(m=>{let g=r.current.find(x=>x.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(m,g.file,g.options,S,C)},[a]),d=(0,te.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),h=(0,te.useCallback)(m=>{t(g=>g.filter(S=>S.id!==m))},[]),f=(0,te.useCallback)(()=>{t(m=>m.filter(g=>g.status!=="complete"))},[]),p=e.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),y=e.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:x,...U})=>U);return{upload:o,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:h,clearCompleted:f,isUploading:p}}var qa=j(ie(),1);async function As(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Da(e,t){return(0,qa.useSyncExternalStore)(tt,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>As(e,t),enabled:!!(e&&t)})}var ge=j(ie(),1);function Ar(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let c,l=a.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(a.artifact_id)c=a;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let h=r.get(c.tool_id);n.timeline[h].artifact_ids.push(c.artifact_id)}else{let h=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,h)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let h=r.get(c.tool_id);if(h!==void 0){let f=n.timeline[h];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return Sr(e,s)}function Ua(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),a=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,h=>{a.current=h,r(new Map(h.artifacts)),i([...h.timeline])}),[e,t]);let o=(0,ge.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:l,reset:o}}function Na(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Or=j(ie(),1);function Xc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Os(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let o=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return o?(o.rows??o.items??o.data??[]).map(Zc).sort((l,d)=>l.seq-d.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function Qa(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},o=e?`${e}/datasets/agent-events`:null,c=N(),l=(0,Or.useRef)(null),d=o?Xc(o,n,r,s):["vfs","timeline-history","__disabled__"],h=F({queryKey:d,queryFn:()=>Os(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Or.useEffect)(()=>{if(!o||!i)return;let f=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},a)},p=>{let y=p?.path;return y?y===o||y.startsWith(o+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[o,i,a,c,JSON.stringify(d)]),{events:h.data??[],isLoading:h.isLoading,error:h.error,isFetching:h.isFetching,refetch:()=>{h.refetch()}}}function Zc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}sa(Ms);return Ga(Ms);})();
4
4
 
5
5
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
6
6
  (function() {