@ai4b-team/fsaos-gateway-sdk 3.27.0 → 3.28.0

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