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