@ai4b-team/fsaos-gateway-sdk 3.29.0 → 3.30.1

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