@ai4b-team/fsaos-gateway-sdk 3.26.1 → 3.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-09-04T03:02:59.902Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var sc=Object.create;var rn=Object.defineProperty;var ic=Object.getOwnPropertyDescriptor;var oc=Object.getOwnPropertyNames;var ac=Object.getPrototypeOf,cc=Object.prototype.hasOwnProperty;var js=e=>{throw TypeError(e)};var uc=(e,t,n)=>t in e?rn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var sn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),lc=(e,t)=>{for(var n in t)rn(e,n,{get:t[n],enumerable:!0})},Vs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oc(t))!cc.call(e,s)&&s!==n&&rn(e,s,{get:()=>t[s],enumerable:!(r=ic(t,s))||r.enumerable});return e};var H=(e,t,n)=>(n=e!=null?sc(ac(e)):{},Vs(t||!e||!e.__esModule?rn(n,"default",{value:e,enumerable:!0}):n,e)),dc=e=>Vs(rn({},"__esModule",{value:!0}),e);var K=(e,t,n)=>uc(e,typeof t!="symbol"?t+"":t,n),Qr=(e,t,n)=>t.has(e)||js("Cannot "+n);var u=(e,t,n)=>(Qr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(Qr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),C=(e,t,n)=>(Qr(e,t,"access private method"),n);var on=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return u(e,t,r)}});var $s=sn((Su,Hs)=>{Hs.exports={createClient:window.supabase.createClient}});var ie=sn((Ld,Bi)=>{Bi.exports=React});var ar=sn((jd,Gi)=>{Gi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Mo=sn((Uf,ko)=>{ko.exports=ReactDOM});var Bo=sn((Hf,Wo)=>{Wo.exports=ReactDOM});var Ls={};lc(Ls,{ComponentRenderer:()=>Ia,EnforcementDeniedError:()=>vt,FormSubmissionError:()=>Pt,GatewayRequestError:()=>Le,InteractionTrackingError:()=>Ct,KernelProvider:()=>Aa,QueryClientProvider:()=>In,auth:()=>Vo,awaitAnchorReady:()=>fn,awaitScopeReady:()=>ni,callTool:()=>Ko,cancelQueuedTurn:()=>fi,cancelTurn:()=>li,clearCachedToken:()=>jr,clearSession:()=>zr,createItem:()=>Uo,disconnectSSE:()=>As,disposeVfsRealtimeWs:()=>Or,electHomeAnchor:()=>pn,emitEvent:()=>To,fetchChannelMessages:()=>po,fetchChannelMessagesPage:()=>Fn,fetchChannelMessagesWithCards:()=>Sr,fetchEdgesForItem:()=>gr,fetchItemHistory:()=>vr,fetchItemVersions:()=>Mn,fetchItems:()=>Gt,fetchMemberFocus:()=>br,fetchOpenEnvelope:()=>wr,fetchRecentActivity:()=>_r,fetchResolvedItems:()=>Ns,fetchTimelineHistory:()=>Ks,fetchTurnQueueEntries:()=>lo,fetchTypeDefinitions:()=>hr,fetchVfsChildren:()=>pr,fetchVfsChildrenPage:()=>mr,fetchVfsItem:()=>fr,fetchVfsItemById:()=>dr,fetchVfsTree:()=>yr,gatewayCall:()=>R,getAccessToken:()=>Ie,getAnchor:()=>dn,getAnchorRef:()=>rt,getAnchorVersion:()=>$r,getAssetUrl:()=>jo,getDefaultSort:()=>Ba,getHomeAnchor:()=>Ke,getMountVersion:()=>hn,getMounts:()=>St,getPathSubscriptionState:()=>xo,getQueryClient:()=>P,getRequiredFormFields:()=>Ga,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>zn,initSession:()=>Rt,initVfsRealtimeWs:()=>Qn,initializeFsaos:()=>ui,interpretSchema:()=>Qs,invalidateAllVfs:()=>go,invalidateChannelMessages:()=>_o,invalidateChildren:()=>lr,invalidateItem:()=>Cs,invalidateOpenEnvelope:()=>vo,invalidatePathAndParent:()=>mo,invalidateSubtree:()=>ho,invalidateTypes:()=>yo,isAnchorReady:()=>Br,isScopeReady:()=>Jn,listChildren:()=>Do,mount:()=>Ho,mountRealtimeScope:()=>Nn,normalizeItem:()=>he,onConnectionStateChange:()=>Io,pathSubscriptionMatches:()=>Ps,ping:()=>Co,pushChanges:()=>No,queryClient:()=>ao,readItem:()=>qo,registerCleanup:()=>Ae,resetAllSdkState:()=>Tt,resolvePrincipalId:()=>xa,resubscribePath:()=>Eo,setAnchor:()=>Ne,setCachedToken:()=>Gs,setQueryClient:()=>oo,setScope:()=>ti,setupRequireShim:()=>$o,signal:()=>Lo,startTracking:()=>Yn,steerTurn:()=>di,submitForm:()=>pi,subscribeAnchor:()=>Wr,subscribeArtifactStream:()=>qr,subscribeMounts:()=>Gn,subscribeScope:()=>it,subscribeToEvents:()=>Y,subscribeToPath:()=>Pr,subscribeToScope:()=>Er,trackAction:()=>ai,trackEvent:()=>ot,trackPageView:()=>oi,unmountRealtimeScope:()=>Oo,updateItem:()=>Qo,uploadFile:()=>za,useAccounts:()=>ya,useAgentTimeline:()=>tc,useAllChannels:()=>Fr,useArrangement:()=>$a,useArtifactStream:()=>ec,useAsset:()=>va,useAuth:()=>Mr,useChannelMessages:()=>Oa,useChannels:()=>Ma,useChildren:()=>ta,useComponent:()=>Ds,useCreate:()=>Da,useDelete:()=>Na,useDmChannels:()=>Fa,useEdges:()=>ca,useEventStream:()=>Va,useFileUpload:()=>Ya,useInfiniteChannelMessages:()=>ka,useInfiniteChildren:()=>aa,useInfiniteItems:()=>oa,useItem:()=>Zo,useItemById:()=>ea,useItemHistory:()=>ma,useItemVersions:()=>pa,useItems:()=>ia,useLink:()=>La,useList:()=>qs,useMemberFocus:()=>fa,useMounts:()=>_a,useMove:()=>Ka,useMutation:()=>ja,useNotifications:()=>Us,useOpen:()=>la,usePermission:()=>Ra,usePermissions:()=>Ta,usePrincipal:()=>Pa,useRealtimeQuery:()=>Ha,useRecentActivity:()=>ha,useResolve:()=>sa,useResolvedItems:()=>Za,useScope:()=>ga,useScopeReady:()=>Xo,useSearch:()=>ra,useTheme:()=>Sa,useTimelineHistory:()=>nc,useTool:()=>Ea,useTree:()=>na,useType:()=>ua,useTypeHelpers:()=>da,useTypes:()=>kr,useUnreadCounts:()=>qa,useUpdate:()=>Ua,useUpdatePrincipal:()=>Qa,vfsKeys:()=>w,waitForPathReady:()=>Po});var vt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);K(this,"name","EnforcementDeniedError");K(this,"deniedBy");K(this,"ruleKey");K(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 Ws=H($s(),1),an=typeof window<"u"&&window.__FSAOS_CONFIG__||{},cn=Array.isArray(an.sources)?an.sources:[],fc=an.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",pc=an.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=an.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",M=(0,Ws.createClient)(fc,pc,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var ln=null,Vn=0,Bs,Lr,Hn=!1;Bs=new Promise(e=>{Lr=e});M.auth.onAuthStateChange((e,t)=>{t?.access_token?(ln=t.access_token,Vn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(ln=null,Vn=0),Hn||(Hn=!0,Lr())});setTimeout(()=>{Hn||(Hn=!0,Lr())},5e3);function Gs(e,t){ln=e,Vn=t??Math.floor(Date.now()/1e3)+3600}function jr(){ln=null,Vn=0}async function Ie(){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 Bs,ln}var $n=null,Bn=null,zs=0,Nr=new Set,Vr,Hr,Wn=!1;Vr=new Promise(e=>{Hr=e});function Js(){zs++,Nr.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=$n!==t;$n=t,Bn=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],mn()),Wn||(Wn=!0,Hr()),n&&Js()}function dn(){return $n}function rt(){return Bn}function $r(){return zs}function Wr(e){return Nr.add(e),()=>{Nr.delete(e)}}function fn(){return Vr}function Br(){return Wn}var wt=null;function pn(e){if(wt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}wt=e,Ne(e)}function Ke(){return wt}var ue=[],Kr=new Set,Ys=0;function mn(){Ys++,Kr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function St(){return ue}function hn(){return Ys}function Gn(e){return Kr.add(e),()=>{Kr.delete(e)}}function Gr(e){ue=e,mn()}function Xs(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],mn())}function Zs(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),mn(),Bn?.id===e&&wt&&Ne(wt))}var bt=null,un=null;async function Rt(){return bt||un||(un=(async()=>{let e=st(),t=await Ie(),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 bt={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},bt})(),un)}function zn(){return bt}function zr(){bt=null,un=null,$n=null,Bn=null,wt=null,ue=[]}var ei=[];function Ae(e){ei.push(e)}function Tt(){zr(),jr(),Wn=!1,Vr=new Promise(e=>{Hr=e}),Js(),mn();for(let e of ei)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function st(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ti=Ne,fe=dn,be=$r,it=Wr,ni=fn,Jn=Br;var Jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,mc=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,ri=new Map,si=new Map,Ct=class extends Error{constructor(n,r,s,i){super(n);K(this,"code");K(this,"status");K(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function yn(e){let t=e?cn.find(n=>n.id===e):cn.find(n=>n.default===!0)??(cn.length===1?cn[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 Yr(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 hc(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function gc(e,t){if(!hc(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Xr(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function yc(e){try{let t=Xr(e)?.getItem(e.key)??void 0;return t&&Jr.test(t)?t:void 0}catch{return}}function ii(e,t){try{Xr(e)?.setItem(e.key,t)}catch{}}function _c(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=yc(t)??ri.get(e.id);if(n)return n;let r=crypto.randomUUID();return ri.set(e.id,r),ii(t,r),r}function vc(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=Xr(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=si.get(e.id),i=r&&typeof r.id=="string"&&Jr.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return si.set(e.id,c),ii(n,JSON.stringify(c)),c.id}function bc(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,o=Object.fromEntries(n.flatMap(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function ot(e,t={},n={}){let r=yn(n.source);if(gc(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??_c(r),o=n.sessionId??vc(r);if(![s,i,o].every(g=>Jr.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)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=bc(r,a),p=d?{...t,source_keys:d}:t,f=st(),m=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Ct(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let h=null;try{h=await y.json()}catch{}if(!y.ok||h?.success!==!0){let g=h;throw new Ct(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return h}function oi(e={},t={}){let n=yn(t.source),r=Yr("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return ot(r.observation,{...s,...e},{...t,source:n.id})}function ai(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=yn(n.source),s=Yr("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return ot(s.observation,{...t,...i},{...n,source:r.id})}function ci(e,t={}){let n=yn(t.source),r=Yr("form_receipt",n);return ot(r.observation,e,{...t,source:n.id})}var gn;function Yn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gn)return gn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=yn(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 m=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};ot(f.observation,m,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=f=>{if(f.target instanceof Element)for(let m of r){let y=m.attribute;if(!y||!mc.test(y))continue;let h=f.target.closest(`[${y}]`);if(!h)continue;let g=h.getAttribute(y)?.trim();if(!g||g.length>128)continue;let S={};m.id_property&&(S[m.id_property]=g),m.element_property&&(S[m.element_property]=h.tagName.toLowerCase()),ot(m.observation,S,{source:t.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),p=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...m){a.apply(this,m),l()},window.history.replaceState=function(...m){c.apply(this,m),l()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),gn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),gn=void 0},gn}var xt;function ui(e={}){return xt||(xt=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Yn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await Rt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),xt=void 0)}}}catch(r){throw n(),xt=void 0,r}})(),xt)}var wc=new Set(["list-memberships","init"]),Le=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);K(this,"name","GatewayRequestError");K(this,"method");K(this,"status");K(this,"statusText");K(this,"payload");K(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function R(e,t={}){let n=st(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await Ie();i&&(s.Authorization=`Bearer ${i}`),!wc.has(e)&&!t._scope_path&&await fn();let o={...t},a=zn();!o.domain_scope_id&&a?.scope_id&&(o.domain_scope_id=a.scope_id);let c=dn();!o._scope_path&&c&&(o._scope_path=c);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:o})}),d=await l.text(),p=null;if(d)try{p=JSON.parse(d)}catch{}if(!l.ok||!p)throw new Le({method:e,status:l.status,statusText:l.statusText,payload:p,responseBody:d});if(p.success===!1){let f=p.error||"",m=p.denied_by||p.error_type||"";throw m==="rule"||m==="access"||m==="entitlement"||f==="RULE_DENIED"||f==="ACCESS_DENIED"||f==="PERMISSION_DENIED"||f==="ENTITLEMENT_REQUIRED"?new vt(p):new Le({method:e,status:l.status,statusText:l.statusText,payload:p,responseBody:d})}return p}async function Zr(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Le)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function es(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function li(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await Zr({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return es(i?{...s,state:i}:s)}async function di(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await Zr({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return es(a?{...o,state:a}:o)}async function fi(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await Zr({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return es(i?{...s,outcome:i}:s)}var Sc=/^[a-z][a-z0-9_-]{0,63}$/,Rc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pt=class extends Error{constructor(n,r,s,i){super(n);K(this,"code");K(this,"status");K(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function pi(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(!Rc.test(r))throw new TypeError("fillId must be a UUID");let s=st(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a;try{a=await fetch(o,{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 Pt(l instanceof Error?l.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let c=null;try{c=await a.json()}catch{}if(!a.ok||c?.success!==!0){let l=c;throw new Pt(l?.message||l?.error||`Form submission failed (${a.status})`,l?.error||"FORM_SUBMISSION_FAILED",a.status,r)}try{await ci({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 at,je,Et,mi,Tc=(mi=class extends le{constructor(){super();b(this,at);b(this,je);b(this,Et);v(this,Et,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,je)||this.setEventListener(u(this,Et))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,Et,t),(n=u(this,je))==null||n.call(this),v(this,je,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,at)!==t&&(v(this,at,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,at)=="boolean"?u(this,at):globalThis.document?.visibilityState!=="hidden"}},at=new WeakMap,je=new WeakMap,Et=new WeakMap,mi),It=new Tc;var Cc={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ve,ts,hi,xc=(hi=class{constructor(){b(this,Ve,Cc);b(this,ts,!1)}setTimeoutProvider(e){v(this,Ve,e)}setTimeout(e,t){return u(this,Ve).setTimeout(e,t)}clearTimeout(e){u(this,Ve).clearTimeout(e)}setInterval(e,t){return u(this,Ve).setInterval(e,t)}clearInterval(e){u(this,Ve).clearInterval(e)}},Ve=new WeakMap,ts=new WeakMap,hi),we=new xc;function gi(e){setTimeout(e,0)}var rs=typeof window>"u"||"Deno"in globalThis;function q(){}function vi(e,t){return typeof e=="function"?e(t):e}function _n(e){return typeof e=="number"&&e>=0&&e!==1/0}function Xn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function pe(e,t){return typeof e=="function"?e(t):e}function Z(e,t){return typeof e=="function"?e(t):e}function Zn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==vn(o,t.options))return!1}else if(!ct(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function er(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(!ct(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function vn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>ns(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function ct(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ct(e[n],t[n])):!1}var Pc=Object.prototype.hasOwnProperty;function ss(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=yi(e)&&yi(t);if(!r&&!(ns(e)&&ns(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},l=0;for(let d=0;d<a;d++){let p=r?d:o[d],f=e[p],m=t[p];if(f===m){c[p]=f,(r?d<i:Pc.call(e,p))&&l++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){c[p]=m;continue}let y=ss(f,m,n+1);c[p]=y,y===f&&l++}return i===a&&l===i?e:c}function At(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 yi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ns(e){if(!_i(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!_i(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function _i(e){return Object.prototype.toString.call(e)==="[object Object]"}function bi(e){return new Promise(t=>{we.setTimeout(t,e)})}function bn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ss(e,t):t}function wi(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Si(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ot=Symbol();function tr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ot?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function kt(e,t){return typeof e=="function"?e(...t):!!e}function Ri(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=()=>rs;return{isServer(){return e()},setIsServer(t){e=t}}})();function wn(){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 Ti=gi;function Ec(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=Ti,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var k=Ec();var Mt,He,Ft,Ci,Ic=(Ci=class extends le{constructor(){super();b(this,Mt,!0);b(this,He);b(this,Ft);v(this,Ft,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,He)||this.setEventListener(u(this,Ft))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,He))==null||t.call(this),v(this,He,void 0))}setEventListener(t){var n;v(this,Ft,t),(n=u(this,He))==null||n.call(this),v(this,He,t(this.setOnline.bind(this)))}setOnline(t){u(this,Mt)!==t&&(v(this,Mt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,Mt)}},Mt=new WeakMap,He=new WeakMap,Ft=new WeakMap,Ci),qt=new Ic;function Ac(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??"online")==="online"?qt.isOnline():!0}var nr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function rr(e){let t=!1,n=0,r,s=wn(),i=()=>s.status!=="pending",o=h=>{if(!i()){let g=new nr(h);f(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},l=()=>It.isFocused()&&(e.networkMode==="always"||qt.isOnline())&&e.canRun(),d=()=>is(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},f=h=>{i()||(r?.(),s.reject(h))},m=()=>new Promise(h=>{r=g=>{(i()||l())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(S){h=Promise.reject(S)}Promise.resolve(h).then(p).catch(S=>{if(i())return;let T=e.retry??(Re.isServer()?0:3),E=e.retryDelay??Ac,U=typeof E=="function"?E(n,S):E,V=T===!0||typeof T=="number"&&n<T||typeof T=="function"&&T(n,S);if(t||!V){f(S);return}n++,e.onFail?.(n,S),bi(U).then(()=>l()?void 0:m()).then(()=>{t?f(S):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?y():m().then(y),s)}}var ut,xi,sr=(xi=class{constructor(){b(this,ut)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_n(this.gcTime)&&v(this,ut,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,ut)!==void 0&&(we.clearTimeout(u(this,ut)),v(this,ut,void 0))}},ut=new WeakMap,xi);var lt,Dt,de,dt,$,Sn,ft,se,Oi,Oe,Ii,Ai=(Ii=class extends sr{constructor(t){super();b(this,se);b(this,lt);b(this,Dt);b(this,de);b(this,dt);b(this,$);b(this,Sn);b(this,ft);v(this,ft,!1),v(this,Sn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,dt,t.client),v(this,de,u(this,dt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,lt,Ei(this.options)),this.state=t.state??u(this,lt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,$)?.promise}setOptions(t){if(this.options={...u(this,Sn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Ei(this.options);n.data!==void 0&&(this.setState(Pi(n.data,n.dataUpdatedAt)),v(this,lt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,de).remove(this)}setData(t,n){let r=bn(this.state.data,t,this.options);return C(this,se,Oe).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){C(this,se,Oe).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,$)?.promise;return u(this,$)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,lt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Z(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ot||!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:!Xn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,$)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,$)?.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,$)&&(u(this,ft)||C(this,se,Oi).call(this)?u(this,$).cancel({revert:!0}):u(this,$).cancelRetry()),this.scheduleGc()),u(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||C(this,se,Oe).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,$)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,$))return u(this,$).continueRetry(),u(this,$).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,ft,!0),r.signal)})},i=()=>{let c=tr(this.options,n),d=(()=>{let p={client:u(this,dt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return v(this,ft,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,dt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),v(this,Dt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&C(this,se,Oe).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),v(this,$,rr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof nr&&c.revert&&this.setState({...u(this,Dt),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{C(this,se,Oe).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{C(this,se,Oe).call(this,{type:"pause"})},onContinue:()=>{C(this,se,Oe).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await u(this,$).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 nr){if(c.silent)return u(this,$).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw C(this,se,Oe).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()}}},lt=new WeakMap,Dt=new WeakMap,de=new WeakMap,dt=new WeakMap,$=new WeakMap,Sn=new WeakMap,ft=new WeakMap,se=new WeakSet,Oi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Oe=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,...os(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Pi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Dt,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),k.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,de).notify({query:this,type:"updated",action:t})})},Ii);function os(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Pi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ei(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 ee,I,Tn,J,pt,Ut,ke,$e,Cn,Qt,Nt,mt,ht,We,Kt,O,Rn,as,cs,us,ls,ds,fs,ps,qi,Fi,xn=(Fi=class extends le{constructor(t,n){super();b(this,O);b(this,ee);b(this,I);b(this,Tn);b(this,J);b(this,pt);b(this,Ut);b(this,ke);b(this,$e);b(this,Cn);b(this,Qt);b(this,Nt);b(this,mt);b(this,ht);b(this,We);b(this,Kt,new Set);this.options=n,v(this,ee,t),v(this,$e,null),v(this,ke,wn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,I).addObserver(this),ki(u(this,I),this.options)?C(this,O,Rn).call(this):this.updateResult(),C(this,O,ls).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ms(u(this,I),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ms(u(this,I),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,C(this,O,ds).call(this),C(this,O,fs).call(this),u(this,I).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,I);if(this.options=u(this,ee).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Z(this.options.enabled,u(this,I))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");C(this,O,ps).call(this),u(this,I).setOptions(this.options),n._defaulted&&!At(this.options,n)&&u(this,ee).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,I),observer:this});let s=this.hasListeners();s&&Mi(u(this,I),r,this.options,n)&&C(this,O,Rn).call(this),this.updateResult(),s&&(u(this,I)!==r||Z(this.options.enabled,u(this,I))!==Z(n.enabled,u(this,I))||pe(this.options.staleTime,u(this,I))!==pe(n.staleTime,u(this,I)))&&C(this,O,as).call(this);let i=C(this,O,cs).call(this);s&&(u(this,I)!==r||Z(this.options.enabled,u(this,I))!==Z(n.enabled,u(this,I))||i!==u(this,We))&&C(this,O,us).call(this,i)}getOptimisticResult(t){let n=u(this,ee).getQueryCache().build(u(this,ee),t),r=this.createResult(n,t);return kc(this,r)&&(v(this,J,r),v(this,Ut,this.options),v(this,pt,u(this,I).state)),r}getCurrentResult(){return u(this,J)}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,ke).status==="pending"&&u(this,ke).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Kt).add(t)}getCurrentQuery(){return u(this,I)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,ee).defaultQueryOptions(t),r=u(this,ee).getQueryCache().build(u(this,ee),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return C(this,O,Rn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,J)))}createResult(t,n){let r=u(this,I),s=this.options,i=u(this,J),o=u(this,pt),a=u(this,Ut),l=t!==r?t.state:u(this,Tn),{state:d}=t,p={...d},f=!1,m;if(n._optimisticResults){let N=this.hasListeners(),X=!N&&ki(t,n),ye=N&&Mi(t,r,n,s);(X||ye)&&(p={...p,...os(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:h,status:g}=p;m=p.data;let S=!1;if(n.placeholderData!==void 0&&m===void 0&&g==="pending"){let N;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(N=i.data,S=!0):N=typeof n.placeholderData=="function"?n.placeholderData(u(this,Nt)?.state.data,u(this,Nt)):n.placeholderData,N!==void 0&&(g="success",m=bn(i?.data,N,n),f=!0)}if(n.select&&m!==void 0&&!S)if(i&&m===o?.data&&n.select===u(this,Cn))m=u(this,Qt);else try{v(this,Cn,n.select),m=n.select(m),m=bn(i?.data,m,n),v(this,Qt,m),v(this,$e,null)}catch(N){v(this,$e,N)}u(this,$e)&&(y=u(this,$e),m=u(this,Qt),h=Date.now(),g="error");let T=p.fetchStatus==="fetching",E=g==="pending",U=g==="error",V=E&&T,B=m!==void 0,re={status:g,fetchStatus:p.fetchStatus,isPending:E,isSuccess:g==="success",isError:U,isInitialLoading:V,isLoading:V,data:m,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:T,isRefetching:T&&!E,isLoadingError:U&&!B,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&B,isStale:hs(t,n),refetch:this.refetch,promise:u(this,ke),isEnabled:Z(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let N=re.data!==void 0,X=re.status==="error"&&!N,ye=A=>{X?A.reject(re.error):N&&A.resolve(re.data)},_e=()=>{let A=v(this,ke,re.promise=wn());ye(A)},ve=u(this,ke);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(X||re.data!==ve.value)&&_e();break;case"rejected":(!X||re.error!==ve.reason)&&_e();break}}return re}updateResult(){let t=u(this,J),n=this.createResult(u(this,I),this.options);if(v(this,pt,u(this,I).state),v(this,Ut,this.options),u(this,pt).data!==void 0&&v(this,Nt,u(this,I)),At(n,t))return;v(this,J,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Kt).size)return!0;let o=new Set(i??u(this,Kt));return this.options.throwOnError&&o.add("error"),Object.keys(u(this,J)).some(a=>{let c=a;return u(this,J)[c]!==t[c]&&o.has(c)})};C(this,O,qi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&C(this,O,ls).call(this)}},ee=new WeakMap,I=new WeakMap,Tn=new WeakMap,J=new WeakMap,pt=new WeakMap,Ut=new WeakMap,ke=new WeakMap,$e=new WeakMap,Cn=new WeakMap,Qt=new WeakMap,Nt=new WeakMap,mt=new WeakMap,ht=new WeakMap,We=new WeakMap,Kt=new WeakMap,O=new WeakSet,Rn=function(t){C(this,O,ps).call(this);let n=u(this,I).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},as=function(){C(this,O,ds).call(this);let t=pe(this.options.staleTime,u(this,I));if(Re.isServer()||u(this,J).isStale||!_n(t))return;let r=Xn(u(this,J).dataUpdatedAt,t)+1;v(this,mt,we.setTimeout(()=>{u(this,J).isStale||this.updateResult()},r))},cs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,I)):this.options.refetchInterval)??!1},us=function(t){C(this,O,fs).call(this),v(this,We,t),!(Re.isServer()||Z(this.options.enabled,u(this,I))===!1||!_n(u(this,We))||u(this,We)===0)&&v(this,ht,we.setInterval(()=>{(this.options.refetchIntervalInBackground||It.isFocused())&&C(this,O,Rn).call(this)},u(this,We)))},ls=function(){C(this,O,as).call(this),C(this,O,us).call(this,C(this,O,cs).call(this))},ds=function(){u(this,mt)!==void 0&&(we.clearTimeout(u(this,mt)),v(this,mt,void 0))},fs=function(){u(this,ht)!==void 0&&(we.clearInterval(u(this,ht)),v(this,ht,void 0))},ps=function(){let t=u(this,ee).getQueryCache().build(u(this,ee),this.options);if(t===u(this,I))return;let n=u(this,I);v(this,I,t),v(this,Tn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},qi=function(t){k.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,J))}),u(this,ee).getQueryCache().notify({query:u(this,I),type:"observerResultsUpdated"})})},Fi);function Oc(e,t){return Z(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ki(e,t){return Oc(e,t)||e.state.data!==void 0&&ms(e,t,t.refetchOnMount)}function ms(e,t,n){if(Z(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&hs(e,t)}return!1}function Mi(e,t,n,r){return(e!==t||Z(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&hs(e,n)}function hs(e,t){return Z(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function kc(e,t){return!At(e.getCurrentResult(),t)}function Lt(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,p=y=>{Ri(y,()=>t.signal,()=>d=!0)},f=tr(t.options,t.fetchOptions),m=async(y,h,g)=>{if(d)return Promise.reject();if(h==null&&y.pages.length)return Promise.resolve(y);let T=(()=>{let B={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p(B),B})(),E=await f(T),{maxPages:U}=t.options,V=g?Si:wi;return{pages:V(y.pages,E,U),pageParams:V(y.pageParams,h,U)}};if(s&&i.length){let y=s==="backward",h=y?Di:gs,g={pages:i,pageParams:o},S=h(r,g);a=await m(g,S,y)}else{let y=e??i.length;do{let h=c===0?o[0]??r.initialPageParam:gs(r,a);if(c>0&&h==null)break;a=await m(a,h),c++}while(c<y)}return a};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 gs(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 Di(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ui(e,t){return t?gs(e,t)!=null:!1}function Qi(e,t){return!t||!e.getPreviousPageParam?!1:Di(e,t)!=null}var ys=class extends xn{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:Lt()})}getOptimisticResult(e){return e.behavior=Lt(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c==="forward",d=s&&c==="forward",p=o&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ui(t,n.data),hasPreviousPage:Qi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:a&&!l&&!p,isRefetching:i&&!d&&!f}}};var Pn,Te,z,gt,Ce,Be,Ni,Ki=(Ni=class extends sr{constructor(t){super();b(this,Ce);b(this,Pn);b(this,Te);b(this,z);b(this,gt);v(this,Pn,t.client),this.mutationId=t.mutationId,v(this,z,t.mutationCache),v(this,Te,[]),this.state=t.state||_s(),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,Te).includes(t)||(u(this,Te).push(t),this.clearGcTimeout(),u(this,z).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Te,u(this,Te).filter(n=>n!==t)),this.scheduleGc(),u(this,z).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Te).length||(this.state.status==="pending"?this.scheduleGc():u(this,z).remove(this))}continue(){return u(this,gt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{C(this,Ce,Be).call(this,{type:"continue"})},r={client:u(this,Pn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,gt,rr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{C(this,Ce,Be).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{C(this,Ce,Be).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,z).canRun(this)}));let s=this.state.status==="pending",i=!u(this,gt).canStart();try{if(s)n();else{C(this,Ce,Be).call(this,{type:"pending",variables:t,isPaused:i}),u(this,z).config.onMutate&&await u(this,z).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&C(this,Ce,Be).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await u(this,gt).start();return await u(this,z).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await u(this,z).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),C(this,Ce,Be).call(this,{type:"success",data:o}),o}catch(o){try{await u(this,z).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await u(this,z).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw C(this,Ce,Be).call(this,{type:"error",error:o}),o}finally{u(this,z).runNext(this)}}},Pn=new WeakMap,Te=new WeakMap,z=new WeakMap,gt=new WeakMap,Ce=new WeakSet,Be=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),k.batch(()=>{u(this,Te).forEach(r=>{r.onMutationUpdate(t)}),u(this,z).notify({mutation:this,type:"updated",action:t})})},Ni);function _s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Me,me,En,Li,ji=(Li=class extends le{constructor(t={}){super();b(this,Me);b(this,me);b(this,En);this.config=t,v(this,Me,new Set),v(this,me,new Map),v(this,En,0)}build(t,n,r){let s=new Ki({client:t,mutationCache:this,mutationId:++on(this,En)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,Me).add(t);let n=ir(t);if(typeof n=="string"){let r=u(this,me).get(n);r?r.push(t):u(this,me).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,Me).delete(t)){let n=ir(t);if(typeof n=="string"){let r=u(this,me).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,me).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=ir(t);if(typeof n=="string"){let s=u(this,me).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=ir(t);return typeof n=="string"?u(this,me).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){k.batch(()=>{u(this,Me).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,Me).clear(),u(this,me).clear()})}getAll(){return Array.from(u(this,Me))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>er(n,r))}findAll(t={}){return this.getAll().filter(n=>er(t,n))}notify(t){k.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return k.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Me=new WeakMap,me=new WeakMap,En=new WeakMap,Li);function ir(e){return e.options.scope?.id}var Fe,Ge,te,qe,De,or,vs,Vi,bs=(Vi=class extends le{constructor(t,n){super();b(this,De);b(this,Fe);b(this,Ge);b(this,te);b(this,qe);v(this,Fe,t),this.setOptions(n),this.bindMethods(),C(this,De,or).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,Fe).defaultMutationOptions(t),At(this.options,n)||u(this,Fe).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,te),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():u(this,te)?.state.status==="pending"&&u(this,te).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,te)?.removeObserver(this)}onMutationUpdate(t){C(this,De,or).call(this),C(this,De,vs).call(this,t)}getCurrentResult(){return u(this,Ge)}reset(){u(this,te)?.removeObserver(this),v(this,te,void 0),C(this,De,or).call(this),C(this,De,vs).call(this)}mutate(t,n){return v(this,qe,n),u(this,te)?.removeObserver(this),v(this,te,u(this,Fe).getMutationCache().build(u(this,Fe),this.options)),u(this,te).addObserver(this),u(this,te).execute(t)}},Fe=new WeakMap,Ge=new WeakMap,te=new WeakMap,qe=new WeakMap,De=new WeakSet,or=function(){let t=u(this,te)?.state??_s();v(this,Ge,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},vs=function(t){k.batch(()=>{if(u(this,qe)&&this.hasListeners()){let n=u(this,Ge).variables,r=u(this,Ge).context,s={client:u(this,Fe),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,qe).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,qe).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,qe).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,qe).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,Ge))})})},Vi);var xe,Hi,$i=(Hi=class extends le{constructor(t={}){super();b(this,xe);this.config=t,v(this,xe,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??vn(s,n),o=this.get(i);return o||(o=new Ai({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){u(this,xe).has(t.queryHash)||(u(this,xe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,xe).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,xe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){k.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,xe).get(t)}getAll(){return[...u(this,xe).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Zn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Zn(t,r)):n}notify(t){k.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){k.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){k.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},xe=new WeakMap,Hi);var D,ze,Je,jt,Vt,Ye,Ht,$t,Wi,ws=(Wi=class{constructor(e={}){b(this,D);b(this,ze);b(this,Je);b(this,jt);b(this,Vt);b(this,Ye);b(this,Ht);b(this,$t);v(this,D,e.queryCache||new $i),v(this,ze,e.mutationCache||new ji),v(this,Je,e.defaultOptions||{}),v(this,jt,new Map),v(this,Vt,new Map),v(this,Ye,0)}mount(){on(this,Ye)._++,u(this,Ye)===1&&(v(this,Ht,It.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onFocus())})),v(this,$t,qt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onOnline())})))}unmount(){var e,t;on(this,Ye)._--,u(this,Ye)===0&&((e=u(this,Ht))==null||e.call(this),v(this,Ht,void 0),(t=u(this,$t))==null||t.call(this),v(this,$t,void 0))}isFetching(e){return u(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,ze).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,o=vi(t,i);if(o!==void 0)return u(this,D).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return k.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);k.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,D);return k.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=k.batch(()=>u(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return k.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=k.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=Lt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Lt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return qt.isOnline()?u(this,ze).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,D)}getMutationCache(){return u(this,ze)}getDefaultOptions(){return u(this,Je)}setDefaultOptions(e){v(this,Je,e)}setQueryDefaults(e,t){u(this,jt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,jt).values()],n={};return t.forEach(r=>{ct(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Vt).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Vt).values()],n={};return t.forEach(r=>{ct(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,Je).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=vn(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===Ot&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,Je).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,D).clear(),u(this,ze).clear()}},D=new WeakMap,ze=new WeakMap,Je=new WeakMap,jt=new WeakMap,Vt=new WeakMap,Ye=new WeakMap,Ht=new WeakMap,$t=new WeakMap,Wi);var Wt=H(ie(),1),zi=H(ar(),1),Ss=Wt.createContext(void 0),Q=e=>{let t=Wt.useContext(Ss);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},In=({client:e,children:t})=>(Wt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,zi.jsx)(Ss.Provider,{value:e,children:t}));var cr=H(ie(),1),Ji=cr.createContext(!1),Yi=()=>cr.useContext(Ji),Hd=Ji.Provider;var An=H(ie(),1),Mc=H(ar(),1);function Fc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var qc=An.createContext(Fc()),Xi=()=>An.useContext(qc);var Zi=H(ie(),1);var eo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?kt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},to=e=>{Zi.useEffect(()=>{e.clearReset()},[e])},no=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||kt(n,[e.error,r]));var ro=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))}},so=(e,t)=>e.isLoading&&e.isFetching&&!t,io=(e,t)=>e?.suspense&&t.isPending,Rs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Xe=H(ie(),1);function ur(e,t,n){let r=Yi(),s=Xi(),i=Q(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ro(o),eo(o,s,a),to(s);let c=!i.getQueryCache().get(o.queryHash),[l]=Xe.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(Xe.useSyncExternalStore(Xe.useCallback(f=>{let m=p?l.subscribe(k.batchCalls(f)):q;return l.updateResult(),m},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Xe.useEffect(()=>{l.setOptions(o)},[o,l]),io(o,d))throw Rs(o,l,s);if(no({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Re.isServer()&&so(d,r)&&(c?Rs(o,l,s):a?.promise)?.catch(q).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return ur(e,xn,t)}var Ue=H(ie(),1);function Qe(e,t){let n=Q(t),[r]=Ue.useState(()=>new bs(n,e));Ue.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Ue.useSyncExternalStore(Ue.useCallback(o=>r.subscribe(k.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Ue.useCallback((o,a)=>{r.mutate(o,a).catch(q)},[r]);if(s.error&&kt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function On(e,t){return ur(e,ys,t)}var Bt=null;function oo(e){if(Bt&&Bt!==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.");Bt=e}function P(){return Bt||(Bt=new ws({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Bt}var ao=new Proxy({},{get(e,t,n){let r=P(),s=r[t];return typeof s=="function"?s.bind(r):s}});function W(){return fe()??"__unscoped__"}var w={all:()=>["vfs",W()],item:e=>["vfs",W(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",W(),"children",e],allChildren:()=>["vfs",W(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",W(),"search",e,...t??[]],items:(e,t)=>["vfs",W(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",W(),"items"],tree:(e,t)=>["vfs",W(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",W(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",W(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",W(),"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",W(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",W(),"channel-messages"],channels:e=>["vfs",W(),"channels",e??"all"],allChannels:()=>["vfs",W(),"channels"],notifications:(e,t)=>["vfs",W(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",W(),"notifications"],unreadCounts:()=>["vfs",W(),"unread-counts"],memberships:e=>["memberships",e]};function co(){return new Date().toISOString()}function uo(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function he(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||co(),updated_at:e.updated_at||co(),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 kn(e){return(e.content?.items||e.items||[]).map(he)}async function dr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=he(t);return r.path&&P().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=he(n);return r.path&&P().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function fr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return he(t);let n=t.item;return n?he(n):null}catch{return null}}async function pr(e){try{let t=await R("list",{path:e,limit:200}),n=kn(t);for(let r of n)P().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function lo(e,t){let{items:n}=await Gt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function mr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=kn(r);for(let i of s)P().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 hr(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 o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function gr(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||uo(),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||uo(),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 yr(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),o=kn(i);for(let a of o)P().setQueryData(w.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function _r(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 Mn(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 vr(e,t=50,n=0){return Mn(e,{limit:t,offset:n})}async function br(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=kn(s);for(let o of i)P().setQueryData(w.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function wr(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 Gt(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=kn(r);for(let i of s)P().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 Dc(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 fo(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:Dc(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 Ts(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,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 po(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 Ts(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function Sr(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||[],o=Ts(i),a=fo(i),c=new Map,l=[];for(let d of a)if(d.parentMessagePath){let p=c.get(d.parentMessagePath)||[];p.push(d),c.set(d.parentMessagePath,p)}else l.push(d);return{messages:o,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 Fn(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||[],o=fo(i),a=new Map,c=[];for(let l of o)if(l.parentMessagePath){let d=a.get(l.parentMessagePath)||[];d.push(l),a.set(l.parentMessagePath,d)}else c.push(l);return{messages:Ts(i),messageCards:a,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 lr(e){P().invalidateQueries({queryKey:w.children(e)})}function Cs(e){P().invalidateQueries({queryKey:w.item(e)})}function mo(e,t){Cs(e),lr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&lr(r)}function ho(e){let t=e+"/";P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function go(){P().invalidateQueries({queryKey:w.all()})}function yo(e){P().invalidateQueries({queryKey:w.types(e)})}function _o(e,t){e?P().invalidateQueries({queryKey:w.channelMessages(e,t)}):P().invalidateQueries({queryKey:w.allChannelMessages()})}function vo(e,t){e&&t?P().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):P().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var Uc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function L(...e){Uc&&console.log("[WS]",...e)}var x=null,zt=null,Jt=null,qn=0,Qc=3e4,bo=1e4,Xt=!1,Ro=3e4,Nc=Ro*2+5e3,Rr=0,Tr=null,wo=!1;function Kc(){Un(),Rr=Date.now(),Tr=setInterval(()=>{if(x&&x.readyState===WebSocket.OPEN&&Date.now()-Rr>Nc){L("ping: no inbound traffic for",Date.now()-Rr,"ms \u2014 closing half-open socket");try{x.close(4e3,"liveness timeout")}catch{}return}et({type:"ping"})},Ro)}function Un(){Tr&&(clearInterval(Tr),Tr=null)}function Lc(){typeof document>"u"||(document.hidden?Un():Dn()&&(L("Tab visible, reconnecting..."),yt()))}function jc(){wo||typeof document>"u"||(document.addEventListener("visibilitychange",Lc),wo=!0)}var oe={};function Ps(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Yt=[],Zt=new Map,Pe=new Map,Ee=new Map,Ze=new Map,xs="disconnected",Cr=[];function xr(e){if(xs!==e){xs=e;for(let t of[...Cr])try{t(e)}catch{}}}function Vc(e){Ee.set(e,"ready");let t=Ze.get(e);if(t){Ze.delete(e);for(let n of t)n()}}function Hc(){for(let e of Ee.keys())Ee.set(e,"disconnected")}function Es(e,t){Ee.set(e,"pending"),et({type:"subscribe_path",path:e,event_types:t})}function $c(){return Object.keys(oe).some(t=>oe[t]&&oe[t].length>0)||Yt.length>0}function Dn(){return Zt.size>0||Pe.size>0}async function yt(){if(!Dn()){L("ensureConnection: no active subscriptions, skipping");return}if(x&&x.readyState===WebSocket.OPEN){L("ensureConnection: already open");return}if(zt)return L("ensureConnection: connection already in flight, waiting..."),zt;if(x){L("ensureConnection: killing stale WS in state",x.readyState);try{x.close()}catch{}x=null}return Xt=!1,zt=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await Ie();if(!n){L("ensureConnection: no token available, will retry"),So();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,L("ensureConnection: opening WS to",i.substring(0,50)+"..."),xr("connecting"),x=new WebSocket(i);let o=x;await new Promise((a,c)=>{if(!x)return c(new Error("WebSocket not created"));let l=setTimeout(()=>{if(x===o){if(L("ensureConnection: TIMEOUT after",bo,"ms"),x&&x.readyState!==WebSocket.OPEN){try{x.close()}catch{}x=null}c(new Error("WebSocket connection timeout"))}},bo);o.onopen=()=>{x===o&&(clearTimeout(l),L("ensureConnection: CONNECTED"),qn=0,xr("connected"),Wc(),(typeof document>"u"||!document.hidden)&&Kc(),jc(),a())},o.onmessage=d=>{x===o&&Bc(d.data)},o.onerror=()=>{L("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),x===o&&(L("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),x=null,Un(),Hc(),xr("disconnected"),!Xt&&Dn()&&So(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){L("ensureConnection: failed -",e?.message||e)}finally{zt=null}})(),zt}function So(){if(Jt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,qn)+Math.random()*1e3,Qc);qn++,L("scheduleReconnect: attempt",qn,"in",Math.round(e),"ms"),Jt=setTimeout(()=>{Jt=null,Dn()&&yt()},e)}function Wc(){for(let e of Zt.values())L("resubscribeAll: scope",e.scope_id),et({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of Pe.values())L("resubscribeAll: path",e.path),Es(e.path,e.event_types)}function et(e){x&&x.readyState===WebSocket.OPEN&&x.send(JSON.stringify(e))}function Bc(e){Rr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Vc(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="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!=="*"&&Ps(s,r.path)&&i.forEach(o=>o(r));oe["*"]&&oe["*"].forEach(s=>s(r));for(let s of Yt)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Is(){!$c()&&Zt.size===0&&Pe.size===0&&x&&(Xt=!0,Un(),x.close(),x=null,Xt=!1)}function Pr(e,t){return oe[e]||(oe[e]=[]),oe[e].push(t),Pe.has(e)||(Pe.set(e,{path:e,event_types:["token_stream"]}),x&&x.readyState===WebSocket.OPEN?Es(e,["token_stream"]):Ee.set(e,"pending")),yt(),()=>{let n=oe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete oe[e],Pe.delete(e),Ee.delete(e),Ze.delete(e),et({type:"unsubscribe_path",path:e}))}Is()}}function Y(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Yt.push(...s),Dn()&&yt(),()=>{for(let i of s){let o=Yt.indexOf(i);o!==-1&&Yt.splice(o,1)}Is()}}function Er(e,t=["vfs_change","ccm_change"]){return L("subscribeToScope:",e,t),Zt.set(e,{scope_id:e,event_types:t}),x&&x.readyState===WebSocket.OPEN&&et({type:"subscribe",scope_id:e,event_types:t}),yt(),()=>{Zt.delete(e),et({type:"unsubscribe",scope_id:e}),Is()}}function To(e,t,n={}){et({type:"emit",scope_id:e,event_type:t,payload:n})}function As(){L("disconnectSSE: tearing down"),Xt=!0,Un(),x&&(x.close(),x=null),Jt&&(clearTimeout(Jt),Jt=null),zt=null,Xt=!1,qn=0;for(let e of Object.keys(oe))delete oe[e];Yt.length=0,Zt.clear(),Pe.clear(),Ee.clear(),Ze.clear(),xr("disconnected")}function Co(){et({type:"ping"})}function xo(e){return Pe.has(e)?Ee.get(e)??"pending":"unsubscribed"}function Po(e,t=5e3){return Pe.has(e)?Ee.get(e)==="ready"&&x&&x.readyState===WebSocket.OPEN?Promise.resolve(!0):(yt(),new Promise(n=>{let r=!1,s=Ze.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Ze.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Ze.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Ze.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Eo(e){let t=Pe.get(e);if(!t){L("resubscribePath: no active subscription for",e);return}x&&x.readyState===WebSocket.OPEN?(L("resubscribePath: re-sending frame for",e),Es(t.path,t.event_types)):(Ee.set(e,"pending"),yt())}function Io(e){Cr.push(e);try{e(xs)}catch{}return()=>{let t=Cr.indexOf(e);t!==-1&&Cr.splice(t,1)}}Ae(As);var en=new Map,Ir=null,Ar=null,tt=new Map,Ao=250;function Qn(e){Or(),Nn(e),Ir=Y("vfs_change",t=>Gc(t)),Ar=Y("ccm_change",t=>zc(t))}function Nn(e){if(en.has(e))return;let t=Er(e,["vfs_change","ccm_change"]);en.set(e,t)}function Oo(e){let t=en.get(e);t&&(t(),en.delete(e))}function Or(){for(let[,e]of en)e();en.clear(),Ir&&(Ir(),Ir=null),Ar&&(Ar(),Ar=null),tt.forEach(e=>clearTimeout(e)),tt.clear()}Ae(Or);function Gc(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=tt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{tt.delete(s),Jc(n,t,e,s)},Ao);tt.set(s,o)}function zc(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=tt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{tt.delete(s),t&&P().invalidateQueries({queryKey:w.edges(t)}),n&&P().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&P().invalidateQueries({predicate:a=>a.queryKey[0]==="vfs"&&a.queryKey[1]==="edges"})},Ao);tt.set(s,o)}function Jc(e,t,n,r){if((e||"").toUpperCase()==="DELETE")P().removeQueries({queryKey:w.item(t)}),P().removeQueries({queryKey:w.children(t)}),P().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},o=he(i);o&&o.id&&P().setQueryData(w.item(t),o)}catch{}P().invalidateQueries({queryKey:w.children(r)}),P().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let a=o[2];return t.startsWith(a+"/")||t===a}}),n.item_id&&P().invalidateQueries({queryKey:w.itemById(n.item_id)})}var Os=H(ie(),1),Fo=H(Mo(),1);function qo(e){return R("read",{path:e})}function Do(e,t){return R("list",{path:e,...t})}function Uo(e){return R("create",e)}function Qo(e){return R("update",e)}function No(e){return R("create",e)}function Ko(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Lo(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function jo(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Vo={signIn:e=>e.provider?M.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):M.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>M.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await M.auth.signOut(),Tt(),P().clear()},getSession:()=>M.auth.getSession().then(e=>e.data.session),getUser:()=>M.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=M.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>M.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>M.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Ho(){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,Fo.createRoot)(e).render((0,Os.createElement)(In,{client:P()},(0,Os.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 $o(){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(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}var _=H(ie(),1),Xc=H(Bo(),1),Zc=H(ar(),1);function Yc(e){return`${e}/settings/mounts`}var Kn=null;async function ks(e,t){Kn=Yc(e);try{let s=((await R("read",{path:Kn}))?.item?.type_data?.mounts??[]).map(t).filter(o=>o!==null),i=Ke();return i&&!s.some(o=>o.id===i.id)&&s.unshift(i),Gr(s),s}catch{let n=Ke(),r=n?[n]:[];return Gr(r),r}}async function Go(){if(!Kn)return;let e=St().map(n=>n.id),t=rt()?.id??null;try{await R("update",{path:Kn,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Kn.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 Ms(e){Xs(e),await Go()}async function zo(e){Zs(e),await Go()}function j(){return(0,_.useSyncExternalStore)(it,be,be)}function Xo(){return j(),Jn()}function Zo(e){return j(),F({queryKey:w.item(e),queryFn:()=>fr(e),enabled:!!e})}function ea(e){return j(),F({queryKey:w.itemById(e),queryFn:()=>dr(e),enabled:!!e})}function qs(e){return j(),F({queryKey:w.children(e),queryFn:()=>pr(e),enabled:!!e})}function ta(e){let t=qs(e);return{...t,children:t.data??[]}}function na(e,t=1){return j(),F({queryKey:w.tree(e,t),queryFn:()=>yr(e,t),enabled:!!e})}function ra(e,t){return j(),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(he)},enabled:!!e&&e.length>0})}function sa(e){j();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 ia(e){j();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>Gt(t),enabled:!!t?.type,select:n=>n.items})}function oa(e){j();let t=e?.limit??20,n=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),r=On({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>Gt({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,o,a)=>{if(!(i.items.length<t))return a+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,o=[];for(let a of r.data.pages)for(let c of a.items)c.id&&!i.has(c.id)&&(i.add(c.id),o.push(c));return o},[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 aa(e){j();let t=20,n=On({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>mr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function ca(e){return j(),F({queryKey:w.edges(e),queryFn:()=>gr(e),enabled:!!e})}function kr(e){return j(),F({queryKey:w.types(e),queryFn:()=>hr(e)})}function ua(e,t){let n=kr(t);return{...n,data:n.data?.get(e)??void 0}}function la(e,t){j();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 o=await wr(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Jo={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 da(e){let t=kr(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:m=>n.get(m.item_type)?.is_container??!1,isScope:m=>n.get(m.item_type)?.is_scope??!1,isScopeType:m=>n.get(m)?.is_scope??!1,isContainerType:m=>n.get(m)?.is_container??!1,getTypeDefinition:m=>n.get(m),getTypeColor:m=>n.get(m)?.color??"gray",getTypeIcon:m=>n.get(m)?.icon??"File",getTypeDisplayName:m=>n.get(m)?.display_name??m,getKnownEdgeTypes:()=>Object.entries(Jo).map(([m,y])=>({key:m,label:y})),getEdgeTypeLabel:m=>Jo[m]??m.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function fa(e,t,n){return j(),F({queryKey:w.memberFocus(e),queryFn:()=>br(e,t,n),enabled:!!e})}function pa(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:()=>Mn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function ma(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>vr(e,t,n),enabled:!!e})}function ha(e,t=50,n=0){return j(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>_r(e,t,n),enabled:!!e})}function ga(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Rt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var eu=[];function Ln(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function ya(){let{user:e}=Mr(),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??eu,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,m)=>Number(p(m))-Number(p(f)))},[s]),o=(0,_.useSyncExternalStore)(it,be,be),a=(0,_.useMemo)(()=>{let d=rt();return d?r.find(p=>p.accountId===d.id)??null:null},[o,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];pn(Ln(d)),Qn(d.accountId),d.personalSpacePath&&ks(d.personalSpacePath,p=>{let f=r.find(m=>m.accountId===p);return f?Ln(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let p=r.find(m=>m.path===d);if(!p)return;let f=Ln(p);Ke()?Ne(f):(pn(f),p.personalSpacePath&&ks(p.personalSpacePath,m=>{let y=r.find(h=>h.accountId===m);return y?Ln(y):null}).catch(()=>{})),Qn(p.accountId)},[r]),l=(0,_.useCallback)(d=>{let p=r.find(f=>f.path===d);p&&(Ms(Ln(p)).catch(()=>{}),Nn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:a,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function _a(){let e=(0,_.useSyncExternalStore)(Gn,hn,hn);return{mounts:(0,_.useMemo)(()=>St(),[e]),homeAnchor:Ke(),anchor:rt(),setAnchor:Ne,mount:Ms,unmount:zo}}function Mr(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{M.auth.getSession().then(({data:m,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m?.session??null),t(m?.session?.user??null),i(!1)}).catch(m=>{console.warn("[useAuth] getSession threw, clearing stale session:",m?.message),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=M.auth.onAuthStateChange((m,y)=>{if(m==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=f,()=>{f?.unsubscribe()}},[]);let a=(0,_.useCallback)(async f=>f.provider?M.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):M.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>M.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await M.auth.signOut(),Tt(),P().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:m}=await M.auth.resetPasswordForEmail(f);if(m)throw m},[]),p=(0,_.useCallback)(async(f,m)=>{let{error:y}=await M.auth.signInWithOtp({email:f,options:m?{emailRedirectTo:m}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:p}}function va(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(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}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var jn={},Yo={};Ae(()=>{for(let e of Object.keys(jn))delete jn[e]});var ba=null;function wa(e){ba=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function tu(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||Xc;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}:Zc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||ba||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function nu(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function ru(e,t){if(!Yo[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=nu(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),Yo[e]=s}catch{}}function su(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)(tu),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ds(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=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,p=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(a)return;if(jn[p]){n(()=>jn[p]),s(!1);return}let m=await fetch(f);if(!m.ok)throw new Error(`Failed to fetch bundle: ${m.status} ${m.statusText} (${f})`);let y=await m.text();if(a)return;let h=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");ru(h).catch(()=>{});let g=su(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})`);jn[p]=g,a||(n(()=>g),s(!1))}catch(d){a||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{a=!0}},[e]),{Component:t,loading:r,error:i}}var iu=["--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 iu.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Ra(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Ta(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,tn=null,Fs=new Set;function ou(){Fs.forEach(e=>e())}Ae(()=>{ae=null,tn=null});async function Ca(e){let t=e;if(!t){let{data:r}=await M.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:o,vfsPath:a}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:o,vfsPath:a}}return tn||(tn=(async()=>{try{let{data:r,error:s}=await M.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,o=null;if(i){let{data:c}=await M.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);o=l.find(d=>d.split("/").length===4)??l[0]??null}let a={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:o};return ae={authUserId:t,...a},a}finally{tn=null}})(),tn)}async function xa(e){return(await Ca(e)).principalId}function Pa(){let e=Mr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let a=ae;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Fs.add(o),()=>{Fs.delete(o)}},[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(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Ea(){return{data:null,loading:!1,error:null}}function Ia(e){let{path:t,...n}=e,r=Ds(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function Aa(e){return e.children}function Oa(e){let t=j(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,_.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),c=Q(),l=(0,_.useRef)(null),d=F({queryKey:a,queryFn:()=>Sr(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let h=Y("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:a})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{h(),l.current&&clearTimeout(l.current)}},[s,o,n,a,c]);let p=d.data,f=p?.messages??[],m=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:f,messageCards:m,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(h=>h.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ka(e){j();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,a=i&&!!t,c=On({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>Fn(t,{parentMessageId:n,limit:r,before_seq:o?void 0:h,after_seq:o?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!o||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>o||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:a}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let h=new Set,g=[];for(let S of c.data.pages)for(let T of S.messages)h.has(T.id)||(h.add(T.id),g.push(T));return g.sort((S,T)=>S.seq-T.seq)},[c.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let h=new Map,g=[];if(!c.data?.pages)return{messageCards:h,siblingCards:g};let S=new Set;for(let T of c.data.pages){for(let[E,U]of T.messageCards)for(let V of U){if(S.has(V.id))continue;S.add(V.id);let B=h.get(E)||[];B.push(V),h.set(E,B)}for(let E of T.siblingCards)S.has(E.id)||(S.add(E.id),g.push(E))}return{messageCards:h,siblingCards:g}},[c.data?.pages]),f=Q(),m=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!a)return;let h=Y("vfs_change",()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(async()=>{let g=f.getQueryData(y);if(!g?.pages?.length){f.invalidateQueries({queryKey:y});return}let S=0;for(let T of g.pages)for(let E of T.messages)E.seq>S&&(S=E.seq);if(S===0){f.invalidateQueries({queryKey:y});return}try{let T=await Fn(t,{parentMessageId:n,limit:r,after_seq:S});if(T.messages.length===0&&T.siblingCards.length===0){f.invalidateQueries({queryKey:y});return}if(T.messages.length>0){let E=Math.min(...T.messages.map(U=>U.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),f.invalidateQueries({queryKey:y});return}}f.setQueryData(y,E=>{if(!E)return E;let U=[...E.pages],V=U.length-1,B=U[V],_t=new Set(B.messages.map(A=>A.id)),re=T.messages.filter(A=>!_t.has(A.id)),N=[...B.messages,...re].sort((A,nt)=>A.seq-nt.seq),X=new Map(B.messageCards);for(let[A,nt]of T.messageCards){let G=X.get(A)||[],nn=new Set(G.map(Ur=>Ur.id)),rc=nt.filter(Ur=>!nn.has(Ur.id));X.set(A,[...G,...rc])}let ye=new Set(B.siblingCards.map(A=>A.id)),_e=T.siblingCards.filter(A=>!ye.has(A.id)),ve=[...B.siblingCards,..._e];return U[V]={...B,messages:N,messageCards:X,siblingCards:ve},{...E,pages:U}})}catch(T){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",T),f.invalidateQueries({queryKey:y})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{h(),m.current&&clearTimeout(m.current)}},[s,t,a,y,f,n,r]),{messages:l,messageCards:d,siblingCards:p,threads:l.filter(h=>h.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 au(e){return e==="on"||e==="auto"?"on":"off"}function cu(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:au(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 Fr(e={}){let t=j(),{realtime:n=!0,enabled:r=!0}=e,s=Q(),i=(0,_.useRef)(null),o=(0,_.useMemo)(()=>w.channels("all"),[t]),a=F({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(cu),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=Y("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),d=Y("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,o,s]),{channels:a.data??[],isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Ma(e={}){let t=Fr(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Fa(e={}){let t=Fr(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Us(e={}){let t=j(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=Q(),a=(0,_.useRef)(null),c=(0,_.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:c,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>Y(f,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},m=>m.item_type==="notification"||m.item_type==="message"));return()=>{p.forEach(f=>f()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function qa(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Us({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let m=new Map;for(let y of s)y.is_unread&&y.channel_id&&m.set(y.channel_id,(m.get(y.channel_id)||0)+1);return m},[s]),d=(0,_.useMemo)(()=>{let m=0;return l.forEach(y=>{m+=y}),m},[l]),{dmUnread:p,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let m=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,h=0;return l.forEach((g,S)=>{m.has(S)?y+=g:h+=g}),{dmUnread:y,channelUnread:h}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:f,isLoading:i,isFetching:o,error:a,refetch:c}}function Da(){let e=Q();return Qe({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function Ua(){let e=Q();return Qe({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 Qa(){return Qe({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},ou()}})}function Na(){let e=Q();return Qe({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 Ka(){let e=Q();return Qe({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 o=i.join("/");o&&e.invalidateQueries({queryKey:w.children(o)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function La(){let e=Q();return Qe({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 ja(e,t){let n=Q(),{optimistic:r,...s}=t??{};return Qe({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Va(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,o=l.enabled??!0}let a=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>o?Y(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function Ha(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=Q(),c=(0,_.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=Y(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:t})},o)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,o,a,JSON.stringify(t)]),l}function $a(e){j();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,o=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),a=i?.resolution_level??null,c=(0,_.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),l=(0,_.useCallback)(d=>{if(!c||!d?.length)return d??[];let p=h=>h.id??h.name??"",f=new Map(c.map((h,g)=>[h,g])),m=[],y=[];for(let h of d)(f.has(p(h))?m:y).push(h);return m.sort((h,g)=>f.get(p(h))-f.get(p(g))),[...m,...y]},[c]);return{...s,arrangement:i,resolvedChildren:o,resolutionLevel:a,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function uu(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function lu(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function du(e,t){return!(e==="object"||e==="array")}function fu(e){return["string","number","integer","boolean"].includes(e)}function pu(e){return e!=="object"&&e!=="array"}function Wa(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",l=a.enum,d=du(c,l),p=fu(c),f=lu(c,l);i.push({key:o,label:a.title||uu(o),type:c,description:a.description,enum_values:l,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:p,filter_widget:f})}return i}function Qs(e){let t=e.default_data||{},n=e.field_defaults||{},r=Wa(e.input_schema,!0,t,n),s=Wa(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>pu(l.type)),a=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Ba(e){return{field:"updated_at",direction:"desc"}}function Ga(e){let t=Qs(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=H(ie(),1);var mu=0;function hu(){return`upload_${Date.now()}_${++mu}`}async function za(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(a.card_parent_path=t.cardParentPath);let l=await R("create",a);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let f=l.storage_key,m=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 gu(y,f,m,e,i,n,r);let h=await Ja(d,f,i);return{itemId:d,itemPath:p,fileRef:h}}function gu(e,t,n,r,s,i,o){return new Promise((a,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?a():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")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{l.abort(),c(new Error("Upload cancelled"))})}l.send(r)})}async function Ja(e,t,n){let r=await Ie(),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 o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.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 Ya(){let[e,t]=(0,ne.useState)([]),n=Q(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((h,g)=>{t(S=>S.map(T=>T.id===h?{...T,...g}:T))},[]),i=(0,ne.useCallback)(h=>{t(g=>[...g,h])},[]),o=(0,ne.useCallback)(async(h,g,S,T,E)=>{let U=S.name||g.name,V=g.type||"application/octet-stream",B=S.itemType||"file",_t=E?.itemId||null,re=E?.itemPath||null,N=E?.storageKey||null,X=E?.uploadToken||null,ye=E?.storageWorkerUrl||null;try{if(!T||T==="create"){s(h,{status:"creating",error:null,_failedAt:null});let A=await R("create",{parent_path:S.parentPath,item_type:B,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:V}}});if(!A.id)throw Object.assign(new Error(A.error||A.message||"Failed to create file item"),{_step:"create"});if(_t=A.id,re=A.path,s(h,{itemId:_t,itemPath:re}),A.storage_completed&&A.file_ref){s(h,{status:"complete",progress:100,fileRef:A.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(N=A.storage_key,X=A.upload_token||"",ye=A.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:N,_uploadToken:X,_storageWorkerUrl:ye}),!N)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!T||T==="create"||T==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((A,nt)=>{let G=new XMLHttpRequest;s(h,{_xhr:G}),G.open("PUT",`${ye}/upload`),G.setRequestHeader("X-Storage-Key",N),G.setRequestHeader("Content-Type",V),X&&G.setRequestHeader("X-Upload-Token",X),G.upload.onprogress=nn=>{nn.lengthComputable&&s(h,{progress:Math.round(nn.loaded/nn.total*100)})},G.onload=()=>{G.status>=200&&G.status<300?A():nt(Object.assign(new Error(`Storage upload failed: HTTP ${G.status}`),{_step:"upload"}))},G.onerror=()=>nt(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),G.ontimeout=()=>nt(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),G.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let _e=await Ja(_t,N,V);s(h,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),A=_e?._step||"create";s(h,{status:"error",error:ve,_failedAt:A,_xhr:null})}},[s,n]),a=(0,ne.useCallback)((h,g)=>{let S=hu();i({id:S,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(S,h,g)},[i,o]),c=(0,ne.useCallback)((h,g)=>{for(let S of h)a(S,g)},[a]),l=(0,ne.useCallback)(h=>{let g=r.current.find(E=>E.id===h);if(!g||g.status!=="error")return;let S=g._failedAt||"create",T=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;o(h,g.file,g.options,S,T)},[o]),d=(0,ne.useCallback)(h=>{let g=r.current.find(S=>S.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ne.useCallback)(h=>{t(g=>g.filter(S=>S.id!==h))},[]),f=(0,ne.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),m=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),y=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:S,_xhr:T,_failedAt:E,...U})=>U);return{upload:a,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:f,isUploading:m}}var Xa=H(ie(),1);async function Ns(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function Za(e,t){return(0,Xa.useSyncExternalStore)(it,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ns(e,t),enabled:!!(e&&t)})}var ge=H(ie(),1);function qr(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(o.artifact_id)c=o;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 p=r.get(c.tool_id);n.timeline[p].artifact_ids.push(c.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,p)}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 p=r.get(c.tool_id);if(p!==void 0){let f=n.timeline[p];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return Pr(e,s)}function ec(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),o=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:qr(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let a=(0,ge.useCallback)(()=>{r(new Map),i([]),o.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:a}}function tc(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:qr(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Dr=H(ie(),1);function yu(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Ks(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 a=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(_u).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function nc(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=Q(),l=(0,Dr.useRef)(null),d=a?yu(a,n,r,s):["vfs","timeline-history","__disabled__"],p=F({queryKey:d,queryFn:()=>Ks(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Dr.useEffect)(()=>{if(!a||!i)return;let f=Y("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},m=>{let y=m?.path;return y?y===a||y.startsWith(a+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[a,i,o,c,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function _u(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}}wa(Ls);return dc(Ls);})();
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-09-06T15:05:48.823Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ac=Object.create;var sn=Object.defineProperty;var cc=Object.getOwnPropertyDescriptor;var uc=Object.getOwnPropertyNames;var lc=Object.getPrototypeOf,dc=Object.prototype.hasOwnProperty;var js=e=>{throw TypeError(e)};var fc=(e,t,n)=>t in e?sn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var on=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),pc=(e,t)=>{for(var n in t)sn(e,n,{get:t[n],enumerable:!0})},Vs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of uc(t))!dc.call(e,s)&&s!==n&&sn(e,s,{get:()=>t[s],enumerable:!(r=cc(t,s))||r.enumerable});return e};var H=(e,t,n)=>(n=e!=null?ac(lc(e)):{},Vs(t||!e||!e.__esModule?sn(n,"default",{value:e,enumerable:!0}):n,e)),mc=e=>Vs(sn({},"__esModule",{value:!0}),e);var K=(e,t,n)=>fc(e,typeof t!="symbol"?t+"":t,n),Nr=(e,t,n)=>t.has(e)||js("Cannot "+n);var u=(e,t,n)=>(Nr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(Nr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),C=(e,t,n)=>(Nr(e,t,"access private method"),n);var an=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return u(e,t,r)}});var $s=on((Ru,Hs)=>{Hs.exports={createClient:window.supabase.createClient}});var ie=on((jd,Ji)=>{Ji.exports=React});var cr=on((Vd,Yi)=>{Yi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Do=on((Qf,qo)=>{qo.exports=ReactDOM});var Jo=on(($f,zo)=>{zo.exports=ReactDOM});var Ls={};pc(Ls,{ComponentRenderer:()=>ka,EnforcementDeniedError:()=>vt,FormSubmissionError:()=>Et,GatewayRequestError:()=>Le,InteractionTrackingError:()=>Ct,KernelProvider:()=>Ma,QueryClientProvider:()=>In,auth:()=>Wo,awaitAnchorReady:()=>pn,awaitScopeReady:()=>ni,callTool:()=>Vo,cancelQueuedTurn:()=>hi,cancelTurn:()=>pi,clearCachedToken:()=>Vr,clearSession:()=>Jr,createItem:()=>Ko,disconnectSSE:()=>As,disposeVfsRealtimeWs:()=>kr,electHomeAnchor:()=>mn,emitEvent:()=>Po,fetchChannelMessages:()=>go,fetchChannelMessagesPage:()=>Fn,fetchChannelMessagesWithCards:()=>Rr,fetchEdgesForItem:()=>yr,fetchItemHistory:()=>br,fetchItemVersions:()=>Mn,fetchItems:()=>zt,fetchMemberFocus:()=>wr,fetchOpenEnvelope:()=>Sr,fetchRecentActivity:()=>vr,fetchResolvedItems:()=>Ns,fetchTimelineHistory:()=>Ks,fetchTurnQueueEntries:()=>mo,fetchTypeDefinitions:()=>gr,fetchVfsChildren:()=>mr,fetchVfsChildrenPage:()=>hr,fetchVfsItem:()=>pr,fetchVfsItemById:()=>fr,fetchVfsTree:()=>_r,gatewayCall:()=>R,getAccessToken:()=>Ie,getAnchor:()=>fn,getAnchorRef:()=>rt,getAnchorVersion:()=>Wr,getAssetUrl:()=>$o,getDefaultSort:()=>Ja,getHomeAnchor:()=>Ke,getMountVersion:()=>gn,getMounts:()=>St,getPathSubscriptionState:()=>Io,getQueryClient:()=>P,getRequiredFormFields:()=>Ya,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>zn,initSession:()=>Rt,initVfsRealtimeWs:()=>Qn,initializeFsaos:()=>fi,interpretSchema:()=>Qs,invalidateAllVfs:()=>vo,invalidateChannelMessages:()=>wo,invalidateChildren:()=>dr,invalidateItem:()=>Cs,invalidateOpenEnvelope:()=>So,invalidatePathAndParent:()=>yo,invalidateSubtree:()=>_o,invalidateTypes:()=>bo,isAnchorReady:()=>Gr,isScopeReady:()=>Jn,listChildren:()=>No,mount:()=>Bo,mountRealtimeScope:()=>Nn,normalizeItem:()=>he,onConnectionStateChange:()=>ko,pathSubscriptionMatches:()=>Ps,ping:()=>Eo,pushChanges:()=>jo,queryClient:()=>lo,readItem:()=>Qo,registerCleanup:()=>Ae,resetAllSdkState:()=>Tt,resolvePrincipalId:()=>Ia,resubscribePath:()=>Oo,setAnchor:()=>Ne,setCachedToken:()=>Gs,setQueryClient:()=>uo,setScope:()=>ti,setupRequireShim:()=>Go,signal:()=>Ho,startTracking:()=>Xn,steerTurn:()=>mi,submitForm:()=>gi,subscribeAnchor:()=>Br,subscribeArtifactStream:()=>Dr,subscribeMounts:()=>Gn,subscribeScope:()=>it,subscribeToEvents:()=>Y,subscribeToPath:()=>Er,subscribeToScope:()=>Ir,trackAction:()=>ui,trackEvent:()=>ot,trackPageView:()=>ci,unmountRealtimeScope:()=>Fo,updateItem:()=>Lo,uploadFile:()=>Xa,useAccounts:()=>ba,useAgentTimeline:()=>sc,useAllChannels:()=>qr,useArrangement:()=>Ga,useArtifactStream:()=>rc,useAsset:()=>Sa,useAuth:()=>Fr,useChannelMessages:()=>Fa,useChannels:()=>Da,useChildren:()=>sa,useComponent:()=>Ds,useCreate:()=>Na,useDelete:()=>ja,useDmChannels:()=>Ua,useEdges:()=>da,useEventStream:()=>Wa,useFileUpload:()=>ec,useInfiniteChannelMessages:()=>qa,useInfiniteChildren:()=>la,useInfiniteItems:()=>ua,useItem:()=>na,useItemById:()=>ra,useItemHistory:()=>ya,useItemVersions:()=>ga,useItems:()=>ca,useLink:()=>Ha,useList:()=>qs,useMemberFocus:()=>ha,useMounts:()=>wa,useMove:()=>Va,useMutation:()=>$a,useNotifications:()=>Us,useOpen:()=>pa,usePermission:()=>xa,usePermissions:()=>Pa,usePrincipal:()=>Aa,useRealtimeQuery:()=>Ba,useRecentActivity:()=>_a,useResolve:()=>aa,useResolvedItems:()=>nc,useScope:()=>va,useScopeReady:()=>ta,useSearch:()=>oa,useTheme:()=>Ca,useTimelineHistory:()=>ic,useTool:()=>Oa,useTree:()=>ia,useType:()=>fa,useTypeHelpers:()=>ma,useTypes:()=>Mr,useUnreadCounts:()=>Qa,useUpdate:()=>Ka,useUpdatePrincipal:()=>La,vfsKeys:()=>w,waitForPathReady:()=>Ao});var vt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);K(this,"name","EnforcementDeniedError");K(this,"deniedBy");K(this,"ruleKey");K(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 Ws=H($s(),1),cn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},un=Array.isArray(cn.sources)?cn.sources:[],hc=cn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",gc=cn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=cn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",M=(0,Ws.createClient)(hc,gc,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var dn=null,Vn=0,Bs,jr,Hn=!1;Bs=new Promise(e=>{jr=e});M.auth.onAuthStateChange((e,t)=>{t?.access_token?(dn=t.access_token,Vn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(dn=null,Vn=0),Hn||(Hn=!0,jr())});setTimeout(()=>{Hn||(Hn=!0,jr())},5e3);function Gs(e,t){dn=e,Vn=t??Math.floor(Date.now()/1e3)+3600}function Vr(){dn=null,Vn=0}async function Ie(){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 Bs,dn}var $n=null,Bn=null,zs=0,Kr=new Set,Hr,$r,Wn=!1;Hr=new Promise(e=>{$r=e});function Js(){zs++,Kr.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=$n!==t;$n=t,Bn=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],hn()),Wn||(Wn=!0,$r()),n&&Js()}function fn(){return $n}function rt(){return Bn}function Wr(){return zs}function Br(e){return Kr.add(e),()=>{Kr.delete(e)}}function pn(){return Hr}function Gr(){return Wn}var wt=null;function mn(e){if(wt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}wt=e,Ne(e)}function Ke(){return wt}var ue=[],Lr=new Set,Ys=0;function hn(){Ys++,Lr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function St(){return ue}function gn(){return Ys}function Gn(e){return Lr.add(e),()=>{Lr.delete(e)}}function zr(e){ue=e,hn()}function Xs(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],hn())}function Zs(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),hn(),Bn?.id===e&&wt&&Ne(wt))}var bt=null,ln=null;async function Rt(){return bt||ln||(ln=(async()=>{let e=st(),t=await Ie(),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 bt={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},bt})(),ln)}function zn(){return bt}function Jr(){bt=null,ln=null,$n=null,Bn=null,wt=null,ue=[]}var ei=[];function Ae(e){ei.push(e)}function Tt(){Jr(),Vr(),Wn=!1,Hr=new Promise(e=>{$r=e}),Js(),hn();for(let e of ei)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function st(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ti=Ne,fe=fn,be=Wr,it=Br,ni=pn,Jn=Gr;var Yr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,yc=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,ri=new Map,si=new Map,Ct=class extends Error{constructor(n,r,s,i){super(n);K(this,"code");K(this,"status");K(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function xt(e){let t=e?un.find(n=>n.id===e):un.find(n=>n.default===!0)??(un.length===1?un[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 Yn(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 _c(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function vc(e,t){if(!_c(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Xr(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function bc(e){try{let t=Xr(e)?.getItem(e.key)??void 0;return t&&Yr.test(t)?t:void 0}catch{return}}function ii(e,t){try{Xr(e)?.setItem(e.key,t)}catch{}}function oi(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=bc(t)??ri.get(e.id);if(n)return n;let r=crypto.randomUUID();return ri.set(e.id,r),ii(t,r),r}function ai(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=Xr(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=si.get(e.id),i=r&&typeof r.id=="string"&&Yr.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return si.set(e.id,c),ii(n,JSON.stringify(c)),c.id}function wc(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,o=Object.fromEntries(n.flatMap(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function ot(e,t={},n={}){let r=xt(n.source);if(vc(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??oi(r),o=n.sessionId??ai(r);if(![s,i,o].every(g=>Yr.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)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=wc(r,a),p=d?{...t,source_keys:d}:t,f=st(),m=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Ct(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let h=null;try{h=await y.json()}catch{}if(!y.ok||h?.success!==!0){let g=h;throw new Ct(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return h}function ci(e={},t={}){let n=xt(t.source),r=Yn("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return ot(r.observation,{...s,...e},{...t,source:n.id})}function ui(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=xt(n.source),s=Yn("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return ot(s.observation,{...t,...i},{...n,source:r.id})}function li(){try{let e=xt();return Yn("form_receipt",e),{visitor_id:oi(e),session_id:ai(e),source:e.id}}catch{return}}function di(e,t={}){let n=xt(t.source),r=Yn("form_receipt",n);return ot(r.observation,e,{...t,source:n.id})}var yn;function Xn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(yn)return yn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=xt(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 m=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};ot(f.observation,m,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=f=>{if(f.target instanceof Element)for(let m of r){let y=m.attribute;if(!y||!yc.test(y))continue;let h=f.target.closest(`[${y}]`);if(!h)continue;let g=h.getAttribute(y)?.trim();if(!g||g.length>128)continue;let S={};m.id_property&&(S[m.id_property]=g),m.element_property&&(S[m.element_property]=h.tagName.toLowerCase()),ot(m.observation,S,{source:t.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),p=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...m){a.apply(this,m),l()},window.history.replaceState=function(...m){c.apply(this,m),l()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),yn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),yn=void 0},yn}var Pt;function fi(e={}){return Pt||(Pt=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Xn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await Rt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),Pt=void 0)}}}catch(r){throw n(),Pt=void 0,r}})(),Pt)}var Sc=new Set(["list-memberships","init"]),Le=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);K(this,"name","GatewayRequestError");K(this,"method");K(this,"status");K(this,"statusText");K(this,"payload");K(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function R(e,t={}){let n=st(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await Ie();i&&(s.Authorization=`Bearer ${i}`),!Sc.has(e)&&!t._scope_path&&await pn();let o={...t},a=zn();!o.domain_scope_id&&a?.scope_id&&(o.domain_scope_id=a.scope_id);let c=fn();!o._scope_path&&c&&(o._scope_path=c);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:o})}),d=await l.text(),p=null;if(d)try{p=JSON.parse(d)}catch{}if(!l.ok||!p)throw new Le({method:e,status:l.status,statusText:l.statusText,payload:p,responseBody:d});if(p.success===!1){let f=p.error||"",m=p.denied_by||p.error_type||"";throw m==="rule"||m==="access"||m==="entitlement"||f==="RULE_DENIED"||f==="ACCESS_DENIED"||f==="PERMISSION_DENIED"||f==="ENTITLEMENT_REQUIRED"?new vt(p):new Le({method:e,status:l.status,statusText:l.statusText,payload:p,responseBody:d})}return p}async function Zr(e){try{return await R("execution-control-transition",e)}catch(t){if(!(t instanceof Le)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),R("execution-control-transition",e)}}function es(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function pi(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await Zr({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return es(i?{...s,state:i}:s)}async function mi(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await Zr({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return es(a?{...o,state:a}:o)}async function hi(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await Zr({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return es(i?{...s,outcome:i}:s)}var Rc=/^[a-z][a-z0-9_-]{0,63}$/,Tc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Et=class extends Error{constructor(n,r,s,i){super(n);K(this,"code");K(this,"status");K(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function gi(e,t,n={}){if(!Rc.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(!Tc.test(r))throw new TypeError("fillId must be a UUID");let s=st(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=li(),c=a?{visitor_id:a.visitor_id,session_id:a.session_id}:void 0,l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new Et(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await l.json()}catch{}if(!l.ok||d?.success!==!0){let p=d;throw new Et(p?.message||p?.error||`Form submission failed (${l.status})`,p?.error||"FORM_SUBMISSION_FAILED",l.status,r)}try{await di({fill_id:r,action_id:e,release_id:d.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0,...a?{source:a.source,visitorId:a.visitor_id,sessionId:a.session_id}:{}})}catch{}return d}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 at,je,It,yi,Cc=(yi=class extends le{constructor(){super();b(this,at);b(this,je);b(this,It);v(this,It,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,je)||this.setEventListener(u(this,It))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,It,t),(n=u(this,je))==null||n.call(this),v(this,je,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,at)!==t&&(v(this,at,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,at)=="boolean"?u(this,at):globalThis.document?.visibilityState!=="hidden"}},at=new WeakMap,je=new WeakMap,It=new WeakMap,yi),At=new Cc;var xc={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ve,ts,_i,Pc=(_i=class{constructor(){b(this,Ve,xc);b(this,ts,!1)}setTimeoutProvider(e){v(this,Ve,e)}setTimeout(e,t){return u(this,Ve).setTimeout(e,t)}clearTimeout(e){u(this,Ve).clearTimeout(e)}setInterval(e,t){return u(this,Ve).setInterval(e,t)}clearInterval(e){u(this,Ve).clearInterval(e)}},Ve=new WeakMap,ts=new WeakMap,_i),we=new Pc;function vi(e){setTimeout(e,0)}var rs=typeof window>"u"||"Deno"in globalThis;function q(){}function Si(e,t){return typeof e=="function"?e(t):e}function _n(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 Z(e,t){return typeof e=="function"?e(t):e}function er(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==vn(o,t.options))return!1}else if(!ct(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function tr(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(!ct(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function vn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>ns(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function ct(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ct(e[n],t[n])):!1}var Ec=Object.prototype.hasOwnProperty;function ss(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=bi(e)&&bi(t);if(!r&&!(ns(e)&&ns(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},l=0;for(let d=0;d<a;d++){let p=r?d:o[d],f=e[p],m=t[p];if(f===m){c[p]=f,(r?d<i:Ec.call(e,p))&&l++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){c[p]=m;continue}let y=ss(f,m,n+1);c[p]=y,y===f&&l++}return i===a&&l===i?e:c}function Ot(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 bi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ns(e){if(!wi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!wi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function wi(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ri(e){return new Promise(t=>{we.setTimeout(t,e)})}function bn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ss(e,t):t}function Ti(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ci(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var kt=Symbol();function nr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===kt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Mt(e,t){return typeof e=="function"?e(...t):!!e}function xi(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=()=>rs;return{isServer(){return e()},setIsServer(t){e=t}}})();function wn(){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 Pi=vi;function Ic(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=Pi,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var k=Ic();var Ft,He,qt,Ei,Ac=(Ei=class extends le{constructor(){super();b(this,Ft,!0);b(this,He);b(this,qt);v(this,qt,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,He)||this.setEventListener(u(this,qt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,He))==null||t.call(this),v(this,He,void 0))}setEventListener(t){var n;v(this,qt,t),(n=u(this,He))==null||n.call(this),v(this,He,t(this.setOnline.bind(this)))}setOnline(t){u(this,Ft)!==t&&(v(this,Ft,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,Ft)}},Ft=new WeakMap,He=new WeakMap,qt=new WeakMap,Ei),Dt=new Ac;function Oc(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??"online")==="online"?Dt.isOnline():!0}var rr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function sr(e){let t=!1,n=0,r,s=wn(),i=()=>s.status!=="pending",o=h=>{if(!i()){let g=new rr(h);f(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},l=()=>At.isFocused()&&(e.networkMode==="always"||Dt.isOnline())&&e.canRun(),d=()=>is(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},f=h=>{i()||(r?.(),s.reject(h))},m=()=>new Promise(h=>{r=g=>{(i()||l())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(S){h=Promise.reject(S)}Promise.resolve(h).then(p).catch(S=>{if(i())return;let T=e.retry??(Re.isServer()?0:3),E=e.retryDelay??Oc,U=typeof E=="function"?E(n,S):E,V=T===!0||typeof T=="number"&&n<T||typeof T=="function"&&T(n,S);if(t||!V){f(S);return}n++,e.onFail?.(n,S),Ri(U).then(()=>l()?void 0:m()).then(()=>{t?f(S):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?y():m().then(y),s)}}var ut,Ii,ir=(Ii=class{constructor(){b(this,ut)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_n(this.gcTime)&&v(this,ut,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,ut)!==void 0&&(we.clearTimeout(u(this,ut)),v(this,ut,void 0))}},ut=new WeakMap,Ii);var lt,Ut,de,dt,$,Sn,ft,se,Fi,Oe,ki,Mi=(ki=class extends ir{constructor(t){super();b(this,se);b(this,lt);b(this,Ut);b(this,de);b(this,dt);b(this,$);b(this,Sn);b(this,ft);v(this,ft,!1),v(this,Sn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,dt,t.client),v(this,de,u(this,dt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,lt,Oi(this.options)),this.state=t.state??u(this,lt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,$)?.promise}setOptions(t){if(this.options={...u(this,Sn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Oi(this.options);n.data!==void 0&&(this.setState(Ai(n.data,n.dataUpdatedAt)),v(this,lt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,de).remove(this)}setData(t,n){let r=bn(this.state.data,t,this.options);return C(this,se,Oe).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){C(this,se,Oe).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,$)?.promise;return u(this,$)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,lt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Z(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===kt||!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,$)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,$)?.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,$)&&(u(this,ft)||C(this,se,Fi).call(this)?u(this,$).cancel({revert:!0}):u(this,$).cancelRetry()),this.scheduleGc()),u(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||C(this,se,Oe).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,$)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,$))return u(this,$).continueRetry(),u(this,$).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,ft,!0),r.signal)})},i=()=>{let c=nr(this.options,n),d=(()=>{let p={client:u(this,dt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return v(this,ft,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,dt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),v(this,Ut,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&C(this,se,Oe).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),v(this,$,sr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof rr&&c.revert&&this.setState({...u(this,Ut),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{C(this,se,Oe).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{C(this,se,Oe).call(this,{type:"pause"})},onContinue:()=>{C(this,se,Oe).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await u(this,$).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 rr){if(c.silent)return u(this,$).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw C(this,se,Oe).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()}}},lt=new WeakMap,Ut=new WeakMap,de=new WeakMap,dt=new WeakMap,$=new WeakMap,Sn=new WeakMap,ft=new WeakMap,se=new WeakSet,Fi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Oe=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,...os(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Ai(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Ut,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),k.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,de).notify({query:this,type:"updated",action:t})})},ki);function os(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ai(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Oi(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 ee,I,Tn,J,pt,Qt,ke,$e,Cn,Nt,Kt,mt,ht,We,Lt,O,Rn,as,cs,us,ls,ds,fs,ps,Qi,Ui,xn=(Ui=class extends le{constructor(t,n){super();b(this,O);b(this,ee);b(this,I);b(this,Tn);b(this,J);b(this,pt);b(this,Qt);b(this,ke);b(this,$e);b(this,Cn);b(this,Nt);b(this,Kt);b(this,mt);b(this,ht);b(this,We);b(this,Lt,new Set);this.options=n,v(this,ee,t),v(this,$e,null),v(this,ke,wn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,I).addObserver(this),qi(u(this,I),this.options)?C(this,O,Rn).call(this):this.updateResult(),C(this,O,ls).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ms(u(this,I),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ms(u(this,I),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,C(this,O,ds).call(this),C(this,O,fs).call(this),u(this,I).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,I);if(this.options=u(this,ee).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Z(this.options.enabled,u(this,I))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");C(this,O,ps).call(this),u(this,I).setOptions(this.options),n._defaulted&&!Ot(this.options,n)&&u(this,ee).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,I),observer:this});let s=this.hasListeners();s&&Di(u(this,I),r,this.options,n)&&C(this,O,Rn).call(this),this.updateResult(),s&&(u(this,I)!==r||Z(this.options.enabled,u(this,I))!==Z(n.enabled,u(this,I))||pe(this.options.staleTime,u(this,I))!==pe(n.staleTime,u(this,I)))&&C(this,O,as).call(this);let i=C(this,O,cs).call(this);s&&(u(this,I)!==r||Z(this.options.enabled,u(this,I))!==Z(n.enabled,u(this,I))||i!==u(this,We))&&C(this,O,us).call(this,i)}getOptimisticResult(t){let n=u(this,ee).getQueryCache().build(u(this,ee),t),r=this.createResult(n,t);return Mc(this,r)&&(v(this,J,r),v(this,Qt,this.options),v(this,pt,u(this,I).state)),r}getCurrentResult(){return u(this,J)}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,ke).status==="pending"&&u(this,ke).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Lt).add(t)}getCurrentQuery(){return u(this,I)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,ee).defaultQueryOptions(t),r=u(this,ee).getQueryCache().build(u(this,ee),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return C(this,O,Rn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,J)))}createResult(t,n){let r=u(this,I),s=this.options,i=u(this,J),o=u(this,pt),a=u(this,Qt),l=t!==r?t.state:u(this,Tn),{state:d}=t,p={...d},f=!1,m;if(n._optimisticResults){let N=this.hasListeners(),X=!N&&qi(t,n),ye=N&&Di(t,r,n,s);(X||ye)&&(p={...p,...os(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:h,status:g}=p;m=p.data;let S=!1;if(n.placeholderData!==void 0&&m===void 0&&g==="pending"){let N;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(N=i.data,S=!0):N=typeof n.placeholderData=="function"?n.placeholderData(u(this,Kt)?.state.data,u(this,Kt)):n.placeholderData,N!==void 0&&(g="success",m=bn(i?.data,N,n),f=!0)}if(n.select&&m!==void 0&&!S)if(i&&m===o?.data&&n.select===u(this,Cn))m=u(this,Nt);else try{v(this,Cn,n.select),m=n.select(m),m=bn(i?.data,m,n),v(this,Nt,m),v(this,$e,null)}catch(N){v(this,$e,N)}u(this,$e)&&(y=u(this,$e),m=u(this,Nt),h=Date.now(),g="error");let T=p.fetchStatus==="fetching",E=g==="pending",U=g==="error",V=E&&T,B=m!==void 0,re={status:g,fetchStatus:p.fetchStatus,isPending:E,isSuccess:g==="success",isError:U,isInitialLoading:V,isLoading:V,data:m,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:T,isRefetching:T&&!E,isLoadingError:U&&!B,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&B,isStale:hs(t,n),refetch:this.refetch,promise:u(this,ke),isEnabled:Z(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let N=re.data!==void 0,X=re.status==="error"&&!N,ye=A=>{X?A.reject(re.error):N&&A.resolve(re.data)},_e=()=>{let A=v(this,ke,re.promise=wn());ye(A)},ve=u(this,ke);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(X||re.data!==ve.value)&&_e();break;case"rejected":(!X||re.error!==ve.reason)&&_e();break}}return re}updateResult(){let t=u(this,J),n=this.createResult(u(this,I),this.options);if(v(this,pt,u(this,I).state),v(this,Qt,this.options),u(this,pt).data!==void 0&&v(this,Kt,u(this,I)),Ot(n,t))return;v(this,J,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Lt).size)return!0;let o=new Set(i??u(this,Lt));return this.options.throwOnError&&o.add("error"),Object.keys(u(this,J)).some(a=>{let c=a;return u(this,J)[c]!==t[c]&&o.has(c)})};C(this,O,Qi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&C(this,O,ls).call(this)}},ee=new WeakMap,I=new WeakMap,Tn=new WeakMap,J=new WeakMap,pt=new WeakMap,Qt=new WeakMap,ke=new WeakMap,$e=new WeakMap,Cn=new WeakMap,Nt=new WeakMap,Kt=new WeakMap,mt=new WeakMap,ht=new WeakMap,We=new WeakMap,Lt=new WeakMap,O=new WeakSet,Rn=function(t){C(this,O,ps).call(this);let n=u(this,I).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},as=function(){C(this,O,ds).call(this);let t=pe(this.options.staleTime,u(this,I));if(Re.isServer()||u(this,J).isStale||!_n(t))return;let r=Zn(u(this,J).dataUpdatedAt,t)+1;v(this,mt,we.setTimeout(()=>{u(this,J).isStale||this.updateResult()},r))},cs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,I)):this.options.refetchInterval)??!1},us=function(t){C(this,O,fs).call(this),v(this,We,t),!(Re.isServer()||Z(this.options.enabled,u(this,I))===!1||!_n(u(this,We))||u(this,We)===0)&&v(this,ht,we.setInterval(()=>{(this.options.refetchIntervalInBackground||At.isFocused())&&C(this,O,Rn).call(this)},u(this,We)))},ls=function(){C(this,O,as).call(this),C(this,O,us).call(this,C(this,O,cs).call(this))},ds=function(){u(this,mt)!==void 0&&(we.clearTimeout(u(this,mt)),v(this,mt,void 0))},fs=function(){u(this,ht)!==void 0&&(we.clearInterval(u(this,ht)),v(this,ht,void 0))},ps=function(){let t=u(this,ee).getQueryCache().build(u(this,ee),this.options);if(t===u(this,I))return;let n=u(this,I);v(this,I,t),v(this,Tn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Qi=function(t){k.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,J))}),u(this,ee).getQueryCache().notify({query:u(this,I),type:"observerResultsUpdated"})})},Ui);function kc(e,t){return Z(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function qi(e,t){return kc(e,t)||e.state.data!==void 0&&ms(e,t,t.refetchOnMount)}function ms(e,t,n){if(Z(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&hs(e,t)}return!1}function Di(e,t,n,r){return(e!==t||Z(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&hs(e,n)}function hs(e,t){return Z(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function Mc(e,t){return!Ot(e.getCurrentResult(),t)}function jt(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,p=y=>{xi(y,()=>t.signal,()=>d=!0)},f=nr(t.options,t.fetchOptions),m=async(y,h,g)=>{if(d)return Promise.reject();if(h==null&&y.pages.length)return Promise.resolve(y);let T=(()=>{let B={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p(B),B})(),E=await f(T),{maxPages:U}=t.options,V=g?Ci:Ti;return{pages:V(y.pages,E,U),pageParams:V(y.pageParams,h,U)}};if(s&&i.length){let y=s==="backward",h=y?Ni:gs,g={pages:i,pageParams:o},S=h(r,g);a=await m(g,S,y)}else{let y=e??i.length;do{let h=c===0?o[0]??r.initialPageParam:gs(r,a);if(c>0&&h==null)break;a=await m(a,h),c++}while(c<y)}return a};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 gs(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 Ni(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ki(e,t){return t?gs(e,t)!=null:!1}function Li(e,t){return!t||!e.getPreviousPageParam?!1:Ni(e,t)!=null}var ys=class extends xn{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:jt()})}getOptimisticResult(e){return e.behavior=jt(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c==="forward",d=s&&c==="forward",p=o&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ki(t,n.data),hasPreviousPage:Li(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:a&&!l&&!p,isRefetching:i&&!d&&!f}}};var Pn,Te,z,gt,Ce,Be,ji,Vi=(ji=class extends ir{constructor(t){super();b(this,Ce);b(this,Pn);b(this,Te);b(this,z);b(this,gt);v(this,Pn,t.client),this.mutationId=t.mutationId,v(this,z,t.mutationCache),v(this,Te,[]),this.state=t.state||_s(),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,Te).includes(t)||(u(this,Te).push(t),this.clearGcTimeout(),u(this,z).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Te,u(this,Te).filter(n=>n!==t)),this.scheduleGc(),u(this,z).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Te).length||(this.state.status==="pending"?this.scheduleGc():u(this,z).remove(this))}continue(){return u(this,gt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{C(this,Ce,Be).call(this,{type:"continue"})},r={client:u(this,Pn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,gt,sr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{C(this,Ce,Be).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{C(this,Ce,Be).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,z).canRun(this)}));let s=this.state.status==="pending",i=!u(this,gt).canStart();try{if(s)n();else{C(this,Ce,Be).call(this,{type:"pending",variables:t,isPaused:i}),u(this,z).config.onMutate&&await u(this,z).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&C(this,Ce,Be).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await u(this,gt).start();return await u(this,z).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await u(this,z).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),C(this,Ce,Be).call(this,{type:"success",data:o}),o}catch(o){try{await u(this,z).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await u(this,z).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw C(this,Ce,Be).call(this,{type:"error",error:o}),o}finally{u(this,z).runNext(this)}}},Pn=new WeakMap,Te=new WeakMap,z=new WeakMap,gt=new WeakMap,Ce=new WeakSet,Be=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),k.batch(()=>{u(this,Te).forEach(r=>{r.onMutationUpdate(t)}),u(this,z).notify({mutation:this,type:"updated",action:t})})},ji);function _s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Me,me,En,Hi,$i=(Hi=class extends le{constructor(t={}){super();b(this,Me);b(this,me);b(this,En);this.config=t,v(this,Me,new Set),v(this,me,new Map),v(this,En,0)}build(t,n,r){let s=new Vi({client:t,mutationCache:this,mutationId:++an(this,En)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,Me).add(t);let n=or(t);if(typeof n=="string"){let r=u(this,me).get(n);r?r.push(t):u(this,me).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,Me).delete(t)){let n=or(t);if(typeof n=="string"){let r=u(this,me).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,me).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=or(t);if(typeof n=="string"){let s=u(this,me).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=or(t);return typeof n=="string"?u(this,me).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){k.batch(()=>{u(this,Me).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,Me).clear(),u(this,me).clear()})}getAll(){return Array.from(u(this,Me))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>tr(n,r))}findAll(t={}){return this.getAll().filter(n=>tr(t,n))}notify(t){k.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return k.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Me=new WeakMap,me=new WeakMap,En=new WeakMap,Hi);function or(e){return e.options.scope?.id}var Fe,Ge,te,qe,De,ar,vs,Wi,bs=(Wi=class extends le{constructor(t,n){super();b(this,De);b(this,Fe);b(this,Ge);b(this,te);b(this,qe);v(this,Fe,t),this.setOptions(n),this.bindMethods(),C(this,De,ar).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,Fe).defaultMutationOptions(t),Ot(this.options,n)||u(this,Fe).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,te),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():u(this,te)?.state.status==="pending"&&u(this,te).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,te)?.removeObserver(this)}onMutationUpdate(t){C(this,De,ar).call(this),C(this,De,vs).call(this,t)}getCurrentResult(){return u(this,Ge)}reset(){u(this,te)?.removeObserver(this),v(this,te,void 0),C(this,De,ar).call(this),C(this,De,vs).call(this)}mutate(t,n){return v(this,qe,n),u(this,te)?.removeObserver(this),v(this,te,u(this,Fe).getMutationCache().build(u(this,Fe),this.options)),u(this,te).addObserver(this),u(this,te).execute(t)}},Fe=new WeakMap,Ge=new WeakMap,te=new WeakMap,qe=new WeakMap,De=new WeakSet,ar=function(){let t=u(this,te)?.state??_s();v(this,Ge,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},vs=function(t){k.batch(()=>{if(u(this,qe)&&this.hasListeners()){let n=u(this,Ge).variables,r=u(this,Ge).context,s={client:u(this,Fe),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,qe).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,qe).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,qe).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,qe).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,Ge))})})},Wi);var xe,Bi,Gi=(Bi=class extends le{constructor(t={}){super();b(this,xe);this.config=t,v(this,xe,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??vn(s,n),o=this.get(i);return o||(o=new Mi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){u(this,xe).has(t.queryHash)||(u(this,xe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,xe).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,xe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){k.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,xe).get(t)}getAll(){return[...u(this,xe).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>er(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>er(t,r)):n}notify(t){k.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){k.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){k.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},xe=new WeakMap,Bi);var D,ze,Je,Vt,Ht,Ye,$t,Wt,zi,ws=(zi=class{constructor(e={}){b(this,D);b(this,ze);b(this,Je);b(this,Vt);b(this,Ht);b(this,Ye);b(this,$t);b(this,Wt);v(this,D,e.queryCache||new Gi),v(this,ze,e.mutationCache||new $i),v(this,Je,e.defaultOptions||{}),v(this,Vt,new Map),v(this,Ht,new Map),v(this,Ye,0)}mount(){an(this,Ye)._++,u(this,Ye)===1&&(v(this,$t,At.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onFocus())})),v(this,Wt,Dt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onOnline())})))}unmount(){var e,t;an(this,Ye)._--,u(this,Ye)===0&&((e=u(this,$t))==null||e.call(this),v(this,$t,void 0),(t=u(this,Wt))==null||t.call(this),v(this,Wt,void 0))}isFetching(e){return u(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,ze).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,o=Si(t,i);if(o!==void 0)return u(this,D).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return k.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);k.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,D);return k.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=k.batch(()=>u(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return k.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=k.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=jt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=jt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Dt.isOnline()?u(this,ze).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,D)}getMutationCache(){return u(this,ze)}getDefaultOptions(){return u(this,Je)}setDefaultOptions(e){v(this,Je,e)}setQueryDefaults(e,t){u(this,Vt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Vt).values()],n={};return t.forEach(r=>{ct(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Ht).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Ht).values()],n={};return t.forEach(r=>{ct(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,Je).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=vn(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===kt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,Je).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,D).clear(),u(this,ze).clear()}},D=new WeakMap,ze=new WeakMap,Je=new WeakMap,Vt=new WeakMap,Ht=new WeakMap,Ye=new WeakMap,$t=new WeakMap,Wt=new WeakMap,zi);var Bt=H(ie(),1),Xi=H(cr(),1),Ss=Bt.createContext(void 0),Q=e=>{let t=Bt.useContext(Ss);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},In=({client:e,children:t})=>(Bt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Xi.jsx)(Ss.Provider,{value:e,children:t}));var ur=H(ie(),1),Zi=ur.createContext(!1),eo=()=>ur.useContext(Zi),$d=Zi.Provider;var An=H(ie(),1),Fc=H(cr(),1);function qc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Dc=An.createContext(qc()),to=()=>An.useContext(Dc);var no=H(ie(),1);var ro=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Mt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},so=e=>{no.useEffect(()=>{e.clearReset()},[e])},io=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Mt(n,[e.error,r]));var oo=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))}},ao=(e,t)=>e.isLoading&&e.isFetching&&!t,co=(e,t)=>e?.suspense&&t.isPending,Rs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Xe=H(ie(),1);function lr(e,t,n){let r=eo(),s=to(),i=Q(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",oo(o),ro(o,s,a),so(s);let c=!i.getQueryCache().get(o.queryHash),[l]=Xe.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(Xe.useSyncExternalStore(Xe.useCallback(f=>{let m=p?l.subscribe(k.batchCalls(f)):q;return l.updateResult(),m},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Xe.useEffect(()=>{l.setOptions(o)},[o,l]),co(o,d))throw Rs(o,l,s);if(io({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Re.isServer()&&ao(d,r)&&(c?Rs(o,l,s):a?.promise)?.catch(q).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return lr(e,xn,t)}var Ue=H(ie(),1);function Qe(e,t){let n=Q(t),[r]=Ue.useState(()=>new bs(n,e));Ue.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Ue.useSyncExternalStore(Ue.useCallback(o=>r.subscribe(k.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Ue.useCallback((o,a)=>{r.mutate(o,a).catch(q)},[r]);if(s.error&&Mt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function On(e,t){return lr(e,ys,t)}var Gt=null;function uo(e){if(Gt&&Gt!==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.");Gt=e}function P(){return Gt||(Gt=new ws({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Gt}var lo=new Proxy({},{get(e,t,n){let r=P(),s=r[t];return typeof s=="function"?s.bind(r):s}});function W(){return fe()??"__unscoped__"}var w={all:()=>["vfs",W()],item:e=>["vfs",W(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",W(),"children",e],allChildren:()=>["vfs",W(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",W(),"search",e,...t??[]],items:(e,t)=>["vfs",W(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",W(),"items"],tree:(e,t)=>["vfs",W(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",W(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",W(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",W(),"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",W(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",W(),"channel-messages"],channels:e=>["vfs",W(),"channels",e??"all"],allChannels:()=>["vfs",W(),"channels"],notifications:(e,t)=>["vfs",W(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",W(),"notifications"],unreadCounts:()=>["vfs",W(),"unread-counts"],memberships:e=>["memberships",e]};function fo(){return new Date().toISOString()}function po(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function he(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||fo(),updated_at:e.updated_at||fo(),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 kn(e){return(e.content?.items||e.items||[]).map(he)}async function fr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=he(t);return r.path&&P().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=he(n);return r.path&&P().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function pr(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return he(t);let n=t.item;return n?he(n):null}catch{return null}}async function mr(e){try{let t=await R("list",{path:e,limit:200}),n=kn(t);for(let r of n)P().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function mo(e,t){let{items:n}=await zt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function hr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=kn(r);for(let i of s)P().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 gr(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 o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function yr(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||po(),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||po(),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 _r(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),o=kn(i);for(let a of o)P().setQueryData(w.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function vr(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 Mn(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 br(e,t=50,n=0){return Mn(e,{limit:t,offset:n})}async function wr(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=kn(s);for(let o of i)P().setQueryData(w.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Sr(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 zt(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=kn(r);for(let i of s)P().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 Uc(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 ho(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:Uc(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 Ts(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,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 go(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 Ts(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function Rr(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||[],o=Ts(i),a=ho(i),c=new Map,l=[];for(let d of a)if(d.parentMessagePath){let p=c.get(d.parentMessagePath)||[];p.push(d),c.set(d.parentMessagePath,p)}else l.push(d);return{messages:o,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 Fn(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||[],o=ho(i),a=new Map,c=[];for(let l of o)if(l.parentMessagePath){let d=a.get(l.parentMessagePath)||[];d.push(l),a.set(l.parentMessagePath,d)}else c.push(l);return{messages:Ts(i),messageCards:a,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 dr(e){P().invalidateQueries({queryKey:w.children(e)})}function Cs(e){P().invalidateQueries({queryKey:w.item(e)})}function yo(e,t){Cs(e),dr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&dr(r)}function _o(e){let t=e+"/";P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function vo(){P().invalidateQueries({queryKey:w.all()})}function bo(e){P().invalidateQueries({queryKey:w.types(e)})}function wo(e,t){e?P().invalidateQueries({queryKey:w.channelMessages(e,t)}):P().invalidateQueries({queryKey:w.allChannelMessages()})}function So(e,t){e&&t?P().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):P().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var Qc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function L(...e){Qc&&console.log("[WS]",...e)}var x=null,Jt=null,Yt=null,qn=0,Nc=3e4,Ro=1e4,Zt=!1,xo=3e4,Kc=xo*2+5e3,Tr=0,Cr=null,To=!1;function Lc(){Un(),Tr=Date.now(),Cr=setInterval(()=>{if(x&&x.readyState===WebSocket.OPEN&&Date.now()-Tr>Kc){L("ping: no inbound traffic for",Date.now()-Tr,"ms \u2014 closing half-open socket");try{x.close(4e3,"liveness timeout")}catch{}return}et({type:"ping"})},xo)}function Un(){Cr&&(clearInterval(Cr),Cr=null)}function jc(){typeof document>"u"||(document.hidden?Un():Dn()&&(L("Tab visible, reconnecting..."),yt()))}function Vc(){To||typeof document>"u"||(document.addEventListener("visibilitychange",jc),To=!0)}var oe={};function Ps(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Xt=[],en=new Map,Pe=new Map,Ee=new Map,Ze=new Map,xs="disconnected",xr=[];function Pr(e){if(xs!==e){xs=e;for(let t of[...xr])try{t(e)}catch{}}}function Hc(e){Ee.set(e,"ready");let t=Ze.get(e);if(t){Ze.delete(e);for(let n of t)n()}}function $c(){for(let e of Ee.keys())Ee.set(e,"disconnected")}function Es(e,t){Ee.set(e,"pending"),et({type:"subscribe_path",path:e,event_types:t})}function Wc(){return Object.keys(oe).some(t=>oe[t]&&oe[t].length>0)||Xt.length>0}function Dn(){return en.size>0||Pe.size>0}async function yt(){if(!Dn()){L("ensureConnection: no active subscriptions, skipping");return}if(x&&x.readyState===WebSocket.OPEN){L("ensureConnection: already open");return}if(Jt)return L("ensureConnection: connection already in flight, waiting..."),Jt;if(x){L("ensureConnection: killing stale WS in state",x.readyState);try{x.close()}catch{}x=null}return Zt=!1,Jt=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await Ie();if(!n){L("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)}`,L("ensureConnection: opening WS to",i.substring(0,50)+"..."),Pr("connecting"),x=new WebSocket(i);let o=x;await new Promise((a,c)=>{if(!x)return c(new Error("WebSocket not created"));let l=setTimeout(()=>{if(x===o){if(L("ensureConnection: TIMEOUT after",Ro,"ms"),x&&x.readyState!==WebSocket.OPEN){try{x.close()}catch{}x=null}c(new Error("WebSocket connection timeout"))}},Ro);o.onopen=()=>{x===o&&(clearTimeout(l),L("ensureConnection: CONNECTED"),qn=0,Pr("connected"),Bc(),(typeof document>"u"||!document.hidden)&&Lc(),Vc(),a())},o.onmessage=d=>{x===o&&Gc(d.data)},o.onerror=()=>{L("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),x===o&&(L("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),x=null,Un(),$c(),Pr("disconnected"),!Zt&&Dn()&&Co(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){L("ensureConnection: failed -",e?.message||e)}finally{Jt=null}})(),Jt}function Co(){if(Yt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,qn)+Math.random()*1e3,Nc);qn++,L("scheduleReconnect: attempt",qn,"in",Math.round(e),"ms"),Yt=setTimeout(()=>{Yt=null,Dn()&&yt()},e)}function Bc(){for(let e of en.values())L("resubscribeAll: scope",e.scope_id),et({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of Pe.values())L("resubscribeAll: path",e.path),Es(e.path,e.event_types)}function et(e){x&&x.readyState===WebSocket.OPEN&&x.send(JSON.stringify(e))}function Gc(e){Tr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Hc(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="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!=="*"&&Ps(s,r.path)&&i.forEach(o=>o(r));oe["*"]&&oe["*"].forEach(s=>s(r));for(let s of Xt)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function Is(){!Wc()&&en.size===0&&Pe.size===0&&x&&(Zt=!0,Un(),x.close(),x=null,Zt=!1)}function Er(e,t){return oe[e]||(oe[e]=[]),oe[e].push(t),Pe.has(e)||(Pe.set(e,{path:e,event_types:["token_stream"]}),x&&x.readyState===WebSocket.OPEN?Es(e,["token_stream"]):Ee.set(e,"pending")),yt(),()=>{let n=oe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete oe[e],Pe.delete(e),Ee.delete(e),Ze.delete(e),et({type:"unsubscribe_path",path:e}))}Is()}}function Y(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Xt.push(...s),Dn()&&yt(),()=>{for(let i of s){let o=Xt.indexOf(i);o!==-1&&Xt.splice(o,1)}Is()}}function Ir(e,t=["vfs_change","ccm_change"]){return L("subscribeToScope:",e,t),en.set(e,{scope_id:e,event_types:t}),x&&x.readyState===WebSocket.OPEN&&et({type:"subscribe",scope_id:e,event_types:t}),yt(),()=>{en.delete(e),et({type:"unsubscribe",scope_id:e}),Is()}}function Po(e,t,n={}){et({type:"emit",scope_id:e,event_type:t,payload:n})}function As(){L("disconnectSSE: tearing down"),Zt=!0,Un(),x&&(x.close(),x=null),Yt&&(clearTimeout(Yt),Yt=null),Jt=null,Zt=!1,qn=0;for(let e of Object.keys(oe))delete oe[e];Xt.length=0,en.clear(),Pe.clear(),Ee.clear(),Ze.clear(),Pr("disconnected")}function Eo(){et({type:"ping"})}function Io(e){return Pe.has(e)?Ee.get(e)??"pending":"unsubscribed"}function Ao(e,t=5e3){return Pe.has(e)?Ee.get(e)==="ready"&&x&&x.readyState===WebSocket.OPEN?Promise.resolve(!0):(yt(),new Promise(n=>{let r=!1,s=Ze.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Ze.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Ze.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Ze.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Oo(e){let t=Pe.get(e);if(!t){L("resubscribePath: no active subscription for",e);return}x&&x.readyState===WebSocket.OPEN?(L("resubscribePath: re-sending frame for",e),Es(t.path,t.event_types)):(Ee.set(e,"pending"),yt())}function ko(e){xr.push(e);try{e(xs)}catch{}return()=>{let t=xr.indexOf(e);t!==-1&&xr.splice(t,1)}}Ae(As);var tn=new Map,Ar=null,Or=null,tt=new Map,Mo=250;function Qn(e){kr(),Nn(e),Ar=Y("vfs_change",t=>zc(t)),Or=Y("ccm_change",t=>Jc(t))}function Nn(e){if(tn.has(e))return;let t=Ir(e,["vfs_change","ccm_change"]);tn.set(e,t)}function Fo(e){let t=tn.get(e);t&&(t(),tn.delete(e))}function kr(){for(let[,e]of tn)e();tn.clear(),Ar&&(Ar(),Ar=null),Or&&(Or(),Or=null),tt.forEach(e=>clearTimeout(e)),tt.clear()}Ae(kr);function zc(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=tt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{tt.delete(s),Yc(n,t,e,s)},Mo);tt.set(s,o)}function Jc(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=tt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{tt.delete(s),t&&P().invalidateQueries({queryKey:w.edges(t)}),n&&P().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&P().invalidateQueries({predicate:a=>a.queryKey[0]==="vfs"&&a.queryKey[1]==="edges"})},Mo);tt.set(s,o)}function Yc(e,t,n,r){if((e||"").toUpperCase()==="DELETE")P().removeQueries({queryKey:w.item(t)}),P().removeQueries({queryKey:w.children(t)}),P().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},o=he(i);o&&o.id&&P().setQueryData(w.item(t),o)}catch{}P().invalidateQueries({queryKey:w.children(r)}),P().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let a=o[2];return t.startsWith(a+"/")||t===a}}),n.item_id&&P().invalidateQueries({queryKey:w.itemById(n.item_id)})}var Os=H(ie(),1),Uo=H(Do(),1);function Qo(e){return R("read",{path:e})}function No(e,t){return R("list",{path:e,...t})}function Ko(e){return R("create",e)}function Lo(e){return R("update",e)}function jo(e){return R("create",e)}function Vo(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Ho(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function $o(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Wo={signIn:e=>e.provider?M.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):M.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>M.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await M.auth.signOut(),Tt(),P().clear()},getSession:()=>M.auth.getSession().then(e=>e.data.session),getUser:()=>M.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=M.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>M.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>M.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Bo(){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,Uo.createRoot)(e).render((0,Os.createElement)(In,{client:P()},(0,Os.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 Go(){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(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}var _=H(ie(),1),Zc=H(Jo(),1),eu=H(cr(),1);function Xc(e){return`${e}/settings/mounts`}var Kn=null;async function ks(e,t){Kn=Xc(e);try{let s=((await R("read",{path:Kn}))?.item?.type_data?.mounts??[]).map(t).filter(o=>o!==null),i=Ke();return i&&!s.some(o=>o.id===i.id)&&s.unshift(i),zr(s),s}catch{let n=Ke(),r=n?[n]:[];return zr(r),r}}async function Yo(){if(!Kn)return;let e=St().map(n=>n.id),t=rt()?.id??null;try{await R("update",{path:Kn,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Kn.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 Ms(e){Xs(e),await Yo()}async function Xo(e){Zs(e),await Yo()}function j(){return(0,_.useSyncExternalStore)(it,be,be)}function ta(){return j(),Jn()}function na(e){return j(),F({queryKey:w.item(e),queryFn:()=>pr(e),enabled:!!e})}function ra(e){return j(),F({queryKey:w.itemById(e),queryFn:()=>fr(e),enabled:!!e})}function qs(e){return j(),F({queryKey:w.children(e),queryFn:()=>mr(e),enabled:!!e})}function sa(e){let t=qs(e);return{...t,children:t.data??[]}}function ia(e,t=1){return j(),F({queryKey:w.tree(e,t),queryFn:()=>_r(e,t),enabled:!!e})}function oa(e,t){return j(),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(he)},enabled:!!e&&e.length>0})}function aa(e){j();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 ca(e){j();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>zt(t),enabled:!!t?.type,select:n=>n.items})}function ua(e){j();let t=e?.limit??20,n=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),r=On({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>zt({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,o,a)=>{if(!(i.items.length<t))return a+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,o=[];for(let a of r.data.pages)for(let c of a.items)c.id&&!i.has(c.id)&&(i.add(c.id),o.push(c));return o},[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 la(e){j();let t=20,n=On({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>hr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function da(e){return j(),F({queryKey:w.edges(e),queryFn:()=>yr(e),enabled:!!e})}function Mr(e){return j(),F({queryKey:w.types(e),queryFn:()=>gr(e)})}function fa(e,t){let n=Mr(t);return{...n,data:n.data?.get(e)??void 0}}function pa(e,t){j();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 o=await Sr(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Zo={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 ma(e){let t=Mr(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:m=>n.get(m.item_type)?.is_container??!1,isScope:m=>n.get(m.item_type)?.is_scope??!1,isScopeType:m=>n.get(m)?.is_scope??!1,isContainerType:m=>n.get(m)?.is_container??!1,getTypeDefinition:m=>n.get(m),getTypeColor:m=>n.get(m)?.color??"gray",getTypeIcon:m=>n.get(m)?.icon??"File",getTypeDisplayName:m=>n.get(m)?.display_name??m,getKnownEdgeTypes:()=>Object.entries(Zo).map(([m,y])=>({key:m,label:y})),getEdgeTypeLabel:m=>Zo[m]??m.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function ha(e,t,n){return j(),F({queryKey:w.memberFocus(e),queryFn:()=>wr(e,t,n),enabled:!!e})}function ga(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:()=>Mn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function ya(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>br(e,t,n),enabled:!!e})}function _a(e,t=50,n=0){return j(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>vr(e,t,n),enabled:!!e})}function va(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Rt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var tu=[];function Ln(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function ba(){let{user:e}=Fr(),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??tu,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,m)=>Number(p(m))-Number(p(f)))},[s]),o=(0,_.useSyncExternalStore)(it,be,be),a=(0,_.useMemo)(()=>{let d=rt();return d?r.find(p=>p.accountId===d.id)??null:null},[o,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];mn(Ln(d)),Qn(d.accountId),d.personalSpacePath&&ks(d.personalSpacePath,p=>{let f=r.find(m=>m.accountId===p);return f?Ln(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let p=r.find(m=>m.path===d);if(!p)return;let f=Ln(p);Ke()?Ne(f):(mn(f),p.personalSpacePath&&ks(p.personalSpacePath,m=>{let y=r.find(h=>h.accountId===m);return y?Ln(y):null}).catch(()=>{})),Qn(p.accountId)},[r]),l=(0,_.useCallback)(d=>{let p=r.find(f=>f.path===d);p&&(Ms(Ln(p)).catch(()=>{}),Nn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:a,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function wa(){let e=(0,_.useSyncExternalStore)(Gn,gn,gn);return{mounts:(0,_.useMemo)(()=>St(),[e]),homeAnchor:Ke(),anchor:rt(),setAnchor:Ne,mount:Ms,unmount:Xo}}function Fr(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{M.auth.getSession().then(({data:m,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m?.session??null),t(m?.session?.user??null),i(!1)}).catch(m=>{console.warn("[useAuth] getSession threw, clearing stale session:",m?.message),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=M.auth.onAuthStateChange((m,y)=>{if(m==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),M.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=f,()=>{f?.unsubscribe()}},[]);let a=(0,_.useCallback)(async f=>f.provider?M.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):M.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>M.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await M.auth.signOut(),Tt(),P().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:m}=await M.auth.resetPasswordForEmail(f);if(m)throw m},[]),p=(0,_.useCallback)(async(f,m)=>{let{error:y}=await M.auth.signInWithOtp({email:f,options:m?{emailRedirectTo:m}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:p}}function Sa(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(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}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var jn={},ea={};Ae(()=>{for(let e of Object.keys(jn))delete jn[e]});var Ra=null;function Ta(e){Ra=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function nu(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||Zc;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}:eu;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 ru(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function su(e,t){if(!ea[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=ru(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),ea[e]=s}catch{}}function iu(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)(nu),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Ds(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let a=!1;s(!0),o(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=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,p=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(a)return;if(jn[p]){n(()=>jn[p]),s(!1);return}let m=await fetch(f);if(!m.ok)throw new Error(`Failed to fetch bundle: ${m.status} ${m.statusText} (${f})`);let y=await m.text();if(a)return;let h=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");su(h).catch(()=>{});let g=iu(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})`);jn[p]=g,a||(n(()=>g),s(!1))}catch(d){a||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{a=!0}},[e]),{Component:t,loading:r,error:i}}var ou=["--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 Ca(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return ou.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function xa(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Pa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,nn=null,Fs=new Set;function au(){Fs.forEach(e=>e())}Ae(()=>{ae=null,nn=null});async function Ea(e){let t=e;if(!t){let{data:r}=await M.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:o,vfsPath:a}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:o,vfsPath:a}}return nn||(nn=(async()=>{try{let{data:r,error:s}=await M.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,o=null;if(i){let{data:c}=await M.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);o=l.find(d=>d.split("/").length===4)??l[0]??null}let a={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:o};return ae={authUserId:t,...a},a}finally{nn=null}})(),nn)}async function Ia(e){return(await Ea(e)).principalId}function Aa(){let e=Fr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let a=ae;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Fs.add(o),()=>{Fs.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Ea(t.id).then(o=>{s(o)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Oa(){return{data:null,loading:!1,error:null}}function ka(e){let{path:t,...n}=e,r=Ds(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function Ma(e){return e.children}function Fa(e){let t=j(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,_.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),c=Q(),l=(0,_.useRef)(null),d=F({queryKey:a,queryFn:()=>Rr(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let h=Y("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:a})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{h(),l.current&&clearTimeout(l.current)}},[s,o,n,a,c]);let p=d.data,f=p?.messages??[],m=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:f,messageCards:m,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(h=>h.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function qa(e){j();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,a=i&&!!t,c=On({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>Fn(t,{parentMessageId:n,limit:r,before_seq:o?void 0:h,after_seq:o?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!o||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>o||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:a}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let h=new Set,g=[];for(let S of c.data.pages)for(let T of S.messages)h.has(T.id)||(h.add(T.id),g.push(T));return g.sort((S,T)=>S.seq-T.seq)},[c.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let h=new Map,g=[];if(!c.data?.pages)return{messageCards:h,siblingCards:g};let S=new Set;for(let T of c.data.pages){for(let[E,U]of T.messageCards)for(let V of U){if(S.has(V.id))continue;S.add(V.id);let B=h.get(E)||[];B.push(V),h.set(E,B)}for(let E of T.siblingCards)S.has(E.id)||(S.add(E.id),g.push(E))}return{messageCards:h,siblingCards:g}},[c.data?.pages]),f=Q(),m=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!a)return;let h=Y("vfs_change",()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(async()=>{let g=f.getQueryData(y);if(!g?.pages?.length){f.invalidateQueries({queryKey:y});return}let S=0;for(let T of g.pages)for(let E of T.messages)E.seq>S&&(S=E.seq);if(S===0){f.invalidateQueries({queryKey:y});return}try{let T=await Fn(t,{parentMessageId:n,limit:r,after_seq:S});if(T.messages.length===0&&T.siblingCards.length===0){f.invalidateQueries({queryKey:y});return}if(T.messages.length>0){let E=Math.min(...T.messages.map(U=>U.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),f.invalidateQueries({queryKey:y});return}}f.setQueryData(y,E=>{if(!E)return E;let U=[...E.pages],V=U.length-1,B=U[V],_t=new Set(B.messages.map(A=>A.id)),re=T.messages.filter(A=>!_t.has(A.id)),N=[...B.messages,...re].sort((A,nt)=>A.seq-nt.seq),X=new Map(B.messageCards);for(let[A,nt]of T.messageCards){let G=X.get(A)||[],rn=new Set(G.map(Qr=>Qr.id)),oc=nt.filter(Qr=>!rn.has(Qr.id));X.set(A,[...G,...oc])}let ye=new Set(B.siblingCards.map(A=>A.id)),_e=T.siblingCards.filter(A=>!ye.has(A.id)),ve=[...B.siblingCards,..._e];return U[V]={...B,messages:N,messageCards:X,siblingCards:ve},{...E,pages:U}})}catch(T){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",T),f.invalidateQueries({queryKey:y})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{h(),m.current&&clearTimeout(m.current)}},[s,t,a,y,f,n,r]),{messages:l,messageCards:d,siblingCards:p,threads:l.filter(h=>h.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 cu(e){return e==="on"||e==="auto"?"on":"off"}function uu(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:cu(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 qr(e={}){let t=j(),{realtime:n=!0,enabled:r=!0}=e,s=Q(),i=(0,_.useRef)(null),o=(0,_.useMemo)(()=>w.channels("all"),[t]),a=F({queryKey:o,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(uu),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=Y("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),d=Y("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:o})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,o,s]),{channels:a.data??[],isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Da(e={}){let t=qr(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Ua(e={}){let t=qr(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Us(e={}){let t=j(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=Q(),a=(0,_.useRef)(null),c=(0,_.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:c,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>Y(f,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},m=>m.item_type==="notification"||m.item_type==="message"));return()=>{p.forEach(f=>f()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Qa(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Us({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let m=new Map;for(let y of s)y.is_unread&&y.channel_id&&m.set(y.channel_id,(m.get(y.channel_id)||0)+1);return m},[s]),d=(0,_.useMemo)(()=>{let m=0;return l.forEach(y=>{m+=y}),m},[l]),{dmUnread:p,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let m=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,h=0;return l.forEach((g,S)=>{m.has(S)?y+=g:h+=g}),{dmUnread:y,channelUnread:h}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:f,isLoading:i,isFetching:o,error:a,refetch:c}}function Na(){let e=Q();return Qe({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function Ka(){let e=Q();return Qe({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 La(){return Qe({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},au()}})}function ja(){let e=Q();return Qe({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 Va(){let e=Q();return Qe({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 o=i.join("/");o&&e.invalidateQueries({queryKey:w.children(o)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function Ha(){let e=Q();return Qe({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 $a(e,t){let n=Q(),{optimistic:r,...s}=t??{};return Qe({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Wa(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,o=l.enabled??!0}let a=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>o?Y(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function Ba(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=Q(),c=(0,_.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=Y(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:t})},o)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Ga(e){j();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,o=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),a=i?.resolution_level??null,c=(0,_.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),l=(0,_.useCallback)(d=>{if(!c||!d?.length)return d??[];let p=h=>h.id??h.name??"",f=new Map(c.map((h,g)=>[h,g])),m=[],y=[];for(let h of d)(f.has(p(h))?m:y).push(h);return m.sort((h,g)=>f.get(p(h))-f.get(p(g))),[...m,...y]},[c]);return{...s,arrangement:i,resolvedChildren:o,resolutionLevel:a,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function lu(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function du(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function fu(e,t){return!(e==="object"||e==="array")}function pu(e){return["string","number","integer","boolean"].includes(e)}function mu(e){return e!=="object"&&e!=="array"}function za(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",l=a.enum,d=fu(c,l),p=pu(c),f=du(c,l);i.push({key:o,label:a.title||lu(o),type:c,description:a.description,enum_values:l,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:p,filter_widget:f})}return i}function Qs(e){let t=e.default_data||{},n=e.field_defaults||{},r=za(e.input_schema,!0,t,n),s=za(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>mu(l.type)),a=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Ja(e){return{field:"updated_at",direction:"desc"}}function Ya(e){let t=Qs(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=H(ie(),1);var hu=0;function gu(){return`upload_${Date.now()}_${++hu}`}async function Xa(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",a={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(a.card_parent_path=t.cardParentPath);let l=await R("create",a);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let f=l.storage_key,m=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 yu(y,f,m,e,i,n,r);let h=await Za(d,f,i);return{itemId:d,itemPath:p,fileRef:h}}function yu(e,t,n,r,s,i,o){return new Promise((a,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?a():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")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{l.abort(),c(new Error("Upload cancelled"))})}l.send(r)})}async function Za(e,t,n){let r=await Ie(),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 o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.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 ec(){let[e,t]=(0,ne.useState)([]),n=Q(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((h,g)=>{t(S=>S.map(T=>T.id===h?{...T,...g}:T))},[]),i=(0,ne.useCallback)(h=>{t(g=>[...g,h])},[]),o=(0,ne.useCallback)(async(h,g,S,T,E)=>{let U=S.name||g.name,V=g.type||"application/octet-stream",B=S.itemType||"file",_t=E?.itemId||null,re=E?.itemPath||null,N=E?.storageKey||null,X=E?.uploadToken||null,ye=E?.storageWorkerUrl||null;try{if(!T||T==="create"){s(h,{status:"creating",error:null,_failedAt:null});let A=await R("create",{parent_path:S.parentPath,item_type:B,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:V}}});if(!A.id)throw Object.assign(new Error(A.error||A.message||"Failed to create file item"),{_step:"create"});if(_t=A.id,re=A.path,s(h,{itemId:_t,itemPath:re}),A.storage_completed&&A.file_ref){s(h,{status:"complete",progress:100,fileRef:A.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(N=A.storage_key,X=A.upload_token||"",ye=A.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:N,_uploadToken:X,_storageWorkerUrl:ye}),!N)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!T||T==="create"||T==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((A,nt)=>{let G=new XMLHttpRequest;s(h,{_xhr:G}),G.open("PUT",`${ye}/upload`),G.setRequestHeader("X-Storage-Key",N),G.setRequestHeader("Content-Type",V),X&&G.setRequestHeader("X-Upload-Token",X),G.upload.onprogress=rn=>{rn.lengthComputable&&s(h,{progress:Math.round(rn.loaded/rn.total*100)})},G.onload=()=>{G.status>=200&&G.status<300?A():nt(Object.assign(new Error(`Storage upload failed: HTTP ${G.status}`),{_step:"upload"}))},G.onerror=()=>nt(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),G.ontimeout=()=>nt(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),G.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let _e=await Za(_t,N,V);s(h,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),A=_e?._step||"create";s(h,{status:"error",error:ve,_failedAt:A,_xhr:null})}},[s,n]),a=(0,ne.useCallback)((h,g)=>{let S=gu();i({id:S,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(S,h,g)},[i,o]),c=(0,ne.useCallback)((h,g)=>{for(let S of h)a(S,g)},[a]),l=(0,ne.useCallback)(h=>{let g=r.current.find(E=>E.id===h);if(!g||g.status!=="error")return;let S=g._failedAt||"create",T=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;o(h,g.file,g.options,S,T)},[o]),d=(0,ne.useCallback)(h=>{let g=r.current.find(S=>S.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ne.useCallback)(h=>{t(g=>g.filter(S=>S.id!==h))},[]),f=(0,ne.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),m=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),y=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:S,_xhr:T,_failedAt:E,...U})=>U);return{upload:a,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:f,isUploading:m}}var tc=H(ie(),1);async function Ns(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function nc(e,t){return(0,tc.useSyncExternalStore)(it,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ns(e,t),enabled:!!(e&&t)})}var ge=H(ie(),1);function Dr(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(o.artifact_id)c=o;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 p=r.get(c.tool_id);n.timeline[p].artifact_ids.push(c.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,p)}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 p=r.get(c.tool_id);if(p!==void 0){let f=n.timeline[p];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return Er(e,s)}function rc(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),o=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:Dr(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let a=(0,ge.useCallback)(()=>{r(new Map),i([]),o.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:a}}function sc(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:Dr(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Ur=H(ie(),1);function _u(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Ks(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 a=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(vu).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function ic(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=Q(),l=(0,Ur.useRef)(null),d=a?_u(a,n,r,s):["vfs","timeline-history","__disabled__"],p=F({queryKey:d,queryFn:()=>Ks(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Ur.useEffect)(()=>{if(!a||!i)return;let f=Y("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},m=>{let y=m?.path;return y?y===a||y.startsWith(a+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[a,i,o,c,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function vu(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}}Ta(Ls);return mc(Ls);})();
4
4
 
5
5
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
6
6
  (function() {