@ai4b-team/fsaos-gateway-sdk 3.40.0 → 3.42.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/README.md +2 -2
- package/dist/iife/gateway.js +4 -4
- package/dist/iife/gateway.js.map +3 -3
- package/dist/iife/ui.js +1 -1
- package/dist/index.cjs +82 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -3
- package/dist/index.d.ts +26 -3
- package/dist/index.js +82 -12
- 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 ju=Object.create;var Fn=Object.defineProperty;var $u=Object.getOwnPropertyDescriptor;var Vu=Object.getOwnPropertyNames;var Wu=Object.getPrototypeOf,Bu=Object.prototype.hasOwnProperty;var Ui=e=>{throw TypeError(e)};var Hu=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gu=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Ni=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vu(t))!Bu.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=$u(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?ju(Wu(e)):{},Ni(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),zu=e=>Ni(Fn({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>Hu(e,typeof t!="symbol"?t+"":t,n),Ps=(e,t,n)=>t.has(e)||Ui("Cannot "+n);var l=(e,t,n)=>(Ps(e,t,"read from private field"),n?n.call(e):t.get(e)),x=(e,t,n)=>t.has(e)?Ui("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,r)=>(Ps(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),M=(e,t,n)=>(Ps(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){b(e,t,s,n)},get _(){return l(e,t,r)}});var oe=qn((fd,Ki)=>{Ki.exports=React});var Ir=qn((lp,wo)=>{wo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Fo=qn((Lp,Oo)=>{Oo.exports={createClient:window.supabase.createClient}});var ia=qn((em,sa)=>{sa.exports=ReactDOM});var lu=qn((Gh,uu)=>{uu.exports=ReactDOM});var Qi={};Gu(Qi,{ComponentRenderer:()=>Ac,EnforcementDeniedError:()=>nt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>kc,QueryClientProvider:()=>Gn,assignPersonalSection:()=>qu,auth:()=>bu,awaitAnchorReady:()=>er,awaitScopeReady:()=>$o,callTool:()=>yu,cancelQueuedTurn:()=>au,cancelTurn:()=>iu,clearCachedToken:()=>Zs,clearSession:()=>oi,configureGatewayReads:()=>Zo,createItem:()=>mu,disconnectSSE:()=>gi,disposeVfsRealtimeWs:()=>_i,electHomeAnchor:()=>kt,emitEvent:()=>Ca,fetchChannelMessages:()=>qa,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Mi,fetchTimelineHistory:()=>Oi,fetchTurnQueueEntries:()=>Ma,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>C,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ni,getAssetUrl:()=>vu,getDefaultSort:()=>xu,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Ta,getQueryClient:()=>A,getRequiredFormFields:()=>Cu,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>Go,getServerClockSyncedAt:()=>zo,getSessionEntry:()=>Mt,hasServerClock:()=>Ho,initSession:()=>mt,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>su,initializeWorkspace:()=>vs,interpretSchema:()=>ki,invalidateAllVfs:()=>Ua,invalidateChannelMessages:()=>Ka,invalidateChildren:()=>Yr,invalidateItem:()=>yi,invalidateOpenEnvelope:()=>La,invalidatePathAndParent:()=>Qa,invalidateSubtree:()=>Da,invalidateTypes:()=>Na,isAnchorReady:()=>si,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Oa,listChildren:()=>pu,loadMounts:()=>Dt,mount:()=>wu,mountRealtimeScope:()=>Pn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>pi,personalSectionsKey:()=>vr,ping:()=>Pa,pushChanges:()=>gu,queryClient:()=>fa,readItem:()=>fu,refreshQuery:()=>Ae,registerCleanup:()=>te,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Tc,resubscribePath:()=>Ia,selectMount:()=>mr,serverDeadlinePassed:()=>Jo,serverMsUntil:()=>Yo,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>Do,setQueryClient:()=>da,setScope:()=>jo,setupRequireShim:()=>Su,signal:()=>_u,startTracking:()=>_s,steerTurn:()=>ou,submitForm:()=>cu,subscribeAnchor:()=>ri,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>ne,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>tu,trackEvent:()=>Nt,trackPageView:()=>eu,unmountRealtimeScope:()=>ls,updateItem:()=>hu,uploadFile:()=>Pu,useAccounts:()=>_c,useAgentTimeline:()=>Mu,useAllChannels:()=>gs,useArrangement:()=>In,useArtifactStream:()=>ku,useAsset:()=>bc,useAuth:()=>hs,useChannelMessages:()=>Mc,useChannels:()=>Fc,useChildren:()=>nc,useComponent:()=>xi,useCreate:()=>Dc,useDelete:()=>Kc,useDmChannels:()=>qc,useEdges:()=>uc,useEventStream:()=>Vc,useFileUpload:()=>Eu,useIncrementalItems:()=>ac,useInfiniteChannelMessages:()=>Oc,useInfiniteChildren:()=>cc,useInfiniteItems:()=>Ri,useItem:()=>ec,useItemById:()=>tc,useItemHistory:()=>hc,useItemVersions:()=>mc,useItems:()=>oc,useLink:()=>jc,useList:()=>Si,useMemberFocus:()=>pc,useMintedAsset:()=>Bc,useMounts:()=>vc,useMove:()=>Lc,useMutation:()=>$c,useNotifications:()=>Ci,useOpen:()=>dc,usePermission:()=>xc,usePermissions:()=>Cc,usePersonalItemOrder:()=>Gc,usePersonalSections:()=>Du,usePinnedItems:()=>Fu,usePrincipal:()=>Ec,useRealtimeQuery:()=>Wc,useRecentActivity:()=>gc,useResolve:()=>ic,useResolvedItems:()=>Au,useScope:()=>yc,useScopeReady:()=>Za,useSearch:()=>sc,useTheme:()=>Rc,useTimelineHistory:()=>Ou,useTool:()=>Ic,useTree:()=>rc,useType:()=>lc,useTypeHelpers:()=>fc,useTypes:()=>ms,useUnreadCounts:()=>Qc,useUpdate:()=>Uc,useUpdatePrincipal:()=>Nc,vfsKeys:()=>P,waitForPathReady:()=>Ea});var nt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);ee(this,"name","EnforcementDeniedError");ee(this,"deniedBy");ee(this,"ruleKey");ee(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 An=X(oe(),1);var xe=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 vt,rt,Lt,Li,Ju=(Li=class extends xe{constructor(){super();x(this,vt);x(this,rt);x(this,Lt);b(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,rt)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,rt))==null||t.call(this),b(this,rt,void 0))}setEventListener(t){var n;b(this,Lt,t),(n=l(this,rt))==null||n.call(this),b(this,rt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,vt)!==t&&(b(this,vt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,vt)=="boolean"?l(this,vt):globalThis.document?.visibilityState!=="hidden"}},vt=new WeakMap,rt=new WeakMap,Lt=new WeakMap,Li),jt=new Ju;var Yu={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},st,Ts,ji,Xu=(ji=class{constructor(){x(this,st,Yu);x(this,Ts,!1)}setTimeoutProvider(e){b(this,st,e)}setTimeout(e,t){return l(this,st).setTimeout(e,t)}clearTimeout(e){l(this,st).clearTimeout(e)}setInterval(e,t){return l(this,st).setInterval(e,t)}clearInterval(e){l(this,st).clearInterval(e)}},st=new WeakMap,Ts=new WeakMap,ji),Qe=new Xu;function $i(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Bi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!bt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!bt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function bt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>bt(e[n],t[n])):!1}var Zu=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Vi(e)&&Vi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:Zu.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=As(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function $t(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 Vi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Wi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Wi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Wi(e){return Object.prototype.toString.call(e)==="[object Object]"}function Hi(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function Gi(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function zi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Vt=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Vt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function Ji(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){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 Yi=$i;function el(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Yi,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var j=el();var Bt,it,Ht,Xi,tl=(Xi=class extends xe{constructor(){super();x(this,Bt,!0);x(this,it);x(this,Ht);b(this,Ht,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(){l(this,it)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,it))==null||t.call(this),b(this,it,void 0))}setEventListener(t){var n;b(this,Ht,t),(n=l(this,it))==null||n.call(this),b(this,it,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(b(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,it=new WeakMap,Ht=new WeakMap,Xi),Gt=new tl;function nl(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new xr(g);m(h),e.onCancel?.(h)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},f=()=>new Promise(g=>{r=h=>{(i()||u())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(_){g=Promise.reject(_)}Promise.resolve(g).then(p).catch(_=>{if(i())return;let w=e.retry??(Ue.isServer()?0:3),q=e.retryDelay??nl,O=typeof q=="function"?q(n,_):q,R=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,_);if(t||!R){m(_);return}n++,e.onFail?.(n,_),Hi(O).then(()=>u()?void 0:f()).then(()=>{t?m(_):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var wt,Zi,Pr=(Zi=class{constructor(){x(this,wt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&b(this,wt,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,wt)!==void 0&&(Qe.clearTimeout(l(this,wt)),b(this,wt,void 0))}},wt=new WeakMap,Zi);var St,zt,Ce,Rt,re,Ln,xt,be,so,Ve,no,ro=(no=class extends Pr{constructor(t){super();x(this,be);x(this,St);x(this,zt);x(this,Ce);x(this,Rt);x(this,re);x(this,Ln);x(this,xt);b(this,xt,!1),b(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],b(this,Rt,t.client),b(this,Ce,l(this,Rt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,b(this,St,to(this.options)),this.state=t.state??l(this,St),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,re)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=to(this.options);n.data!==void 0&&(this.setState(eo(n.data,n.dataUpdatedAt)),b(this,St,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return M(this,be,Ve).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){M(this,be,Ve).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,re)?.promise;return l(this,re)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,St)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Vt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(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:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,re)&&(l(this,xt)||M(this,be,so).call(this)?l(this,re).cancel({revert:!0}):l(this,re).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||M(this,be,Ve).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,re)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,re))return l(this,re).continueRetry(),l(this,re).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(b(this,xt,!0),r.signal)})},i=()=>{let a=Rr(this.options,n),d=(()=>{let p={client:l(this,Rt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return b(this,xt,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,Rt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),b(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&M(this,be,Ve).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),b(this,re,Cr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof xr&&a.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{M(this,be,Ve).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{M(this,be,Ve).call(this,{type:"pause"})},onContinue:()=>{M(this,be,Ve).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,re).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,Ce).config.onSuccess?.(a,this),l(this,Ce).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof xr){if(a.silent)return l(this,re).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw M(this,be,Ve).call(this,{type:"error",error:a}),l(this,Ce).config.onError?.(a,this),l(this,Ce).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},St=new WeakMap,zt=new WeakMap,Ce=new WeakMap,Rt=new WeakMap,re=new WeakMap,Ln=new WeakMap,xt=new WeakMap,be=new WeakSet,so=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ve=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,...eo(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return b(this,zt,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),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},no);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function eo(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function to(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 he,N,$n,le,Ct,Jt,We,ot,Vn,Yt,Xt,Pt,Tt,at,Zt,L,jn,Os,Fs,qs,Qs,Ds,Us,Ns,co,ao,Wn=(ao=class extends xe{constructor(t,n){super();x(this,L);x(this,he);x(this,N);x(this,$n);x(this,le);x(this,Ct);x(this,Jt);x(this,We);x(this,ot);x(this,Vn);x(this,Yt);x(this,Xt);x(this,Pt);x(this,Tt);x(this,at);x(this,Zt,new Set);this.options=n,b(this,he,t),b(this,ot,null),b(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,N).addObserver(this),io(l(this,N),this.options)?M(this,L,jn).call(this):this.updateResult(),M(this,L,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,N),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,N),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,M(this,L,Ds).call(this),M(this,L,Us).call(this),l(this,N).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,N);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,N))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");M(this,L,Ns).call(this),l(this,N).setOptions(this.options),n._defaulted&&!$t(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,N),observer:this});let s=this.hasListeners();s&&oo(l(this,N),r,this.options,n)&&M(this,L,jn).call(this),this.updateResult(),s&&(l(this,N)!==r||me(this.options.enabled,l(this,N))!==me(n.enabled,l(this,N))||Me(this.options.staleTime,l(this,N))!==Me(n.staleTime,l(this,N)))&&M(this,L,Os).call(this);let i=M(this,L,Fs).call(this);s&&(l(this,N)!==r||me(this.options.enabled,l(this,N))!==me(n.enabled,l(this,N))||i!==l(this,at))&&M(this,L,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return sl(this,r)&&(b(this,le,r),b(this,Jt,this.options),b(this,Ct,l(this,N).state)),r}getCurrentResult(){return l(this,le)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,N)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return M(this,L,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,le)))}createResult(t,n){let r=l(this,N),s=this.options,i=l(this,le),o=l(this,Ct),c=l(this,Jt),u=t!==r?t.state:l(this,$n),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),k=!T&&io(t,n),I=T&&oo(t,r,n,s);(k||I)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=p;f=p.data;let _=!1;if(n.placeholderData!==void 0&&f===void 0&&h==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,_=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,T!==void 0&&(h="success",f=Nn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!_)if(i&&f===o?.data&&n.select===l(this,Vn))f=l(this,Yt);else try{b(this,Vn,n.select),f=n.select(f),f=Nn(i?.data,f,n),b(this,Yt,f),b(this,ot,null)}catch(T){b(this,ot,T)}l(this,ot)&&(y=l(this,ot),f=l(this,Yt),g=Date.now(),h="error");let w=p.fetchStatus==="fetching",q=h==="pending",O=h==="error",R=q&&w,F=f!==void 0,S={status:h,fetchStatus:p.fetchStatus,isPending:q,isSuccess:h==="success",isError:O,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!q,isLoadingError:O&&!F,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:O&&F,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=S.data!==void 0,k=S.status==="error"&&!T,I=D=>{k?D.reject(S.error):T&&D.resolve(S.data)},E=()=>{let D=b(this,We,S.promise=Kn());I(D)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&I(U);break;case"fulfilled":(k||S.data!==U.value)&&E();break;case"rejected":(!k||S.error!==U.reason)&&E();break}}return S}updateResult(){let t=l(this,le),n=this.createResult(l(this,N),this.options);if(b(this,Ct,l(this,N).state),b(this,Jt,this.options),l(this,Ct).data!==void 0&&b(this,Xt,l(this,N)),$t(n,t))return;b(this,le,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,le)).some(c=>{let a=c;return l(this,le)[a]!==t[a]&&o.has(a)})};M(this,L,co).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&M(this,L,Qs).call(this)}},he=new WeakMap,N=new WeakMap,$n=new WeakMap,le=new WeakMap,Ct=new WeakMap,Jt=new WeakMap,We=new WeakMap,ot=new WeakMap,Vn=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Pt=new WeakMap,Tt=new WeakMap,at=new WeakMap,Zt=new WeakMap,L=new WeakSet,jn=function(t){M(this,L,Ns).call(this);let n=l(this,N).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){M(this,L,Ds).call(this);let t=Me(this.options.staleTime,l(this,N));if(Ue.isServer()||l(this,le).isStale||!Dn(t))return;let r=br(l(this,le).dataUpdatedAt,t)+1;b(this,Pt,Qe.setTimeout(()=>{l(this,le).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,N)):this.options.refetchInterval)??!1},qs=function(t){M(this,L,Us).call(this),b(this,at,t),!(Ue.isServer()||me(this.options.enabled,l(this,N))===!1||!Dn(l(this,at))||l(this,at)===0)&&b(this,Tt,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&M(this,L,jn).call(this)},l(this,at)))},Qs=function(){M(this,L,Os).call(this),M(this,L,qs).call(this,M(this,L,Fs).call(this))},Ds=function(){l(this,Pt)!==void 0&&(Qe.clearTimeout(l(this,Pt)),b(this,Pt,void 0))},Us=function(){l(this,Tt)!==void 0&&(Qe.clearInterval(l(this,Tt)),b(this,Tt,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,N))return;let n=l(this,N);b(this,N,t),b(this,$n,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},co=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,le))}),l(this,he).getQueryCache().notify({query:l(this,N),type:"observerResultsUpdated"})})},ao);function rl(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function io(e,t){return rl(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function oo(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function sl(e,t){return!$t(e.getCurrentResult(),t)}function en(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||[],c={pages:[],pageParams:[]},a=0,u=async()=>{let d=!1,p=y=>{Ji(y,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),f=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let w=(()=>{let F={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return p(F),F})(),q=await m(w),{maxPages:O}=t.options,R=h?zi:Gi;return{pages:R(y.pages,q,O),pageParams:R(y.pageParams,g,O)}};if(s&&i.length){let y=s==="backward",g=y?uo:js,h={pages:i,pageParams:o},_=g(r,h);c=await f(h,_,y)}else{let y=e??i.length;do{let g=a===0?o[0]??r.initialPageParam:js(r,c);if(a>0&&g==null)break;c=await f(c,g),a++}while(a<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function js(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 uo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function lo(e,t){return t?js(e,t)!=null:!1}function fo(e,t){return!t||!e.getPreviousPageParam?!1:uo(e,t)!=null}var $s=class extends Wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:en()})}getOptimisticResult(e){return e.behavior=en(),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:c}=r,a=n.fetchMeta?.fetchMore?.direction,u=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:lo(t,n.data),hasPreviousPage:fo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var Bn,Ne,ae,Et,Ke,ct,po,mo=(po=class extends Pr{constructor(t){super();x(this,Ke);x(this,Bn);x(this,Ne);x(this,ae);x(this,Et);b(this,Bn,t.client),this.mutationId=t.mutationId,b(this,ae,t.mutationCache),b(this,Ne,[]),this.state=t.state||Vs(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){b(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ae).remove(this))}continue(){return l(this,Et)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{M(this,Ke,ct).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};b(this,Et,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{M(this,Ke,ct).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{M(this,Ke,ct).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ae).canRun(this)}));let s=this.state.status==="pending",i=!l(this,Et).canStart();try{if(s)n();else{M(this,Ke,ct).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ae).config.onMutate&&await l(this,ae).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&M(this,Ke,ct).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,Et).start();return await l(this,ae).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ae).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),M(this,Ke,ct).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ae).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await l(this,ae).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw M(this,Ke,ct).call(this,{type:"error",error:o}),o}finally{l(this,ae).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ae=new WeakMap,Et=new WeakMap,Ke=new WeakSet,ct=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),j.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ae).notify({mutation:this,type:"updated",action:t})})},po);function Vs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,ho,go=(ho=class extends xe{constructor(t={}){super();x(this,Be);x(this,Oe);x(this,Hn);this.config=t,b(this,Be,new Set),b(this,Oe,new Map),b(this,Hn,0)}build(t,n,r){let s=new mo({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,ho);function Tr(e){return e.options.scope?.id}var He,ut,ge,Ge,ze,Er,Ws,yo,Bs=(yo=class extends xe{constructor(t,n){super();x(this,ze);x(this,He);x(this,ut);x(this,ge);x(this,Ge);b(this,He,t),this.setOptions(n),this.bindMethods(),M(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),$t(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){M(this,ze,Er).call(this),M(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,ut)}reset(){l(this,ge)?.removeObserver(this),b(this,ge,void 0),M(this,ze,Er).call(this),M(this,ze,Ws).call(this)}mutate(t,n){return b(this,Ge,n),l(this,ge)?.removeObserver(this),b(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,ut=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??Vs();b(this,ut,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){j.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,ut).variables,r=l(this,ut).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,ut))})})},yo);var Le,_o,vo=(_o=class extends xe{constructor(t={}){super();x(this,Le);this.config=t,b(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(s,n),o=this.get(i);return o||(o=new ro({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,_o);var z,lt,dt,tn,nn,ft,rn,sn,bo,Hs=(bo=class{constructor(e={}){x(this,z);x(this,lt);x(this,dt);x(this,tn);x(this,nn);x(this,ft);x(this,rn);x(this,sn);b(this,z,e.queryCache||new vo),b(this,lt,e.mutationCache||new go),b(this,dt,e.defaultOptions||{}),b(this,tn,new Map),b(this,nn,new Map),b(this,ft,0)}mount(){Qn(this,ft)._++,l(this,ft)===1&&(b(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),b(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,ft)._--,l(this,ft)===0&&((e=l(this,rn))==null||e.call(this),b(this,rn,void 0),(t=l(this,sn))==null||t.call(this),b(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,lt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).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=l(this,z).get(r.queryHash)?.state.data,o=Bi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return j.batch(()=>(l(this,z).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=j.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,lt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,lt)}getDefaultOptions(){return l(this,dt)}setDefaultOptions(e){b(this,dt,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{bt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{bt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,dt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(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===Vt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,dt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,lt).clear()}},z=new WeakMap,lt=new WeakMap,dt=new WeakMap,tn=new WeakMap,nn=new WeakMap,ft=new WeakMap,rn=new WeakMap,sn=new WeakMap,bo);var on=X(oe(),1),So=X(Ir(),1),Gs=on.createContext(void 0),V=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,So.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(oe(),1),Ro=Ar.createContext(!1),xo=()=>Ar.useContext(Ro),fp=Ro.Provider;var zn=X(oe(),1),il=X(Ir(),1);function ol(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var al=zn.createContext(ol()),Co=()=>zn.useContext(al);var Po=X(oe(),1);var To=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Eo=e=>{Po.useEffect(()=>{e.clearReset()},[e])},Io=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Ao=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ko=(e,t)=>e.isLoading&&e.isFetching&&!t,Mo=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var pt=X(oe(),1);function kr(e,t,n){let r=xo(),s=Co(),i=V(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Ao(o),To(o,s,c),Eo(s);let a=!i.getQueryCache().get(o.queryHash),[u]=pt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(pt.useSyncExternalStore(pt.useCallback(m=>{let f=p?u.subscribe(j.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),pt.useEffect(()=>{u.setOptions(o)},[o,u]),Mo(o,d))throw zs(o,u,s);if(Io({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&ko(d,r)&&(a?zs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return kr(e,Wn,t)}var Je=X(oe(),1);function de(e,t){let n=V(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,$s,t)}var qo=X(Fo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},It=Array.isArray(Yn.sources)?Yn.sources:[],cl=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",ul=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Pe=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,qo.createClient)(cl,ul,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Qo,Xs,Or=!1;Qo=new Promise(e=>{Xs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Xs())});setTimeout(()=>{Or||(Or=!0,Xs())},5e3);function Do(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function Zs(){Xn=null,Mr=0}async function Ye(){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 Qo,Xn}var ln=null,dn=null,Uo=0,Js=new Set,ei,Zn,fn=!1;ei=new Promise(e=>{Zn=e});function ti(){Uo++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!At.some(r=>r.id===e.id)&&(At=[...At,e],ii()),fn||(fn=!0,Zn()),n&&ti()}function pn(){return ln}function ye(){return dn}function ni(){return Uo}function ri(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ei}function si(){return fn}var Fr=null;function kt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var At=[],Ys=new Set,No=0;function ii(){No++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return At}function tr(){return No}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function Ko(e,t){let n=JSON.stringify(At)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;At=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&ii(),r&&ti()}var cn=null,an=null,un=0;function se(){return un}async function mt(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Pe}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},cn})().catch(t=>{throw e===un&&(an=null),t}),an}function Mt(){return cn}function oi(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,At=[]}var Lo=[];function te(e){Lo.push(e)}function mn(){oi(),Zs(),Zn(),fn=!1,ei=new Promise(e=>{Zn=e}),ti(),ii();for(let e of Lo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var jo=qr,H=pn,Z=ni,we=ri,$o=er,Dr=si;var ai=0,Vo=!1,Wo=0;function Bo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ai=t-Date.now(),Vo=!0,Wo=Date.now())}function Ur(){return Date.now()+ai}function Ho(){return Vo}function Go(){return ai}function zo(){return Wo}function Jo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function Yo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],ci=0,ui={foreground:0,normal:1,background:2},Nr=()=>performance.now(),li=()=>new DOMException("Read cancelled","AbortError");function Zo(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function ea(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(li());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function ta(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function na(e,t,n,r){if(n.signal?.aborted)return Promise.reject(li());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)ui[n.priority??"normal"]<ui[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let c=s;s.timer=setTimeout(()=>{c.controller.abort();let a=new Error("The read timed out. Please retry.");a.name="TimeoutError";for(let u of c.consumers)u.detach(),u.reject(a);c.consumers.clear(),Ee.get(c.key)===c&&Ee.delete(c.key),Xo(c)},hn.timeoutMs)}let i=s,o=new Promise((c,a)=>{let u=()=>{d.detach(),i.consumers.delete(d),a(li()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),Xo(i))},d={resolve:p=>c(structuredClone(p)),reject:a,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function Xo(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;ci<hn.concurrency&&Ft.length;){let e=r=>ui[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;ci++,t.startedAt=Nr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ee.get(t.key)===t&&Ee.delete(t.key),ci--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}te(ea);var ll=new Set(["list-memberships","init"]),Ie=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);ee(this,"name","GatewayRequestError");ee(this,"method");ee(this,"status");ee(this,"statusText");ee(this,"payload");ee(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){let r=se(),s=pn(),i=Ot(),o=`${Pe}/d/${i}`,c={"Content-Type":"application/json"},a=await ra(Ye(),n.signal);if(r!==se())throw new Error("Session changed before gateway request");if(a&&(c.Authorization=`Bearer ${a}`),!ll.has(e)&&!t._scope_path&&await ra(er(),n.signal),r!==se())throw new Error("Session changed before gateway request");let u={...t},d=Mt();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let m=async f=>{if(r!==se())throw new Error("Session changed before queued gateway request");let y=await fetch(o,{method:"POST",signal:f,headers:c,body:JSON.stringify({method:e,params:u})}),g=await y.text();if(r!==se())throw new Error("Session changed during gateway request");let h=null;if(g)try{h=JSON.parse(g)}catch{}if(!y.ok||!h)throw new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g});if(h.success===!1){let _=h.error||"",w=h.denied_by||h.error_type||"";throw w==="rule"||w==="access"||w==="entitlement"||_==="RULE_DENIED"||_==="ACCESS_DENIED"||_==="PERMISSION_DENIED"||_==="ENTITLEMENT_REQUIRED"?new nt(h):new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g})}return h&&h.server_now!==void 0&&Bo(h.server_now),h};return ta(e,u)?na(Kr([r,i,a,e,u]),e,n,m):m(n.signal)}function ra(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var v=X(oe(),1),Ol=X(ia(),1),Fl=X(Ir(),1);var oa=new WeakMap;function Ae(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)}`,c=oa.get(e);c||(c=new Map,oa.set(e,c));let a=c.get(o);if(a)return a;let u=c,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,aa=e=>e.meta?.arrangementRealtime===!0;function Xe(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.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&&Ae(e,t,{exact:!0})},250))}function ca(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!aa(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Xe(e,n.queryKey);continue}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)))&&Xe(e,n.queryKey)}}function ua(e){for(let t of e.getQueryCache().getAll())aa(t)&&t.state.data!==void 0&&Xe(e,t.queryKey)}function la(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var Ze=null;te(()=>{Ze&&(Ze.cancelQueries({queryKey:["vfs"]}),Ze.removeQueries({queryKey:["vfs"]}))});function da(e){if(Ze&&Ze!==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.");Ze=e}function A(){return Ze||(Ze=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Ze}var fa=new Proxy({},{get(e,t,n){let r=A(),s=r[t];return typeof s=="function"?s.bind(r):s}});var $r=new WeakMap;function di(e){return e.meta?.infiniteItemsRealtime?.filter}function dl(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 fl(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function pl(e,t,n){if(dl(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=fl(t);return n.item_type&&o&&!o.has(n.item_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 pa(e,t){let n=$r.get(e);n||(n=new Map,$r.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||!di(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function ma(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=di(n);r&&pl(n,r,t)&&pa(e,n)}}function ha(e){for(let t of e.getQueryCache().getAll())di(t)&&t.state.data!==void 0&&pa(e,t)}function ga(e){$r.get(e)?.forEach(clearTimeout),$r.delete(e)}var Vr=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function ya(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new Vr}function ht(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function gn(e){return e instanceof Vr||e instanceof nt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ie(){return H()??"__unscoped__"}var P={all:()=>["vfs",ie()],item:e=>["vfs",ie(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ie(),"children",e],allChildren:()=>["vfs",ie(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ie(),"search",e,...t??[]],items:(e,t)=>["vfs",ie(),"items",e,JSON.stringify(ht(t??{}))],allItems:()=>["vfs",ie(),"items"],tree:(e,t)=>["vfs",ie(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ie(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ie(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ie(),"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",ie(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ie(),"channel-messages"],channels:e=>["vfs",ie(),"channels",e??"all"],allChannels:()=>["vfs",ie(),"channels"],notifications:(e,t)=>["vfs",ie(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ie(),"notifications"],unreadCounts:()=>["vfs",ie(),"unread-counts"],memberships:e=>["memberships",e]};var ml=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ml&&console.log("[WS]",...e)}var Q=null,yn=null,vn=null,nr=0,hl=3e4,_a=1e4,wn=!1,va=!1,xa=3e4,gl=xa*2+5e3,Wr=0,Br=null,ba=!1;function yl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-Wr>gl){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}tt({type:"ping"})},xa)}function sr(){Br&&(clearInterval(Br),Br=null)}function _l(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function vl(){ba||typeof document>"u"||(document.addEventListener("visibilitychange",_l),ba=!0)}var Se={};function pi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],et=new Map,_n=new Map,ke=new Map;function bl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function wa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Sa(e){let t=bl(e);if(t.length===0)return et.delete(e),null;let n={scope_id:e,event_types:t};return et.set(e,n),n}var je=new Map,gt=new Map,fi="disconnected",Hr=[];function Gr(e){if(fi!==e){fi=e;for(let t of[...Hr])try{t(e)}catch{}}}function wl(e){je.set(e,"ready");let t=gt.get(e);if(t){gt.delete(e);for(let n of t)n()}}function Sl(){for(let e of je.keys())je.set(e,"disconnected")}function mi(e,t){je.set(e,"pending"),tt({type:"subscribe_path",path:e,event_types:t})}function Rl(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return et.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Pe,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Ra();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),Gr("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((c,a)=>{if(!Q)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",_a,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}a(new Error("WebSocket connection timeout"))}},_a);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=va;va=!0,nr=0,Gr("connected"),xl(d),(typeof document>"u"||!document.hidden)&&yl(),vl(),c()},o.onmessage=d=>{Q===o&&Cl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),Q=null,sr(),Sl(),Gr("disconnected"),!wn&&rr()&&Ra(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Ra(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,hl);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function xl(e=!1){for(let t of et.values())J("resubscribeAll: scope",t.scope_id),tt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),mi(t.path,t.event_types);if(e)try{let t=A();ha(t),ua(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",ke.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function tt(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function Cl(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&wl(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"&&(ma(A(),r),ca(A(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&pi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function hi(){!Rl()&&et.size===0&&ke.size===0&&Q&&(wn=!0,sr(),Q.close(),Q=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?mi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),gt.delete(e),tt({type:"unsubscribe_path",path:e}))}hi()}}function ne(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}hi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=et.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Sa(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!wa(i,o.event_types)&&tt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let c=!0;return()=>{if(!c)return;c=!1;let a=_n.get(e);if(!a?.delete(n))return;let u=et.get(e)?.event_types;if(a.size===0)_n.delete(e),et.delete(e),tt({type:"unsubscribe",scope_id:e});else{let d=Sa(e);d&&Q&&Q.readyState===WebSocket.OPEN&&!wa(u,d.event_types)&&tt({type:"subscribe",scope_id:e,event_types:d.event_types})}hi()}}function Ca(e,t,n={}){tt({type:"emit",scope_id:e,event_type:t,payload:n})}function gi(){J("disconnectSSE: tearing down"),ga(A()),la(A()),wn=!0,sr(),Q&&(Q.close(),Q=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,et.clear(),_n.clear(),ke.clear(),je.clear(),gt.clear(),Gr("disconnected")}function Pa(){tt({type:"ping"})}function Ta(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Ea(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=gt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),gt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=gt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&>.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Ia(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),mi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(fi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}te(gi);function Aa(){return new Date().toISOString()}function ka(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Aa(),updated_at:e.updated_at||Aa(),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 or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&A().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&A().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await C("list",{path:e,limit:200}),n=or(t);for(let r of n)A().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Ma(e,t){let{items:n}=await xn({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 Zr(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)A().setQueryData(P.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 es(e){let n=await C("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function ts(e){try{let t=await C("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ka(),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||ka(),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 ns(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 C("tree",s),o=or(i);for(let c of o)A().setQueryData(P.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await C("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 ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await C("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 ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await C("member-focus",r),i=or(s);for(let o of i)A().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(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 C("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}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Pl(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Tl=["catalog","parent_only","internal"];function Oa(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?c[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(a[u.slice(9)]=d.filter(n));return{fields:c,field_in:a}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Tl.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,u={};typeof a.item_type=="string"&&a.item_type&&(u.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=ht(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),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);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(Pl)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&ya(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)A().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function El(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 Fa(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:El(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 ir(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 qa(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||[],o=ir(i),c=Fa(i),a=new Map,u=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:u,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 lr(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 C("get-channel-messages",n),i=s.messages||[],o=Fa(i),c=new Map,a=[];for(let u of o)if(u.parentMessagePath){let d=c.get(u.parentMessagePath)||[];d.push(u),c.set(u.parentMessagePath,d)}else a.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:a,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 Yr(e){A().invalidateQueries({queryKey:P.children(e)})}function yi(e){A().invalidateQueries({queryKey:P.item(e)})}function Qa(e,t){yi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function Da(e){let t=e+"/";A().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ua(){A().invalidateQueries({queryKey:P.all()})}function Na(e){A().invalidateQueries({queryKey:P.types(e)})}function Ka(e,t){e?A().invalidateQueries({queryKey:P.channelMessages(e,t)}):A().invalidateQueries({queryKey:P.allChannelMessages()})}function La(e,t){e&&t?A().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?A().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):A().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await C("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Cn=new Map,dr=null,us=null,yt=new Map,ja=250;function Qt(e){if(dr){Pn(e);return}Pn(e),dr=ne("vfs_change",t=>Il(t)),us=ne("ccm_change",t=>Al(t))}function Pn(e){if(Cn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Cn.set(e,t)}function ls(e){let t=Cn.get(e);t&&(t(),Cn.delete(e))}function _i(){for(let[,e]of Cn)e();Cn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),yt.forEach(e=>clearTimeout(e)),yt.clear()}te(_i);function Il(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=yt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{yt.delete(s),kl(n,t,e,s)},ja);yt.set(s,o)}function Al(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)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=yt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{yt.delete(s),t&&A().invalidateQueries({queryKey:P.edges(t)}),n&&A().invalidateQueries({queryKey:P.edges(n)})},ja);yt.set(s,o)}function kl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")A().removeQueries({queryKey:P.item(t)}),A().removeQueries({queryKey:P.children(t)}),A().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&A().setQueryData(P.item(t),o)}catch{}A().invalidateQueries({queryKey:P.children(r)}),A().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&A().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;te(()=>{Tn=null});function _t(e){if(e!==Tn||e.generation!==se())throw new Error("Workspace session changed")}function Ml(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function pr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function $a(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Va(e,t,n){_t(e);let r=$a(t,n);if(e.saved===r)return;let s=JSON.parse(r);await C(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),_t(e),e.exists=!0,e.saved=r}function Wa(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Pn(r.id);Ko(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return _t(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await C("read",{path:s,_scope_path:i.scope});if(_t(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(_t(i),!Ml(d))throw d;i.exists=!1}let c=n.initialAnchor?fr(i,n.initialAnchor):r,a=pr(o?o.mounts.map(t).filter(d=>d!==null):[c]),u=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=$a(a,u):n.initialAnchor&&await Va(i,a,u),_t(i),i.ready=!0,Wa(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{_t(t);let{refs:r,anchor:s}=e(t);await Va(t,r,s),_t(t),Wa(r,s)});return t.queue=n.catch(()=>{}),n}function vi(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function Ba(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function bi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var Ha=new WeakMap;function Ga(e,t,n){let r=Ha.get(e);r||(r=new Map,Ha.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,u=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||u||a||(a=setTimeout(()=>{a=void 0,g()},250))},g=async()=>{if(c)return;u=!0;let O=d;d=!1;let R=[...p],F=new Set(m);m.clear(),p.clear();try{if(O)await Ae(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async T=>{let k=e.getQueryCache().find({queryKey:t,exact:!0});if(!k)return;let I=await C("read",{id:T});if(I.success===!1)throw new Error("Channel refresh failed");if(c||!k||e.getQueryCache().find({queryKey:t,exact:!0})!==k)return;let E=_e(I.item??I);if(E.id!==T||E.item_type!=="channel")return;let U=f().find(B=>B.id===T);if(!U)return;let D=n({...E}),ue={...U,path:D.path,name:D.name,displayName:D.displayName,messageCount:D.messageCount,aiMode:D.aiMode,isPrivate:D.isPrivate,isDm:D.isDm,autoPilot:D.autoPilot,updatedAt:D.updatedAt};F.has(T)&&(U.name!==ue.name||U.displayName!==ue.displayName||U.path!==ue.path)&&(d=!0),e.setQueryData(t,B=>B?.map(qe=>qe.id===T?ue:qe))}))).find(T=>T.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(d||p.size)&&y()}},h=O=>f().some(R=>R.id===O.item_id||R.path===O.path)?!0:ps(O),_=O=>{if(!h(O))return;let R=String(O.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let F=f().find(K=>K.id===O.item_id||K.path===O.path);F&&(p.add(F.id),m.add(F.id))}(d||p.size)&&y()},w=O=>{let R=f().find(F=>F.id===O.parent_id);R&&(p.add(R.id),y())},q=["vfs_change","ccm_change"].flatMap(O=>[ne(O,_,R=>R.item_type==="channel"),ne(O,w,R=>R.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),q.forEach(O=>O())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,v.useSyncExternalStore)(we,Z,Z)}function Za(){return Y(),Dr()}function ec(e){return Y(),$({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function tc(e){return Y(),$({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function Si(e){return Y(),$({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function nc(e){let t=Si(e);return{...t,children:t.data??[]}}function rc(e,t=1){return Y(),$({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function sc(e,t){return Y(),$({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await C("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function ic(e){Y();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function oc(e){Y();let t=ht(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&Hc(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Ri(e,t={}){let n=Y(),{realtime:r=!1}=t,s=ht(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,v.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Jn({queryKey:c,queryFn:async({pageParam:p=0,signal:m})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!gn(m)&&Hc(p,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&gn(a.error);return{allItems:u,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function za(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function ql(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function ac(e,t={}){let n=za(e),r=Ri(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=V(),i=JSON.stringify([H(),ht(e)]),[o,c]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),a=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,v.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(a.upserts),y=new Set(f.map(w=>w.id)),g=[...f,...r.allItems.filter(w=>!y.has(w.id))].filter(w=>!a.deleted.has(w.path)),h=e.sort_by??"updated_at",_=e.sort_dir==="asc"?1:-1;return g.sort((w,q)=>_*String(w[h]??"").localeCompare(String(q[h]??"")))},[n,r.allItems,a,e?.sort_by,e?.sort_dir]),d=(0,v.useRef)(u);d.current=u;let p=(0,v.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!za(e))return;let f=e,y=!1,g=!1,h=!1,_=0,w=new Map,q=()=>{let S=_;m.current().then(T=>{!y&&!T.isError&&_===S&&c({identity:i,upserts:{},deleted:new Set})})},O=S=>{_++,c(k=>{let I=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},E={...I.upserts};return delete E[S],{identity:i,upserts:E,deleted:new Set(I.deleted).add(S)}});let T=w.get("__reconcile__");T&&clearTimeout(T),w.set("__reconcile__",setTimeout(()=>{w.delete("__reconcile__"),q()},250))},R=S=>{let T=w.get(S);T&&clearTimeout(T),w.set(S,setTimeout(()=>{w.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(k=>{if(!y){if(!k||!ql(k,f)){let I=d.current.find(E=>E.path===S||E.id===k?.id);I&&O(I.path);return}c(I=>{let E=I.identity===i?I:{identity:i,upserts:{},deleted:new Set},U=new Set(E.deleted);return U.delete(S),{identity:i,upserts:{...E.upserts,[S]:k},deleted:U}})}}).catch(k=>console.warn("[useIncrementalItems] item read failed:",k))},250))},F=ne("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let T=typeof S.path=="string"?S.path:S.old_path,k=d.current.find(E=>E.path===T||E.path===S.old_path||S.item_id&&E.id===S.item_id),I=!!k;if(!(!pe(T,f.scope)&&!pe(S.old_path,f.scope)&&!I)&&!(S.item_type&&S.item_type!==f.type&&!I)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!I)){if(k&&(T!==k.path||S.old_path&&S.old_path!==T||S.parent_id&&S.parent_id!==k.parent_id||S.item_type&&S.item_type!==f.type)){O(k.path);return}if(!k&&S.old_path&&S.old_path!==T&&pe(T,f.scope)){_++,R(T);return}if(S.action==="insert")_++,R(T);else if(S.action==="move")_++,R(T);else if(S.action==="update"){if(!p.current?.(S,d.current))return;_++,R(T)}else S.action==="delete"&&O(k?.path??S.old_path??T)}}),K=Jr(S=>{if(S!=="connected"){g&&(h=!0);return}g=!0,h&&(h=!1,q())});return()=>{y=!0,F(),K(),w.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function cc(e){Y();let t=20,n=Jn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));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 uc(e){return Y(),$({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),$({queryKey:P.types(e),queryFn:()=>es(e)})}function lc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function dc(e,t){Y();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var Ja={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 fc(e){let t=ms(e),n=t.data??new Map;return(0,v.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(Ja).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>Ja[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function pc(e,t,n){return Y(),$({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function mc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function hc(e,t=50,n=0){return $({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function gc(e,t=50,n=0){return Y(),$({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function yc(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return mt().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Ql=[];function _c(){let{user:e}=hs(),t=(0,v.useRef)(null),[n,r]=(0,v.useState)(null),s=$({queryKey:P.memberships(e?.id??"anonymous"),queryFn:cs,enabled:!!e?.id,staleTime:1e3*60*2}),i=s.data??Ql,o=(0,v.useMemo)(()=>i.filter(m=>m.isAccount!==!1&&!m.isSpace),[i]),c=(0,v.useMemo)(()=>{let m=new Set(o.map(y=>y.accountId)),f=y=>!y.subordinateTo||!m.has(y.subordinateTo);return[...o].sort((y,g)=>Number(f(g))-Number(f(y)))},[o]),a=(0,v.useSyncExternalStore)(we,Z,Z),u=(0,v.useMemo)(()=>{let m=ye();return m?i.find(f=>f.accountId===m.id)??null:null},[a,i]);(0,v.useEffect)(()=>{if(!e?.id){t.current=null;return}if(t.current!==e.id)if(r(null),c.length===1){let m=c[0];fe()||kt($e(m)),Qt(m.accountId),m.personalSpacePath&&Dt(m.personalSpacePath,f=>{let y=i.find(g=>g.accountId===f);return y?$e(y):null}).catch(r),t.current=e.id}else c.length>1&&(t.current=e.id)},[e?.id,c,i]);let d=(0,v.useCallback)(async m=>{let f=i.find(h=>h.path===m);if(!f)throw new Error("Account membership is unavailable");let y=$e(f);fe()||kt(y);let g=i.find(h=>h.accountId===fe()?.id);if(!g?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(g.personalSpacePath,h=>{let _=i.find(w=>w.accountId===h);return _?$e(_):null}),await mr(y),r(null),Qt(f.accountId)},[i]),p=(0,v.useCallback)(async m=>{let f=i.find(y=>y.path===m);if(!f)throw new Error("Scope membership is unavailable");await vi($e(f))},[i]);return{accounts:c,allMemberships:i,currentAccount:u,mountedScope:null,switchAccount:d,mountScope:p,loading:s.isLoading,error:s.error??n}}function vc(){Y();let e=(0,v.useSyncExternalStore)(Qr,tr,tr),t=(0,v.useMemo)(()=>Te(),[e]),n=ye(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:vi,unmount:Ba}}function hs(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{W.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,v.useCallback)(async m=>m.provider?W.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,v.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,v.useCallback)(async()=>{await W.auth.signOut(),mn(),A().clear()},[]),d=(0,v.useCallback)(async m=>{let{error:f}=await W.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,v.useCallback)(async(m,f)=>{let{error:y}=await W.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:u,resetPassword:d,signInWithMagicLink:p}}function bc(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.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),C("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var hr={},Ya={};te(()=>{for(let e of Object.keys(hr))delete hr[e]});var wc=null;function Sc(e){wc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Dl(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Ol;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}:Fl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||wc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Ul(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Nl(e,t){if(!Ya[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=Ul(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),Ya[e]=s}catch{}}function Kl(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)(Dl),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function xi(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!0),[i,o]=(0,v.useState)(null);return(0,v.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=u+e+"/__bundle.js";try{let _=await fetch(u+e+"/__meta",{cache:"no-store"});_.ok&&(d=(await _.json()).version||1,p=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(c)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let g=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Nl(g).catch(()=>{});let h=Kl(y);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})`);hr[p]=h,c||(n(()=>h),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var Ll=["--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 Rc(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Ll.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function xc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Cc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,En=null,wi=new Set;function jl(){wi.forEach(e=>e())}te(()=>{ce=null,En=null});async function Pc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=Mt()?.principal_id??null;if(n){if(ce&&ce.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ce&&ce.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.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,c=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ce={authUserId:r,...a},a}finally{En=null}})(),En)}async function Tc(e){return(await Pc(e)).principalId}function Ec(){let e=hs(),t=e.user,n=ce?.authUserId===t?.id?ce:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let c=ce;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return wi.add(o),()=>{wi.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Pc(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 Ic(){return{data:null,loading:!1,error:null}}function Ac(e){let{path:t,...n}=e,r=xi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function kc(e){return e.children}function Mc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,v.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),a=V(),u=(0,v.useRef)(null),d=$({queryKey:c,queryFn:()=>as(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let g=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(a,c,{exact:!0})},500)},h=>{let _=a.getQueryData(c);return bi(h,n,r,[..._?.messages??[],..._?.activityMessages??[]])});return()=>{g(),u.current&&clearTimeout(u.current)}},[s,o,n,r,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:y,threads:(0,v.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Oc(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>lr(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:c}),u=(0,v.useMemo)(()=>{if(!a.data?.pages)return[];let g=new Set,h=[];for(let _ of a.data.pages)for(let w of _.messages)g.has(w.id)||(g.add(w.id),h.push(w));return h.sort((_,w)=>_.seq-w.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,v.useMemo)(()=>{let g=new Map,h=[];if(!a.data?.pages)return{messageCards:g,siblingCards:h};let _=new Set;for(let w of a.data.pages){for(let[q,O]of w.messageCards)for(let R of O){if(_.has(R.id))continue;_.add(R.id);let F=g.get(q)||[];F.push(R),g.set(q,F)}for(let q of w.siblingCards)_.has(q.id)||(_.add(q.id),h.push(q))}return{messageCards:g,siblingCards:h}},[a.data?.pages]),m=V(),f=(0,v.useRef)(null),y=(0,v.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,v.useEffect)(()=>{if(!s||!t||!c)return;let g=()=>void Ae(m,y,{exact:!0}),h=!1,_=!1,w=!1,q=async()=>{let F=m.getQueryData(y);if(!F?.pages?.length){g();return}let K=0;for(let S of F.pages)for(let T of S.messages)T.seq>K&&(K=T.seq);if(K===0){g();return}try{let S=await lr(t,{parentMessageId:n,limit:r,after_seq:K});if(S.messages.length===0&&S.siblingCards.length===0){g();return}if(S.messages.length>0){let T=Math.min(...S.messages.map(k=>k.seq));if(T>K+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${K}, minNewSeq=${T}. Triggering full refetch.`),g();return}}m.setQueryData(y,T=>{if(!T)return T;let k=[...T.pages],I=k.length-1,E=k[I],U=new Set(E.messages.map(Re=>Re.id)),D=S.messages.filter(Re=>!U.has(Re.id)),ue=[...E.messages,...D].sort((Re,xs)=>Re.seq-xs.seq),B=new Map(E.messageCards);for(let[Re,xs]of S.messageCards){let Di=B.get(Re)||[],Ku=new Set(Di.map(Cs=>Cs.id)),Lu=xs.filter(Cs=>!Ku.has(Cs.id));B.set(Re,[...Di,...Lu])}let qe=new Set(E.siblingCards.map(Re=>Re.id)),Uu=S.siblingCards.filter(Re=>!qe.has(Re.id)),Nu=[...E.siblingCards,...Uu];return k[I]={...E,activityMessages:S.activityMessages??[],messages:ue,messageCards:B,siblingCards:Nu},{...T,pages:k}})}catch(S){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",S),g()}},O=async()=>{if(h){_=!0;return}h=!0;try{do _=!1,await q();while(_&&!w)}finally{h=!1}},R=ne("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{O()},500)},F=>bi(F,t,n,m.getQueryData(y)?.pages.flatMap(K=>K.messages)??[]));return()=>{w=!0,R(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:u,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:u.filter(g=>g.reply_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}function $l(e){return e==="on"||e==="auto"?"on":"off"}function Xa(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:$l(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",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 gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0}=e,s=V(),i=(0,v.useMemo)(()=>P.channels("all"),[t]),o=$({queryKey:i,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Xa),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return Ga(s,i,Xa)},[n,r,i,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function Fc(e={}){let t=gs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function qc(e={}){let t=gs(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ci(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=V(),c=(0,v.useRef)(null),a=(0,v.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=$({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await C("get-notifications",p)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>ne(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Qc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=Ci({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,v.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,v.useMemo)(()=>{let f=0;return u.forEach(y=>{f+=y}),f},[u]),{dmUnread:p,channelUnread:m}=(0,v.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return u.forEach((h,_)=>{f.has(_)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function Dc(){let e=V();return de({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Uc(){let e=V();return de({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Nc(){return de({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!ce)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ce.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}:{}};ce={...ce,displayName:typeof t.display_name=="string"?t.display_name:ce.displayName,metadata:n},jl()}})}function Kc(){let e=V();return de({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Lc(){let e=V();return de({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function jc(){let e=V();return de({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function $c(e,t){let n=V(),{optimistic:r,...s}=t??{};return de({mutationFn:i=>C(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Vc(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let c=(0,v.useRef)(s),a=(0,v.useRef)(i);(0,v.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,v.useEffect)(()=>o?ne(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Wc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=V(),a=(0,v.useRef)(s);a.current=s;let u=(0,v.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let p=ne(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,c,JSON.stringify(t)]),d}function In(e){Y();let t=H(),n=(0,v.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=$({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await C("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),c=o.data??null,a=(0,v.useMemo)(()=>c?.resolved_children??[],[c]),u=c?.resolution_level??null,d=(0,v.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,v.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=_=>_.id??_.name??"",y=new Map(d.map((_,w)=>[_,w])),g=[],h=[];for(let _ of m)(y.has(f(_))?g:h).push(_);return g.sort((_,w)=>y.get(f(_))-y.get(f(w))),[...g,...h]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function Bc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=Mt(),u=i??a?.scope_id??null,d=(0,v.useMemo)(()=>{if(!t)return null;let R="/accounts/",F=t.indexOf(R);if(F===-1)return null;let K=t.indexOf("/",F+R.length);return K===-1?t:t.slice(0,K)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
|
|
1
|
+
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-26T20:36:19.809Z */
|
|
2
|
+
"use strict";var __FSAOS_GATEWAY__=(()=>{var Gu=Object.create;var Fn=Object.defineProperty;var zu=Object.getOwnPropertyDescriptor;var Ju=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Xu=Object.prototype.hasOwnProperty;var Ki=e=>{throw TypeError(e)};var Zu=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),el=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Li=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ju(t))!Xu.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=zu(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?Gu(Yu(e)):{},Li(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),tl=e=>Li(Fn({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>Zu(e,typeof t!="symbol"?t+"":t,n),Ps=(e,t,n)=>t.has(e)||Ki("Cannot "+n);var l=(e,t,n)=>(Ps(e,t,"read from private field"),n?n.call(e):t.get(e)),x=(e,t,n)=>t.has(e)?Ki("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Ps(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Ps(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var oe=qn((vd,ji)=>{ji.exports=React});var Ir=qn((yp,Ro)=>{Ro.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Qo=qn((Gp,qo)=>{qo.exports={createClient:window.supabase.createClient}});var la=qn((am,ua)=>{ua.exports=ReactDOM});var gu=qn((tg,hu)=>{hu.exports=ReactDOM});var Ui={};el(Ui,{ComponentRenderer:()=>Qc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>Dc,QueryClientProvider:()=>Gn,assignPersonalSection:()=>Lu,auth:()=>Pu,awaitAnchorReady:()=>er,awaitScopeReady:()=>Go,callTool:()=>Ru,cancelQueuedTurn:()=>pu,cancelTurn:()=>du,clearCachedToken:()=>ei,clearSession:()=>ci,configureGatewayReads:()=>sa,createItem:()=>bu,disconnectSSE:()=>_i,disposeVfsRealtimeWs:()=>bi,electHomeAnchor:()=>Mt,emitEvent:()=>Aa,fetchChannelMessages:()=>Ka,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Fi,fetchTimelineHistory:()=>qi,fetchTurnQueueEntries:()=>Da,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>C,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ri,getAssetUrl:()=>Cu,getDefaultSort:()=>Au,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Ma,getQueryClient:()=>O,getRequiredFormFields:()=>ku,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>Zo,getServerClockSyncedAt:()=>ea,getSessionEntry:()=>ht,hasServerClock:()=>Xo,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>lu,initializeWorkspace:()=>vs,interpretSchema:()=>Oi,invalidateAllVfs:()=>Va,invalidateChannelMessages:()=>Wa,invalidateChildren:()=>Yr,invalidateItem:()=>vi,invalidateOpenEnvelope:()=>Ba,invalidatePathAndParent:()=>La,invalidateSubtree:()=>ja,invalidateTypes:()=>$a,isAnchorReady:()=>ii,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Ua,listChildren:()=>vu,loadMounts:()=>Dt,mount:()=>Tu,mountRealtimeScope:()=>Pn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>hi,personalSectionsKey:()=>vr,ping:()=>ka,pushChanges:()=>Su,queryClient:()=>ya,readItem:()=>_u,refreshQuery:()=>Ae,registerCleanup:()=>te,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Oc,resubscribePath:()=>Fa,selectMount:()=>mr,serverDeadlinePassed:()=>ta,serverMsUntil:()=>na,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>No,setQueryClient:()=>ga,setScope:()=>Ho,setupRequireShim:()=>Eu,signal:()=>xu,startTracking:()=>_s,steerTurn:()=>fu,submitForm:()=>mu,subscribeAnchor:()=>si,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>ne,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>au,trackEvent:()=>Nt,trackPageView:()=>ou,unmountRealtimeScope:()=>ls,updateItem:()=>wu,uploadFile:()=>Mu,useAccounts:()=>xc,useAgentTimeline:()=>Uu,useAllChannels:()=>gs,useArrangement:()=>In,useArtifactStream:()=>Du,useAsset:()=>Pc,useAuth:()=>hs,useChannelMessages:()=>Uc,useChannels:()=>Kc,useChildren:()=>cc,useComponent:()=>Pi,useCreate:()=>Vc,useDelete:()=>Bc,useDmChannels:()=>Lc,useEdges:()=>hc,useEventStream:()=>Jc,useFileUpload:()=>Fu,useIncrementalItems:()=>pc,useInfiniteChannelMessages:()=>Nc,useInfiniteChildren:()=>mc,useInfiniteItems:()=>Ci,useItem:()=>oc,useItemById:()=>ac,useItemHistory:()=>wc,useItemVersions:()=>bc,useItems:()=>fc,useLink:()=>Gc,useList:()=>xi,useMemberFocus:()=>vc,useMintedAsset:()=>Xc,useMounts:()=>Cc,useMove:()=>Hc,useMutation:()=>zc,useNotifications:()=>Ti,useOpen:()=>yc,usePermission:()=>Ac,usePermissions:()=>kc,usePersonalItemOrder:()=>eu,usePersonalSections:()=>Vu,usePinnedItems:()=>Ku,usePrincipal:()=>Fc,useRealtimeQuery:()=>Yc,useRecentActivity:()=>Sc,useResolve:()=>dc,useResolvedItems:()=>Qu,useScope:()=>Rc,useScopeReady:()=>ic,useSearch:()=>lc,useTheme:()=>Ic,useTimelineHistory:()=>Nu,useTool:()=>qc,useTree:()=>uc,useType:()=>gc,useTypeHelpers:()=>_c,useTypes:()=>ms,useUnreadCounts:()=>jc,useUpdate:()=>$c,useUpdatePrincipal:()=>Wc,vfsKeys:()=>P,waitForPathReady:()=>Oa});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);ee(this,"name","EnforcementDeniedError");ee(this,"deniedBy");ee(this,"ruleKey");ee(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 An=X(oe(),1);var xe=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 bt,st,Lt,Vi,nl=(Vi=class extends xe{constructor(){super();x(this,bt);x(this,st);x(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,Vi),jt=new nl;var rl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Ts,$i,sl=($i=class{constructor(){x(this,it,rl);x(this,Ts,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Ts=new WeakMap,$i),Qe=new sl;function Wi(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Gi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var il=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Bi(e)&&Bi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:il.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=As(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Bi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Hi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Hi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Hi(e){return Object.prototype.toString.call(e)==="[object Object]"}function zi(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function Ji(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Yi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function Xi(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){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=Wi;function ol(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Zi,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var j=ol();var Bt,ot,Ht,eo,al=(eo=class extends xe{constructor(){super();x(this,Bt,!0);x(this,ot);x(this,Ht);w(this,Ht,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(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,eo),Gt=new al;function cl(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new xr(g);m(h),e.onCancel?.(h)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},f=()=>new Promise(g=>{r=h=>{(i()||u())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(p).catch(v=>{if(i())return;let b=e.retry??(Ue.isServer()?0:3),E=e.retryDelay??cl,I=typeof E=="function"?E(n,v):E,R=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,v);if(t||!R){m(v);return}n++,e.onFail?.(n,v),zi(I).then(()=>u()?void 0:f()).then(()=>{t?m(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var St,to,Pr=(to=class{constructor(){x(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,to);var Rt,zt,Ce,xt,re,Ln,Ct,be,oo,$e,so,io=(so=class extends Pr{constructor(t){super();x(this,be);x(this,Rt);x(this,zt);x(this,Ce);x(this,xt);x(this,re);x(this,Ln);x(this,Ct);w(this,Ct,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Ce,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,ro(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,re)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=ro(this.options);n.data!==void 0&&(this.setState(no(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,re)?.promise;return l(this,re)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(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:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,re)&&(l(this,Ct)||q(this,be,oo).call(this)?l(this,re).cancel({revert:!0}):l(this,re).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,re)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,re))return l(this,re).continueRetry(),l(this,re).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(w(this,Ct,!0),r.signal)})},i=()=>{let a=Rr(this.options,n),d=(()=>{let p={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return w(this,Ct,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),w(this,re,Cr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof xr&&a.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,re).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,Ce).config.onSuccess?.(a,this),l(this,Ce).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof xr){if(a.silent)return l(this,re).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:a}),l(this,Ce).config.onError?.(a,this),l(this,Ce).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Ce=new WeakMap,xt=new WeakMap,re=new WeakMap,Ln=new WeakMap,Ct=new WeakMap,be=new WeakSet,oo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=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,...no(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return w(this,zt,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),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},so);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function no(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ro(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 he,K,Vn,le,Pt,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,L,jn,Os,Fs,qs,Qs,Ds,Us,Ns,lo,uo,Wn=(uo=class extends xe{constructor(t,n){super();x(this,L);x(this,he);x(this,K);x(this,Vn);x(this,le);x(this,Pt);x(this,Jt);x(this,We);x(this,at);x(this,$n);x(this,Yt);x(this,Xt);x(this,Tt);x(this,Et);x(this,ct);x(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,K).addObserver(this),ao(l(this,K),this.options)?q(this,L,jn).call(this):this.updateResult(),q(this,L,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,L,Ds).call(this),q(this,L,Us).call(this),l(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,K);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,L,Ns).call(this),l(this,K).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,K),observer:this});let s=this.hasListeners();s&&co(l(this,K),r,this.options,n)&&q(this,L,jn).call(this),this.updateResult(),s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||Me(this.options.staleTime,l(this,K))!==Me(n.staleTime,l(this,K)))&&q(this,L,Os).call(this);let i=q(this,L,Fs).call(this);s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||i!==l(this,ct))&&q(this,L,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return ll(this,r)&&(w(this,le,r),w(this,Jt,this.options),w(this,Pt,l(this,K).state)),r}getCurrentResult(){return l(this,le)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,L,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,le)))}createResult(t,n){let r=l(this,K),s=this.options,i=l(this,le),o=l(this,Pt),c=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),F=!T&&ao(t,n),k=T&&co(t,r,n,s);(F||k)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&h==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,v=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,T!==void 0&&(h="success",f=Nn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,$n))f=l(this,Yt);else try{w(this,$n,n.select),f=n.select(f),f=Nn(i?.data,f,n),w(this,Yt,f),w(this,at,null)}catch(T){w(this,at,T)}l(this,at)&&(y=l(this,at),f=l(this,Yt),g=Date.now(),h="error");let b=p.fetchStatus==="fetching",E=h==="pending",I=h==="error",R=E&&b,M=f!==void 0,S={status:h,fetchStatus:p.fetchStatus,isPending:E,isSuccess:h==="success",isError:I,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!E,isLoadingError:I&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:I&&M,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=S.data!==void 0,F=S.status==="error"&&!T,k=Q=>{F?Q.reject(S.error):T&&Q.resolve(S.data)},A=()=>{let Q=w(this,We,S.promise=Kn());k(Q)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&k(U);break;case"fulfilled":(F||S.data!==U.value)&&A();break;case"rejected":(!F||S.error!==U.reason)&&A();break}}return S}updateResult(){let t=l(this,le),n=this.createResult(l(this,K),this.options);if(w(this,Pt,l(this,K).state),w(this,Jt,this.options),l(this,Pt).data!==void 0&&w(this,Xt,l(this,K)),Vt(n,t))return;w(this,le,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,le)).some(c=>{let a=c;return l(this,le)[a]!==t[a]&&o.has(a)})};q(this,L,lo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,L,Qs).call(this)}},he=new WeakMap,K=new WeakMap,Vn=new WeakMap,le=new WeakMap,Pt=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,L=new WeakSet,jn=function(t){q(this,L,Ns).call(this);let n=l(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){q(this,L,Ds).call(this);let t=Me(this.options.staleTime,l(this,K));if(Ue.isServer()||l(this,le).isStale||!Dn(t))return;let r=br(l(this,le).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,le).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,K)):this.options.refetchInterval)??!1},qs=function(t){q(this,L,Us).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,K))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,L,jn).call(this)},l(this,ct)))},Qs=function(){q(this,L,Os).call(this),q(this,L,qs).call(this,q(this,L,Fs).call(this))},Ds=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Us=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,K))return;let n=l(this,K);w(this,K,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},lo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,le))}),l(this,he).getQueryCache().notify({query:l(this,K),type:"observerResultsUpdated"})})},uo);function ul(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ao(e,t){return ul(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function co(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function ll(e,t){return!Vt(e.getCurrentResult(),t)}function en(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||[],c={pages:[],pageParams:[]},a=0,u=async()=>{let d=!1,p=y=>{Xi(y,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),f=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let b=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return p(M),M})(),E=await m(b),{maxPages:I}=t.options,R=h?Yi:Ji;return{pages:R(y.pages,E,I),pageParams:R(y.pageParams,g,I)}};if(s&&i.length){let y=s==="backward",g=y?fo:js,h={pages:i,pageParams:o},v=g(r,h);c=await f(h,v,y)}else{let y=e??i.length;do{let g=a===0?o[0]??r.initialPageParam:js(r,c);if(a>0&&g==null)break;c=await f(c,g),a++}while(a<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function js(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 fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function po(e,t){return t?js(e,t)!=null:!1}function mo(e,t){return!t||!e.getPreviousPageParam?!1:fo(e,t)!=null}var Vs=class extends Wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:en()})}getOptimisticResult(e){return e.behavior=en(),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:c}=r,a=n.fetchMeta?.fetchMore?.direction,u=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:po(t,n.data),hasPreviousPage:mo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var Bn,Ne,ae,It,Ke,ut,ho,go=(ho=class extends Pr{constructor(t){super();x(this,Ke);x(this,Bn);x(this,Ne);x(this,ae);x(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ae,t.mutationCache),w(this,Ne,[]),this.state=t.state||$s(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ae).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ae).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ae).config.onMutate&&await l(this,ae).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ae).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ae).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ae).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await l(this,ae).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ae).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ae=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=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),j.batch(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ae).notify({mutation:this,type:"updated",action:t})})},ho);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,yo,_o=(yo=class extends xe{constructor(t={}){super();x(this,Be);x(this,Oe);x(this,Hn);this.config=t,w(this,Be,new Set),w(this,Oe,new Map),w(this,Hn,0)}build(t,n,r){let s=new go({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,yo);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Ws,vo,Bs=(vo=class extends xe{constructor(t,n){super();x(this,ze);x(this,He);x(this,lt);x(this,ge);x(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Ws).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??$s();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){j.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},vo);var Le,bo,wo=(bo=class extends xe{constructor(t={}){super();x(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(s,n),o=this.get(i);return o||(o=new io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Le=new WeakMap,bo);var z,dt,ft,tn,nn,pt,rn,sn,So,Hs=(So=class{constructor(e={}){x(this,z);x(this,dt);x(this,ft);x(this,tn);x(this,nn);x(this,pt);x(this,rn);x(this,sn);w(this,z,e.queryCache||new wo),w(this,dt,e.mutationCache||new _o),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).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=l(this,z).get(r.queryHash)?.state.data,o=Gi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return j.batch(()=>(l(this,z).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=j.batch(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(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===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,So);var on=X(oe(),1),xo=X(Ir(),1),Gs=on.createContext(void 0),$=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,xo.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(oe(),1),Co=Ar.createContext(!1),Po=()=>Ar.useContext(Co),vp=Co.Provider;var zn=X(oe(),1),dl=X(Ir(),1);function fl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var pl=zn.createContext(fl()),To=()=>zn.useContext(pl);var Eo=X(oe(),1);var Io=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ao=e=>{Eo.useEffect(()=>{e.clearReset()},[e])},ko=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Mo=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))}},Oo=(e,t)=>e.isLoading&&e.isFetching&&!t,Fo=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(oe(),1);function kr(e,t,n){let r=Po(),s=To(),i=$(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Mo(o),Io(o,s,c),Ao(s);let a=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let f=p?u.subscribe(j.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),Fo(o,d))throw zs(o,u,s);if(ko({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&Oo(d,r)&&(a?zs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function V(e,t){return kr(e,Wn,t)}var Je=X(oe(),1);function de(e,t){let n=$(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,Vs,t)}var Do=X(Qo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],ml=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",hl=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Pe=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,Do.createClient)(ml,hl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Uo,Zs,Or=!1;Uo=new Promise(e=>{Zs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Zs())});setTimeout(()=>{Or||(Or=!0,Zs())},5e3);function No(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ei(){Xn=null,Mr=0}async function Ye(){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 Uo,Xn}var ln=null,dn=null,Ko=0,Js=new Set,ti,Zn,fn=!1;ti=new Promise(e=>{Zn=e});function ni(){Ko++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],oi()),fn||(fn=!0,Zn()),n&&ni()}function pn(){return ln}function ye(){return dn}function ri(){return Ko}function si(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ti}function ii(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Ys=new Set,Lo=0;function oi(){Lo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return kt}function tr(){return Lo}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function jo(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&oi(),r&&ni()}var cn=null,an=null,un=0,Xs=new Set,Vo=0;function $o(){Vo++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function se(){return un}function ai(){return Vo}function Wo(e){return Xs.add(e),()=>{Xs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Pe}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},$o(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ci(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],$o()}var Bo=[];function te(e){Bo.push(e)}function mn(){ci(),ei(),Zn(),fn=!1,ti=new Promise(e=>{Zn=e}),ni(),oi();for(let e of Bo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ho=qr,H=pn,Z=ri,we=si,Go=er,Dr=ii;var ui=0,zo=!1,Jo=0;function Yo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ui=t-Date.now(),zo=!0,Jo=Date.now())}function Ur(){return Date.now()+ui}function Xo(){return zo}function Zo(){return ui}function ea(){return Jo}function ta(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function na(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],li=0,di={foreground:0,normal:1,background:2},Nr=()=>performance.now(),fi=()=>new DOMException("Read cancelled","AbortError");function sa(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function ia(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(fi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function oa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function aa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(fi());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)di[n.priority??"normal"]<di[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let c=s;s.timer=setTimeout(()=>{c.controller.abort();let a=new Error("The read timed out. Please retry.");a.name="TimeoutError";for(let u of c.consumers)u.detach(),u.reject(a);c.consumers.clear(),Ee.get(c.key)===c&&Ee.delete(c.key),ra(c)},hn.timeoutMs)}let i=s,o=new Promise((c,a)=>{let u=()=>{d.detach(),i.consumers.delete(d),a(fi()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),ra(i))},d={resolve:p=>c(structuredClone(p)),reject:a,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function ra(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;li<hn.concurrency&&Ft.length;){let e=r=>di[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;li++,t.startedAt=Nr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ee.get(t.key)===t&&Ee.delete(t.key),li--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}te(ia);var gl=new Set(["list-memberships","init"]),Ie=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);ee(this,"name","GatewayRequestError");ee(this,"method");ee(this,"status");ee(this,"statusText");ee(this,"payload");ee(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){let r=se(),s=pn(),i=Ot(),o=`${Pe}/d/${i}`,c={"Content-Type":"application/json"},a=await ca(Ye(),n.signal);if(r!==se())throw new Error("Session changed before gateway request");if(a&&(c.Authorization=`Bearer ${a}`),!gl.has(e)&&!t._scope_path&&await ca(er(),n.signal),r!==se())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let m=async f=>{if(r!==se())throw new Error("Session changed before queued gateway request");let y=await fetch(o,{method:"POST",signal:f,headers:c,body:JSON.stringify({method:e,params:u})}),g=await y.text();if(r!==se())throw new Error("Session changed during gateway request");let h=null;if(g)try{h=JSON.parse(g)}catch{}if(!y.ok||!h)throw new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g});if(h.success===!1){let v=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new rt(h):new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g})}return h&&h.server_now!==void 0&&Yo(h.server_now),h};return oa(e,u)?aa(Kr([r,i,a,e,u]),e,n,m):m(n.signal)}function ca(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var _=X(oe(),1),Nl=X(la(),1),Kl=X(Ir(),1);var da=new WeakMap;function Ae(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)}`,c=da.get(e);c||(c=new Map,da.set(e,c));let a=c.get(o);if(a)return a;let u=c,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,fa=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.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&&Ae(e,t,{exact:!0})},250))}function pa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!fa(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&Ze(e,n.queryKey);continue}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)))&&Ze(e,n.queryKey)}}function ma(e){for(let t of e.getQueryCache().getAll())fa(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function ha(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;te(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function ga(e){if(et&&et!==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.");et=e}function O(){return et||(et=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var ya=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function pi(e){return e.meta?.infiniteItemsRealtime?.filter}function yl(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 _l(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function vl(e,t,n){if(yl(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=_l(t);return n.item_type&&o&&!o.has(n.item_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 _a(e,t){let n=Vr.get(e);n||(n=new Map,Vr.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||!pi(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function va(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=pi(n);r&&vl(n,r,t)&&_a(e,n)}}function ba(e){for(let t of e.getQueryCache().getAll())pi(t)&&t.state.data!==void 0&&_a(e,t)}function wa(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Sa(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function gn(e){return e instanceof $r||e instanceof rt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ie(){return H()??"__unscoped__"}var P={all:()=>["vfs",ie()],item:e=>["vfs",ie(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ie(),"children",e],allChildren:()=>["vfs",ie(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ie(),"search",e,...t??[]],items:(e,t)=>["vfs",ie(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",ie(),"items"],tree:(e,t)=>["vfs",ie(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ie(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ie(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ie(),"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",ie(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ie(),"channel-messages"],channels:e=>["vfs",ie(),"channels",e??"all"],allChannels:()=>["vfs",ie(),"channels"],notifications:(e,t)=>["vfs",ie(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ie(),"notifications"],unreadCounts:()=>["vfs",ie(),"unread-counts"],memberships:e=>["memberships",e]};var bl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){bl&&console.log("[WS]",...e)}var D=null,yn=null,vn=null,nr=0,wl=3e4,Ra=1e4,wn=!1,xa=!1,Ia=3e4,Sl=Ia*2+5e3,Wr=0,Br=null,Ca=!1;function Rl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Wr>Sl){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},Ia)}function sr(){Br&&(clearInterval(Br),Br=null)}function xl(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Cl(){Ca||typeof document>"u"||(document.addEventListener("visibilitychange",xl),Ca=!0)}var Se={};function hi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,ke=new Map;function Pl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Pa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ta(e){let t=Pl(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,mi="disconnected",Hr=[];function Gr(e){if(mi!==e){mi=e;for(let t of[...Hr])try{t(e)}catch{}}}function Tl(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function El(){for(let e of je.keys())je.set(e,"disconnected")}function gi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Il(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Pe,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Ea();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),Gr("connecting"),D=new WebSocket(i);let o=D;await new Promise((c,a)=>{if(!D)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ra,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}a(new Error("WebSocket connection timeout"))}},Ra);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=xa;xa=!0,nr=0,Gr("connected"),Al(d),(typeof document>"u"||!document.hidden)&&Rl(),Cl(),c()},o.onmessage=d=>{D===o&&kl(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,sr(),El(),Gr("disconnected"),!wn&&rr()&&Ea(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Ea(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,wl);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function Al(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),gi(t.path,t.event_types);if(e)try{let t=O();ba(t),ma(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",ke.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function kl(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Tl(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"&&(va(O(),r),pa(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&hi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function yi(){!Il()&&tt.size===0&&ke.size===0&&D&&(wn=!0,sr(),D.close(),D=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?gi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}yi()}}function ne(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}yi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Ta(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Pa(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let c=!0;return()=>{if(!c)return;c=!1;let a=_n.get(e);if(!a?.delete(n))return;let u=tt.get(e)?.event_types;if(a.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Ta(e);d&&D&&D.readyState===WebSocket.OPEN&&!Pa(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}yi()}}function Aa(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function _i(){J("disconnectSSE: tearing down"),wa(O()),ha(O()),wn=!0,sr(),D&&(D.close(),D=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),ke.clear(),je.clear(),yt.clear(),Gr("disconnected")}function ka(){nt({type:"ping"})}function Ma(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Oa(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=yt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Fa(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),gi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(mi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}te(_i);function qa(){return new Date().toISOString()}function Qa(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||qa(),updated_at:e.updated_at||qa(),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 or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await C("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Da(e,t){let{items:n}=await xn({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 Zr(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.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 es(e){let n=await C("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function ts(e){try{let t=await C("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Qa(),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||Qa(),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 ns(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 C("tree",s),o=or(i);for(let c of o)O().setQueryData(P.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await C("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 ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await C("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 ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await C("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(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 C("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}}function Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Ml(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Ol=["catalog","parent_only","internal"];function Ua(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?c[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(a[u.slice(9)]=d.filter(n));return{fields:c,field_in:a}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Ol.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,u={};typeof a.item_type=="string"&&a.item_type&&(u.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),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);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(Ml)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&Sa(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function Fl(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 Na(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:Fl(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 ir(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 Ka(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||[],o=ir(i),c=Na(i),a=new Map,u=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:u,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 lr(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 C("get-channel-messages",n),i=s.messages||[],o=Na(i),c=new Map,a=[];for(let u of o)if(u.parentMessagePath){let d=c.get(u.parentMessagePath)||[];d.push(u),c.set(u.parentMessagePath,d)}else a.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:a,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 Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function vi(e){O().invalidateQueries({queryKey:P.item(e)})}function La(e,t){vi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function ja(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Va(){O().invalidateQueries({queryKey:P.all()})}function $a(e){O().invalidateQueries({queryKey:P.types(e)})}function Wa(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Ba(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await C("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Cn=new Map,dr=null,us=null,_t=new Map,Ha=250;function Qt(e){if(dr){Pn(e);return}Pn(e),dr=ne("vfs_change",t=>ql(t)),us=ne("ccm_change",t=>Ql(t))}function Pn(e){if(Cn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Cn.set(e,t)}function ls(e){let t=Cn.get(e);t&&(t(),Cn.delete(e))}function bi(){for(let[,e]of Cn)e();Cn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}te(bi);function ql(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Dl(n,t,e,s)},Ha);_t.set(s,o)}function Ql(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)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},Ha);_t.set(s,o)}function Dl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;te(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==se())throw new Error("Workspace session changed")}function Ul(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function pr(e){let t=fe();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function Ga(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function za(e,t,n){vt(e);let r=Ga(t,n);if(e.saved===r)return;let s=JSON.parse(r);await C(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),vt(e),e.exists=!0,e.saved=r}function Ja(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Pn(r.id);jo(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await C("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Ul(d))throw d;i.exists=!1}let c=n.initialAnchor?fr(i,n.initialAnchor):r,a=pr(o?o.mounts.map(t).filter(d=>d!==null):[c]),u=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=Ga(a,u):n.initialAnchor&&await za(i,a,u),vt(i),i.ready=!0,Ja(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await za(t,r,s),vt(t),Ja(r,s)});return t.queue=n.catch(()=>{}),n}function wi(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function Ya(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function Si(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&pe(e.path,i)})}var Xa=new WeakMap;function Za(e,t,n){let r=Xa.get(e);r||(r=new Map,Xa.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,u=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||u||a||(a=setTimeout(()=>{a=void 0,g()},250))},g=async()=>{if(c)return;u=!0;let I=d;d=!1;let R=[...p],M=new Set(m);m.clear(),p.clear();try{if(I)await Ae(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async T=>{let F=e.getQueryCache().find({queryKey:t,exact:!0});if(!F)return;let k=await C("read",{id:T});if(k.success===!1)throw new Error("Channel refresh failed");if(c||!F||e.getQueryCache().find({queryKey:t,exact:!0})!==F)return;let A=_e(k.item??k);if(A.id!==T||A.item_type!=="channel")return;let U=f().find(B=>B.id===T);if(!U)return;let Q=n({...A}),ue={...U,path:Q.path,name:Q.name,displayName:Q.displayName,messageCount:Q.messageCount,aiMode:Q.aiMode,isPrivate:Q.isPrivate,isDm:Q.isDm,autoPilot:Q.autoPilot,isArchived:Q.isArchived,updatedAt:Q.updatedAt};M.has(T)&&(U.name!==ue.name||U.displayName!==ue.displayName||U.path!==ue.path)&&(d=!0),e.setQueryData(t,B=>B?.map(qe=>qe.id===T?ue:qe))}))).find(T=>T.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(d||p.size)&&y()}},h=I=>f().some(R=>R.id===I.item_id||R.path===I.path)?!0:ps(I),v=I=>{if(!h(I))return;let R=String(I.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let M=f().find(N=>N.id===I.item_id||N.path===I.path);M&&(p.add(M.id),m.add(M.id))}(d||p.size)&&y()},b=I=>{let R=f().find(M=>M.id===I.parent_id);R&&(p.add(R.id),y())},E=["vfs_change","ccm_change"].flatMap(I=>[ne(I,v,R=>R.item_type==="channel"),ne(I,b,R=>R.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),E.forEach(I=>I())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,_.useSyncExternalStore)(we,Z,Z)}function ic(){return Y(),Dr()}function oc(e){return Y(),V({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function ac(e){return Y(),V({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function xi(e){return Y(),V({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function cc(e){let t=xi(e);return{...t,children:t.data??[]}}function uc(e,t=1){return Y(),V({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function lc(e,t){return Y(),V({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await C("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function dc(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return V({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function fc(e){Y();let t=gt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=V({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&Zc(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Ci(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,_.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Jn({queryKey:c,queryFn:async({pageParam:p=0,signal:m})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!gn(m)&&Zc(p,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&gn(a.error);return{allItems:u,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function ec(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Ll(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function pc(e,t={}){let n=ec(e),r=Ci(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=$(),i=JSON.stringify([H(),gt(e)]),[o,c]=(0,_.useState)(()=>({identity:i,upserts:{},deleted:new Set})),a=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,_.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(a.upserts),y=new Set(f.map(b=>b.id)),g=[...f,...r.allItems.filter(b=>!y.has(b.id))].filter(b=>!a.deleted.has(b.path)),h=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return g.sort((b,E)=>v*String(b[h]??"").localeCompare(String(E[h]??"")))},[n,r.allItems,a,e?.sort_by,e?.sort_dir]),d=(0,_.useRef)(u);d.current=u;let p=(0,_.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let m=(0,_.useRef)(r.refetch);return m.current=r.refetch,(0,_.useEffect)(()=>{if(!ec(e))return;let f=e,y=!1,g=!1,h=!1,v=0,b=new Map,E=()=>{let S=v;m.current().then(T=>{!y&&!T.isError&&v===S&&c({identity:i,upserts:{},deleted:new Set})})},I=S=>{v++,c(F=>{let k=F.identity===i?F:{identity:i,upserts:{},deleted:new Set},A={...k.upserts};return delete A[S],{identity:i,upserts:A,deleted:new Set(k.deleted).add(S)}});let T=b.get("__reconcile__");T&&clearTimeout(T),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),E()},250))},R=S=>{let T=b.get(S);T&&clearTimeout(T),b.set(S,setTimeout(()=>{b.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(F=>{if(!y){if(!F||!Ll(F,f)){let k=d.current.find(A=>A.path===S||A.id===F?.id);k&&I(k.path);return}c(k=>{let A=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},U=new Set(A.deleted);return U.delete(S),{identity:i,upserts:{...A.upserts,[S]:F},deleted:U}})}}).catch(F=>console.warn("[useIncrementalItems] item read failed:",F))},250))},M=ne("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let T=typeof S.path=="string"?S.path:S.old_path,F=d.current.find(A=>A.path===T||A.path===S.old_path||S.item_id&&A.id===S.item_id),k=!!F;if(!(!pe(T,f.scope)&&!pe(S.old_path,f.scope)&&!k)&&!(S.item_type&&S.item_type!==f.type&&!k)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!k)){if(F&&(T!==F.path||S.old_path&&S.old_path!==T||S.parent_id&&S.parent_id!==F.parent_id||S.item_type&&S.item_type!==f.type)){I(F.path);return}if(!F&&S.old_path&&S.old_path!==T&&pe(T,f.scope)){v++,R(T);return}if(S.action==="insert")v++,R(T);else if(S.action==="move")v++,R(T);else if(S.action==="update"){if(!p.current?.(S,d.current))return;v++,R(T)}else S.action==="delete"&&I(F?.path??S.old_path??T)}}),N=Jr(S=>{if(S!=="connected"){g&&(h=!0);return}g=!0,h&&(h=!1,E())});return()=>{y=!0,M(),N(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function mc(e){Y();let t=20,n=Jn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));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 hc(e){return Y(),V({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),V({queryKey:P.types(e),queryFn:()=>es(e)})}function gc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function yc(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return V({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var tc={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 _c(e){let t=ms(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(tc).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>tc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function vc(e,t,n){return Y(),V({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function bc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return V({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function wc(e,t=50,n=0){return V({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Sc(e,t=50,n=0){return Y(),V({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Rc(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Xe().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var jl=[];function nc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Vl(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function xc(){let{user:e}=hs(),t=(0,_.useSyncExternalStore)(Wo,ai,ai),n=ht()?.principal_id??null,r=(0,_.useRef)(null),[s,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(n){c(null);return}if(!e?.id&&!nc()){c(null);return}let b=!1;return Xe().then(E=>{b||E.principal_id||c(new Error("Memberships require an authenticated principal"))}).catch(E=>{b||c(E instanceof Error?E:new Error(String(E)))}),()=>{b=!0}},[n,e?.id,t]);let a=V({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=a.data??jl,d=(0,_.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),p=(0,_.useMemo)(()=>{let b=new Set(d.map(I=>I.accountId)),E=I=>!I.subordinateTo||!b.has(I.subordinateTo);return[...d].sort((I,R)=>Number(E(R))-Number(E(I)))},[d]),m=(0,_.useSyncExternalStore)(we,Z,Z),f=(0,_.useMemo)(()=>{let b=ye();return b?u.find(E=>E.accountId===b.id)??null:null},[m,u]),y=(0,_.useMemo)(()=>Vl(d),[d]);(0,_.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let b=p[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,E=>{let I=u.find(R=>R.accountId===E);return I?Ve(I):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let g=(0,_.useCallback)(async b=>{let E=u.find(M=>M.path===b);if(!E)throw new Error("Account membership is unavailable");let I=Ve(E);fe()||Mt(I);let R=u.find(M=>M.accountId===fe()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(R.personalSpacePath,M=>{let N=u.find(S=>S.accountId===M);return N?Ve(N):null}),await mr(I),i(null),Qt(E.accountId)},[u]),h=(0,_.useCallback)(async b=>{let E=u.find(I=>I.path===b);if(!E)throw new Error("Scope membership is unavailable");await wi(Ve(E))},[u]),v=(!!e?.id||nc())&&!n&&!o;return{accounts:p,switcherAccounts:y,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:g,mountScope:h,loading:v||a.isLoading,error:o??a.error??s}}function Cc(){Y();let e=(0,_.useSyncExternalStore)(Qr,tr,tr),t=(0,_.useMemo)(()=>Te(),[e]),n=ye(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:wi,unmount:Ya}}function hs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{W.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,_.useCallback)(async m=>m.provider?W.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await W.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await W.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:u,resetPassword:d,signInWithMagicLink:p}}function Pc(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),C("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var hr={},rc={};te(()=>{for(let e of Object.keys(hr))delete hr[e]});var Tc=null;function Ec(e){Tc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function $l(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Nl;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}:Kl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Tc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Wl(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Bl(e,t){if(!rc[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=Wl(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),rc[e]=s}catch{}}function Hl(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)($l),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Pi(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=u+e+"/__bundle.js";try{let v=await fetch(u+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(c)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let g=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Bl(g).catch(()=>{});let h=Hl(y);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})`);hr[p]=h,c||(n(()=>h),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var Gl=["--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,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Gl.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Ac(e,t){return{data:{allowed:!0},loading:!1,error:null}}function kc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,En=null,Ri=new Set;function zl(){Ri.forEach(e=>e())}te(()=>{ce=null,En=null});async function Mc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ce&&ce.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ce&&ce.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.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,c=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ce={authUserId:r,...a},a}finally{En=null}})(),En)}async function Oc(e){return(await Mc(e)).principalId}function Fc(){let e=hs(),t=e.user,n=ce?.authUserId===t?.id?ce:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let c=ce;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Mc(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 qc(){return{data:null,loading:!1,error:null}}function Qc(e){let{path:t,...n}=e,r=Pi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function Dc(e){return e.children}function Uc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),a=$(),u=(0,_.useRef)(null),d=V({queryKey:c,queryFn:()=>as(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let g=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(a,c,{exact:!0})},500)},h=>{let v=a.getQueryData(c);return Si(h,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{g(),u.current&&clearTimeout(u.current)}},[s,o,n,r,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:y,threads:(0,_.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Nc(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>lr(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:c}),u=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let g=new Set,h=[];for(let v of a.data.pages)for(let b of v.messages)g.has(b.id)||(g.add(b.id),h.push(b));return h.sort((v,b)=>v.seq-b.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let g=new Map,h=[];if(!a.data?.pages)return{messageCards:g,siblingCards:h};let v=new Set;for(let b of a.data.pages){for(let[E,I]of b.messageCards)for(let R of I){if(v.has(R.id))continue;v.add(R.id);let M=g.get(E)||[];M.push(R),g.set(E,M)}for(let E of b.siblingCards)v.has(E.id)||(v.add(E.id),h.push(E))}return{messageCards:g,siblingCards:h}},[a.data?.pages]),m=$(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let g=()=>void Ae(m,y,{exact:!0}),h=!1,v=!1,b=!1,E=async()=>{let M=m.getQueryData(y);if(!M?.pages?.length){g();return}let N=0;for(let S of M.pages)for(let T of S.messages)T.seq>N&&(N=T.seq);if(N===0){g();return}try{let S=await lr(t,{parentMessageId:n,limit:r,after_seq:N});if(S.messages.length===0&&S.siblingCards.length===0){g();return}if(S.messages.length>0){let T=Math.min(...S.messages.map(F=>F.seq));if(T>N+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${N}, minNewSeq=${T}. Triggering full refetch.`),g();return}}m.setQueryData(y,T=>{if(!T)return T;let F=[...T.pages],k=F.length-1,A=F[k],U=new Set(A.messages.map(Re=>Re.id)),Q=S.messages.filter(Re=>!U.has(Re.id)),ue=[...A.messages,...Q].sort((Re,xs)=>Re.seq-xs.seq),B=new Map(A.messageCards);for(let[Re,xs]of S.messageCards){let Ni=B.get(Re)||[],Bu=new Set(Ni.map(Cs=>Cs.id)),Hu=xs.filter(Cs=>!Bu.has(Cs.id));B.set(Re,[...Ni,...Hu])}let qe=new Set(A.siblingCards.map(Re=>Re.id)),$u=S.siblingCards.filter(Re=>!qe.has(Re.id)),Wu=[...A.siblingCards,...$u];return F[k]={...A,activityMessages:S.activityMessages??[],messages:ue,messageCards:B,siblingCards:Wu},{...T,pages:F}})}catch(S){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",S),g()}},I=async()=>{if(h){v=!0;return}h=!0;try{do v=!1,await E();while(v&&!b)}finally{h=!1}},R=ne("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{I()},500)},M=>Si(M,t,n,m.getQueryData(y)?.pages.flatMap(N=>N.messages)??[]));return()=>{b=!0,R(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:u,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:u.filter(g=>g.reply_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}function Jl(e){return e==="on"||e==="auto"?"on":"off"}function sc(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:Jl(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",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,isArchived:t.is_archived===!0}}function gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=$(),o=(0,_.useMemo)(()=>P.channels("all"),[t]),c=V({queryKey:o,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(sc),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return Za(i,o,sc)},[n,r,o,i]),{channels:(0,_.useMemo)(()=>(c.data??[]).filter(u=>s||!u.isArchived),[c.data,s]),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Kc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Lc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ti(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=$(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=V({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await C("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>ne(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function jc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=Ti({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,_.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return u.forEach(y=>{f+=y}),f},[u]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return u.forEach((h,v)=>{f.has(v)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function Vc(){let e=$();return de({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function $c(){let e=$();return de({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Wc(){return de({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!ce)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ce.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}:{}};ce={...ce,displayName:typeof t.display_name=="string"?t.display_name:ce.displayName,metadata:n},zl()}})}function Bc(){let e=$();return de({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Hc(){let e=$();return de({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function Gc(){let e=$();return de({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function zc(e,t){let n=$(),{optimistic:r,...s}=t??{};return de({mutationFn:i=>C(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Jc(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?ne(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Yc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=$(),a=(0,_.useRef)(s);a.current=s;let u=(0,_.useRef)(null),d=V({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=ne(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,c,JSON.stringify(t)]),d}function In(e){Y();let t=H(),n=(0,_.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=V({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await C("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),c=o.data??null,a=(0,_.useMemo)(()=>c?.resolved_children??[],[c]),u=c?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,_.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=v=>v.id??v.name??"",y=new Map(d.map((v,b)=>[v,b])),g=[],h=[];for(let v of m)(y.has(f(v))?g:h).push(v);return g.sort((v,b)=>y.get(f(v))-y.get(f(b))),[...g,...h]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function Xc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=ht(),u=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let N=t.indexOf("/",M+R.length);return N===-1?t:t.slice(0,N)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
|
|
4
4
|
${u??""}
|
|
5
5
|
${p??""}
|
|
6
6
|
${m??""}
|
|
7
|
-
${t??""}`,[y,g]=(0,v.useState)(null),h=(0,v.useRef)({key:f,found:null,earlyContentPaths:new Set}),_=y?.key===f?y:null;(0,v.useLayoutEffect)(()=>{h.current={key:f,found:_,earlyContentPaths:new Set}},[f]);let w=$({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let R=await C("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),F=R.content?.items??R.items??[],K=F[0]?_e(F[0]):null;if(!K)return null;let T=(await cr(K.path)).some(k=>k.item_type==="file"&&!!k.type_data?.file_ref);return{asset:K,hasBytes:T}},enabled:!!(t&&p&&m&&!s),refetchInterval:R=>h.current.key===f&&h.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,v.useEffect)(()=>{let R=w.data;if(!R||h.current.key!==f)return;let F=h.current.found,K={key:f,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(F?.itemId===R.asset.id&&F.hasBytes)};h.current.found=K,g(K)},[w.data,f]);let q=!!(t&&u)&&!s&&!_?.hasBytes;return(0,v.useEffect)(()=>{if(!(!q||!u))return Sn(u,["asset.materialized","content.written"])},[q,u]),(0,v.useEffect)(()=>{if(!q||!t||!u)return;let R=f,F=I=>I?.payload??I,K=I=>{let U=F(I)?.scope_id??I?.scope_id;return typeof U=="string"?U:void 0},S=I=>{let U=F(I)?.item_path??I?.item_path;return typeof U=="string"&&U?U:void 0},T=(I,E)=>{let U=E.replace(/\/+$/,"");return I===U||I.startsWith(`${U}/`)},k=[ne("asset.materialized",I=>{if(h.current.key!==R)return;let E=F(I);if(typeof E?.item_id!="string"||!E.item_id)return;let U=h.current.found,D=typeof E.item_path=="string"?E.item_path:void 0,ue=!!E.has_bytes||!!(D&&Array.from(h.current.earlyContentPaths).some(qe=>T(qe,D)))||!!(U&&U.itemId===E.item_id&&U.hasBytes),B={key:R,itemId:E.item_id,itemPath:D,displayName:typeof E.display_name=="string"?E.display_name:void 0,hasBytes:ue};h.current.found=B,g(B)},I=>{let E=K(I);return(!E||E===u)&&F(I)?.origin===t}),ne("content.written",I=>{if(h.current.key!==R)return;let E=S(I);if(!E)return;let U=h.current.found;if(!U?.itemPath||!T(E,U.itemPath)){if(h.current.earlyContentPaths.add(E),h.current.earlyContentPaths.size>128){let ue=h.current.earlyContentPaths.values().next().value;ue&&h.current.earlyContentPaths.delete(ue)}return}if(U.hasBytes)return;let D={...U,hasBytes:!0};h.current.found=D,g(D)},I=>{let E=K(I);return(!E||E===u)&&!!S(I)})];return()=>k.forEach(I=>I())},[q,t,u,f]),{state:s?"failed":t?_?_.hasBytes?"ready":"materializing":"pending":"idle",itemId:_?.itemId,itemPath:_?.itemPath,displayName:_?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Hc(e,t){let n=A().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Gc(e,t){let n=(0,An.useSyncExternalStore)(we,Z,Z),r=ye(),s=H(),i=r?.kind==="space",o=In(i&&s?{key:e,scope_id:r.id}:null),c=(0,An.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),g=f.filter(_=>!y.has(_.id)),h=_=>Date.parse(_.createdAt??"")||0;return g.sort((_,w)=>h(w)-h(_)),[...g,...f.filter(_=>y.has(_.id))]},[e,t,o.applyTo,o.order]),a=V(),u=(0,An.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=de({mutationFn:async f=>{let y=await C("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,g)=>Xe(a,g.queryKey)});async function m(f){if(!d||!s||n!==Z()||H()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let y=t.map(R=>R.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(R=>!f.includes(R)))throw new Error("Order must include each displayed item exactly once");let g=a.getQueryData(o.arrangementQueryKey);if(g?.item_id!==o.arrangement.item_id||JSON.stringify(g?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=c.map(R=>R.id);if(f.every((R,F)=>h[F]===R))return;let _=new Set(y),w=0,O=[...(o.order??[]).map(R=>_.has(R)?f[w++]:R),...f.slice(w)];u.current=!0;try{return await p.mutateAsync({ids:O,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Vl=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,zc=new Map,Jc=new Map,kn=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Ut(e){let t=e?It.find(n=>n.id===e):It.find(n=>n.default===!0)??(It.length===1?It[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 ys(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 Wl(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Bl(e,t){if(!Wl(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ti(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Hl(e){try{let t=Ti(e)?.getItem(e.key)??void 0;return t&&Pi.test(t)?t:void 0}catch{return}}function Yc(e,t){try{Ti(e)?.setItem(e.key,t)}catch{}}function Xc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Hl(t)??zc.get(e.id);if(n)return n;let r=crypto.randomUUID();return zc.set(e.id,r),Yc(t,r),r}function Zc(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 u=Ti(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=Jc.get(e.id),i=r&&typeof r.id=="string"&&Pi.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Jc.set(e.id,a),Yc(n,JSON.stringify(a)),a.id}function Gl(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(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Nt(e,t={},n={}){let r=Ut(n.source);if(Bl(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??Xc(r),o=n.sessionId??Zc(r);if(![s,i,o].every(h=>Pi.test(h)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=Gl(r,c),p=d?{...t,source_keys:d}:t,m=Ot(),f=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new kn(h instanceof Error?h.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let g=null;try{g=await y.json()}catch{}if(!y.ok||g?.success!==!0){let h=g;throw new kn(h?.message||h?.error||`Observation transport failed (${y.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return g}function eu(e={},t={}){let n=Ut(t.source),r=ys("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Nt(r.observation,{...s,...e},{...t,source:n.id})}function tu(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Ut(n.source),s=ys("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Nt(s.observation,{...t,...i},{...n,source:r.id})}function nu(){try{let e=Ut();return ys("form_receipt",e),{visitor_id:Xc(e),session_id:Zc(e),source:e.id}}catch{return}}function zl(e,t={}){let n=Ut(t.source),r=ys("form_receipt",n);return Nt(r.observation,e,{...t,source:n.id})}async function Jl(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function ru(e,t,n,r,s){let i=It.filter(o=>o.adapters?.some(c=>c.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let c=o.id===r?.source;return zl(e,{source:o.id,eventId:c?t:await Jl(t,o.id),pageUrl:n,signal:s,keepalive:!0,...c?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var gr;function _s(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gr)return gr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Ut(e.source)]:It.map(m=>Ut(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="page_view").map(f=>({source:m,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="declared_action").map(f=>({source:m,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:f}of n){let y=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};Nt(f.observation,y,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:f,adapter:y}of r){let g=y.attribute;if(!g||!Vl.test(g))continue;let h=m.target.closest(`[${g}]`);if(!h)continue;let _=h.getAttribute(g)?.trim();if(!_||_.length>128)continue;let w={};y.id_property&&(w[y.id_property]=_),y.element_property&&(w[y.element_property]=h.tagName.toLowerCase()),Nt(y.observation,w,{source:f.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:m})=>m.history===!0),p=n.some(({adapter:m})=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),u()},window.history.replaceState=function(...f){a.apply(this,f),u()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),gr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),gr=void 0},gr}var Mn;te(()=>{Mn=void 0});function vs(e){if(Mn)return Mn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Mn.promise;let t=se(),n=()=>{if(t!==se())throw new Error("Workspace session changed")},r=(async()=>{let s=await mt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await A().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:cs,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=$e(o),u=$e(c),d=fe();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||kt(a,{activate:!1}),await Dt(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?$e(m):null},{initialAnchor:u}),n(),{home:a,defaultSpace:u,memberships:i}})().catch(s=>{throw t===se()&&(Mn=void 0),s});return Mn={accountPath:e.accountPath,promise:r},r}var Kt,_r,yr;te(()=>{_r?.(),_r=void 0,Kt=void 0,yr=void 0});function su(e={}){if(Kt)return e.workspace&&e.workspace.accountPath!==yr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Kt;yr=e.workspace?.accountPath;let t=se();return Kt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:_s(typeof n=="object"?n:{});_r=r;try{let s=e.session===!1?null:await mt(),i=e.workspace?await vs(e.workspace):void 0;if(t!==se())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===se()&&(Kt=void 0,yr=void 0,_r=void 0))}}}catch(s){throw r(),t===se()&&(Kt=void 0,yr=void 0,_r=void 0),s}})(),Kt}async function Ei(e){try{return await C("execution-control-transition",e)}catch(t){if(!(t instanceof Ie)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),C("execution-control-transition",e)}}function Ii(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 iu(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 Ei({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 Ii(i?{...s,state:i}:s)}async function ou(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 Ei({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return Ii(c?{...o,state:c}:o)}async function au(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 Ei({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 Ii(i?{...s,outcome:i}:s)}var Yl=/^[a-z][a-z0-9_-]{0,63}$/,Xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function cu(e,t,n={}){if(!Yl.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(!Xl.test(r))throw new TypeError("fillId must be a UUID");let s=Ot(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=nu(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new On(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await u.json()}catch{}if(!u.ok||d?.success!==!0){let p=d;throw new On(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await ru({fill_id:r,action_id:e,release_id:d.release_id},r,i,c,n.signal),d}var Ai=X(oe(),1),du=X(lu(),1);function fu(e){return C("read",{path:e})}function pu(e,t){return C("list",{path:e,...t})}function mu(e){return C("create",e)}function hu(e){return C("update",e)}function gu(e){return C("create",e)}function yu(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return C("tools/call",{name:e,instance_path:r,...t||{}})}function _u(e,t,n){return C("signal",{target_id:e,event_name:t,payload:n||{}})}function vu(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var bu={signIn:e=>e.provider?W.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):W.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>W.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await W.auth.signOut(),mn(),A().clear()},getSession:()=>W.auth.getSession().then(e=>e.data.session),getUser:()=>W.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=W.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>W.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>W.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function wu(){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,du.createRoot)(e).render((0,Ai.createElement)(Gn,{client:A()},(0,Ai.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 Su(){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}function Zl(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ed(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function td(e,t){return!(e==="object"||e==="array")}function nd(e){return["string","number","integer","boolean"].includes(e)}function rd(e){return e!=="object"&&e!=="array"}function Ru(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",u=c.enum,d=td(a,u),p=nd(a),m=ed(a,u);i.push({key:o,label:c.title||Zl(o),type:a,description:c.description,enum_values:u,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function ki(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ru(e.input_schema,!0,t,n),s=Ru(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>rd(u.type)),c=i.filter(u=>u.filterable),a=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function xu(e){return{field:"updated_at",direction:"desc"}}function Cu(e){let t=ki(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(oe(),1);var sd=0;function id(){return`upload_${Date.now()}_${++sd}`}async function Pu(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",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let u=await C("create",c);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,p=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:p,fileRef:u.file_ref};let m=u.storage_key,f=u.upload_token,y=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await od(y,m,f,e,i,n,r);let g=await Tu(d,m,i);return{itemId:d,itemPath:p,fileRef:g}}function od(e,t,n,r,s,i,o){return new Promise((c,a)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},u.onload=()=>{u.status>=200&&u.status<300?c():a(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>a(new Error("Storage upload network error")),u.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),a(new Error("Upload cancelled"))})}u.send(r)})}async function Tu(e,t,n){let r=await Ye(),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 Eu(){let[e,t]=(0,ve.useState)([]),n=V(),r=(0,ve.useRef)(e);r.current=e;let s=(0,ve.useCallback)((g,h)=>{t(_=>_.map(w=>w.id===g?{...w,...h}:w))},[]),i=(0,ve.useCallback)(g=>{t(h=>[...h,g])},[]),o=(0,ve.useCallback)(async(g,h,_,w,q)=>{let O=_.name||h.name,R=h.type||"application/octet-stream",F=_.itemType||"file",K=q?.itemId||null,S=q?.itemPath||null,T=q?.storageKey||null,k=q?.uploadToken||null,I=q?.storageWorkerUrl||null;try{if(!w||w==="create"){s(g,{status:"creating",error:null,_failedAt:null});let D=await C("create",{parent_path:_.parentPath,item_type:F,name:O,type_data:{..._.typeData||{},file_source:{type:"upload",content_type:R}}});if(!D.id)throw Object.assign(new Error(D.error||D.message||"Failed to create file item"),{_step:"create"});if(K=D.id,S=D.path,s(g,{itemId:K,itemPath:S}),D.storage_completed&&D.file_ref){s(g,{status:"complete",progress:100,fileRef:D.file_ref}),n.invalidateQueries({queryKey:P.children(_.parentPath)});return}if(T=D.storage_key,k=D.upload_token||"",I=D.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(g,{_storageKey:T,_uploadToken:k,_storageWorkerUrl:I}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!w||w==="create"||w==="upload")&&(s(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((D,ue)=>{let B=new XMLHttpRequest;s(g,{_xhr:B}),B.open("PUT",`${I}/upload`),B.setRequestHeader("X-Storage-Key",T),B.setRequestHeader("Content-Type",R),k&&B.setRequestHeader("X-Upload-Token",k),B.upload.onprogress=qe=>{qe.lengthComputable&&s(g,{progress:Math.round(qe.loaded/qe.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?D():ue(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>ue(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>ue(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(h)}),s(g,{progress:100,_xhr:null})),s(g,{status:"confirming",error:null,_failedAt:null});let E=await Tu(K,T,R);s(g,{status:"complete",fileRef:E}),n.invalidateQueries({queryKey:P.children(_.parentPath)})}catch(E){let U=E?.message||String(E),D=E?._step||"create";s(g,{status:"error",error:U,_failedAt:D,_xhr:null})}},[s,n]),c=(0,ve.useCallback)((g,h)=>{let _=id();i({id:_,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(_,g,h)},[i,o]),a=(0,ve.useCallback)((g,h)=>{for(let _ of g)c(_,h)},[c]),u=(0,ve.useCallback)(g=>{let h=r.current.find(q=>q.id===g);if(!h||h.status!=="error")return;let _=h._failedAt||"create",w=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,_,w)},[o]),d=(0,ve.useCallback)(g=>{let h=r.current.find(_=>_.id===g);h&&(h._xhr&&h._xhr.abort(),s(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ve.useCallback)(g=>{t(h=>h.filter(_=>_.id!==g))},[]),m=(0,ve.useCallback)(()=>{t(g=>g.filter(h=>h.status!=="complete"))},[]),f=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),y=e.map(({_storageKey:g,_uploadToken:h,_storageWorkerUrl:_,_xhr:w,_failedAt:q,...O})=>O);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:u,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var Iu=X(oe(),1);async function Mi(e,t){return await C("resolve-items",{context_id:e,item_type:t})}function Au(e,t){return(0,Iu.useSyncExternalStore)(we,Z,Z),$({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Mi(e,t),enabled:!!(e&&t)})}var Fe=X(oe(),1);function bs(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{a=JSON.parse(u)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return zr(e,s)}function ku(e,t=!0){let[n,r]=(0,Fe.useState)(new Map),[s,i]=(0,Fe.useState)([]),o=(0,Fe.useRef)({artifacts:new Map,timeline:[]});(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Fe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,u=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:u,reset:c}}function Mu(e,t=!0){let[n,r]=(0,Fe.useState)([]);(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ws=X(oe(),1);function ad(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Oi(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 c=(await C("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(cd).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Ou(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=V(),u=(0,ws.useRef)(null),d=c?ad(c,n,r,s):["vfs","timeline-history","__disabled__"],p=$({queryKey:d,queryFn:()=>Oi(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ws.useEffect)(()=>{if(!c||!i)return;let m=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c&&f.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function cd(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 Ss=X(oe(),1);function Fu(){(0,Ss.useSyncExternalStore)(we,Z,Z);let e=H(),t=ye(),n=In(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=V(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=de({mutationFn:async a=>{let u,d={_scope_path:a.scopePath};if(a.operation==="pin"?u=await C("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?u=await C("delete",{...d,id:a.entry.id}):u=await C("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(a,u,d)=>Xe(r,d.queryKey)}),c=(0,Ss.useCallback)(a=>!i||!e||H()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(u=>u.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(u=>!a.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,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:a=>s.some(u=>u.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return u?c({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}var Rs=X(oe(),1);var vr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Fi(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function qi(e,t,n,r){let s=await C("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function qu(e,t){let n=await qi(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=A();return r.setQueryData(vr(e.scopePath,e.contextId,e.collection),s=>Fi(s,n)),Qu(r,e.scopePath),n}function Qu(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Xe(e,n.queryKey)}function Du(e,t){let n=(0,Rs.useSyncExternalStore)(we,Z,Z),r=H(),s=V(),i=vr(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>qi(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,m)=>Fi(p,m)}),c=(0,Rs.useRef)(!1),a=de({mutationFn:async p=>{let m=await qi(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(vr(p.scope,p.context,p.collection),f=>Fi(f,m)),m},onSettled:(p,m,f)=>Qu(s,f.scope)});async function u(p){if(!r||!e||n!==Z()||H()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(c.current)throw new Error("A section change is still being saved");c.current=!0;try{return await a.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{c.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(m=>m.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:a.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}Sc(Qi);return zu(Qi);})();
|
|
7
|
+
${t??""}`,[y,g]=(0,_.useState)(null),h=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=y?.key===f?y:null;(0,_.useLayoutEffect)(()=>{h.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let b=V({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let R=await C("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),M=R.content?.items??R.items??[],N=M[0]?_e(M[0]):null;if(!N)return null;let T=(await cr(N.path)).some(F=>F.item_type==="file"&&!!F.type_data?.file_ref);return{asset:N,hasBytes:T}},enabled:!!(t&&p&&m&&!s),refetchInterval:R=>h.current.key===f&&h.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let R=b.data;if(!R||h.current.key!==f)return;let M=h.current.found,N={key:f,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(M?.itemId===R.asset.id&&M.hasBytes)};h.current.found=N,g(N)},[b.data,f]);let E=!!(t&&u)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!E||!u))return Sn(u,["asset.materialized","content.written"])},[E,u]),(0,_.useEffect)(()=>{if(!E||!t||!u)return;let R=f,M=k=>k?.payload??k,N=k=>{let U=M(k)?.scope_id??k?.scope_id;return typeof U=="string"?U:void 0},S=k=>{let U=M(k)?.item_path??k?.item_path;return typeof U=="string"&&U?U:void 0},T=(k,A)=>{let U=A.replace(/\/+$/,"");return k===U||k.startsWith(`${U}/`)},F=[ne("asset.materialized",k=>{if(h.current.key!==R)return;let A=M(k);if(typeof A?.item_id!="string"||!A.item_id)return;let U=h.current.found,Q=typeof A.item_path=="string"?A.item_path:void 0,ue=!!A.has_bytes||!!(Q&&Array.from(h.current.earlyContentPaths).some(qe=>T(qe,Q)))||!!(U&&U.itemId===A.item_id&&U.hasBytes),B={key:R,itemId:A.item_id,itemPath:Q,displayName:typeof A.display_name=="string"?A.display_name:void 0,hasBytes:ue};h.current.found=B,g(B)},k=>{let A=N(k);return(!A||A===u)&&M(k)?.origin===t}),ne("content.written",k=>{if(h.current.key!==R)return;let A=S(k);if(!A)return;let U=h.current.found;if(!U?.itemPath||!T(A,U.itemPath)){if(h.current.earlyContentPaths.add(A),h.current.earlyContentPaths.size>128){let ue=h.current.earlyContentPaths.values().next().value;ue&&h.current.earlyContentPaths.delete(ue)}return}if(U.hasBytes)return;let Q={...U,hasBytes:!0};h.current.found=Q,g(Q)},k=>{let A=N(k);return(!A||A===u)&&!!S(k)})];return()=>F.forEach(k=>k())},[E,t,u,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Zc(e,t){let n=O().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function eu(e,t){let n=(0,An.useSyncExternalStore)(we,Z,Z),r=ye(),s=H(),i=r?.kind==="space",o=In(i&&s?{key:e,scope_id:r.id}:null),c=(0,An.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),g=f.filter(v=>!y.has(v.id)),h=v=>Date.parse(v.createdAt??"")||0;return g.sort((v,b)=>h(b)-h(v)),[...g,...f.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),a=$(),u=(0,An.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=de({mutationFn:async f=>{let y=await C("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,g)=>Ze(a,g.queryKey)});async function m(f){if(!d||!s||n!==Z()||H()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let y=t.map(R=>R.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(R=>!f.includes(R)))throw new Error("Order must include each displayed item exactly once");let g=a.getQueryData(o.arrangementQueryKey);if(g?.item_id!==o.arrangement.item_id||JSON.stringify(g?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let h=c.map(R=>R.id);if(f.every((R,M)=>h[M]===R))return;let v=new Set(y),b=0,I=[...(o.order??[]).map(R=>v.has(R)?f[b++]:R),...f.slice(b)];u.current=!0;try{return await p.mutateAsync({ids:I,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Yl=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,tu=new Map,nu=new Map,kn=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Ut(e){let t=e?At.find(n=>n.id===e):At.find(n=>n.default===!0)??(At.length===1?At[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 ys(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 Xl(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Zl(e,t){if(!Xl(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Ii(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function ed(e){try{let t=Ii(e)?.getItem(e.key)??void 0;return t&&Ei.test(t)?t:void 0}catch{return}}function ru(e,t){try{Ii(e)?.setItem(e.key,t)}catch{}}function su(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=ed(t)??tu.get(e.id);if(n)return n;let r=crypto.randomUUID();return tu.set(e.id,r),ru(t,r),r}function iu(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 u=Ii(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=nu.get(e.id),i=r&&typeof r.id=="string"&&Ei.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return nu.set(e.id,a),ru(n,JSON.stringify(a)),a.id}function td(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(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function Nt(e,t={},n={}){let r=Ut(n.source);if(Zl(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??su(r),o=n.sessionId??iu(r);if(![s,i,o].every(h=>Ei.test(h)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=td(r,c),p=d?{...t,source_keys:d}:t,m=Ot(),f=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new kn(h instanceof Error?h.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let g=null;try{g=await y.json()}catch{}if(!y.ok||g?.success!==!0){let h=g;throw new kn(h?.message||h?.error||`Observation transport failed (${y.status})`,h?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return g}function ou(e={},t={}){let n=Ut(t.source),r=ys("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return Nt(r.observation,{...s,...e},{...t,source:n.id})}function au(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Ut(n.source),s=ys("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return Nt(s.observation,{...t,...i},{...n,source:r.id})}function cu(){try{let e=Ut();return ys("form_receipt",e),{visitor_id:su(e),session_id:iu(e),source:e.id}}catch{return}}function nd(e,t={}){let n=Ut(t.source),r=ys("form_receipt",n);return Nt(r.observation,e,{...t,source:n.id})}async function rd(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function uu(e,t,n,r,s){let i=At.filter(o=>o.adapters?.some(c=>c.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let c=o.id===r?.source;return nd(e,{source:o.id,eventId:c?t:await rd(t,o.id),pageUrl:n,signal:s,keepalive:!0,...c?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var gr;function _s(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(gr)return gr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[Ut(e.source)]:At.map(m=>Ut(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="page_view").map(f=>({source:m,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(f=>f.type==="declared_action").map(f=>({source:m,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:f}of n){let y=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};Nt(f.observation,y,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:f,adapter:y}of r){let g=y.attribute;if(!g||!Yl.test(g))continue;let h=m.target.closest(`[${g}]`);if(!h)continue;let v=h.getAttribute(g)?.trim();if(!v||v.length>128)continue;let b={};y.id_property&&(b[y.id_property]=v),y.element_property&&(b[y.element_property]=h.tagName.toLowerCase()),Nt(y.observation,b,{source:f.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:m})=>m.history===!0),p=n.some(({adapter:m})=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),u()},window.history.replaceState=function(...f){a.apply(this,f),u()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),gr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),gr=void 0},gr}var Mn;te(()=>{Mn=void 0});function vs(e){if(Mn)return Mn.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):Mn.promise;let t=se(),n=()=>{if(t!==se())throw new Error("Workspace session changed")},r=(async()=>{let s=await Xe();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await O().fetchQuery({queryKey:P.memberships(s.principal_id),queryFn:cs,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=Ve(o),u=Ve(c),d=fe();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||Mt(a,{activate:!1}),await Dt(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?Ve(m):null},{initialAnchor:u}),n(),{home:a,defaultSpace:u,memberships:i}})().catch(s=>{throw t===se()&&(Mn=void 0),s});return Mn={accountPath:e.accountPath,promise:r},r}var Kt,_r,yr;te(()=>{_r?.(),_r=void 0,Kt=void 0,yr=void 0});function lu(e={}){if(Kt)return e.workspace&&e.workspace.accountPath!==yr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Kt;yr=e.workspace?.accountPath;let t=se();return Kt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:_s(typeof n=="object"?n:{});_r=r;try{let s=e.session===!1?null:await Xe(),i=e.workspace?await vs(e.workspace):void 0;if(t!==se())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===se()&&(Kt=void 0,yr=void 0,_r=void 0))}}}catch(s){throw r(),t===se()&&(Kt=void 0,yr=void 0,_r=void 0),s}})(),Kt}async function Ai(e){try{return await C("execution-control-transition",e)}catch(t){if(!(t instanceof Ie)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),C("execution-control-transition",e)}}function ki(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 du(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 Ai({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 ki(i?{...s,state:i}:s)}async function fu(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 Ai({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return ki(c?{...o,state:c}:o)}async function pu(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 Ai({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 ki(i?{...s,outcome:i}:s)}var sd=/^[a-z][a-z0-9_-]{0,63}$/,id=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function mu(e,t,n={}){if(!sd.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(!id.test(r))throw new TypeError("fillId must be a UUID");let s=Ot(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=cu(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new On(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await u.json()}catch{}if(!u.ok||d?.success!==!0){let p=d;throw new On(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await uu({fill_id:r,action_id:e,release_id:d.release_id},r,i,c,n.signal),d}var Mi=X(oe(),1),yu=X(gu(),1);function _u(e){return C("read",{path:e})}function vu(e,t){return C("list",{path:e,...t})}function bu(e){return C("create",e)}function wu(e){return C("update",e)}function Su(e){return C("create",e)}function Ru(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return C("tools/call",{name:e,instance_path:r,...t||{}})}function xu(e,t,n){return C("signal",{target_id:e,event_name:t,payload:n||{}})}function Cu(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Pu={signIn:e=>e.provider?W.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):W.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>W.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await W.auth.signOut(),mn(),O().clear()},getSession:()=>W.auth.getSession().then(e=>e.data.session),getUser:()=>W.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=W.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>W.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>W.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Tu(){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,yu.createRoot)(e).render((0,Mi.createElement)(Gn,{client:O()},(0,Mi.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 Eu(){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}function od(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ad(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function cd(e,t){return!(e==="object"||e==="array")}function ud(e){return["string","number","integer","boolean"].includes(e)}function ld(e){return e!=="object"&&e!=="array"}function Iu(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",u=c.enum,d=cd(a,u),p=ud(a),m=ad(a,u);i.push({key:o,label:c.title||od(o),type:a,description:c.description,enum_values:u,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function Oi(e){let t=e.default_data||{},n=e.field_defaults||{},r=Iu(e.input_schema,!0,t,n),s=Iu(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>ld(u.type)),c=i.filter(u=>u.filterable),a=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function Au(e){return{field:"updated_at",direction:"desc"}}function ku(e){let t=Oi(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ve=X(oe(),1);var dd=0;function fd(){return`upload_${Date.now()}_${++dd}`}async function Mu(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",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let u=await C("create",c);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,p=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:p,fileRef:u.file_ref};let m=u.storage_key,f=u.upload_token,y=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await pd(y,m,f,e,i,n,r);let g=await Ou(d,m,i);return{itemId:d,itemPath:p,fileRef:g}}function pd(e,t,n,r,s,i,o){return new Promise((c,a)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},u.onload=()=>{u.status>=200&&u.status<300?c():a(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>a(new Error("Storage upload network error")),u.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),a(new Error("Upload cancelled"))})}u.send(r)})}async function Ou(e,t,n){let r=await Ye(),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 Fu(){let[e,t]=(0,ve.useState)([]),n=$(),r=(0,ve.useRef)(e);r.current=e;let s=(0,ve.useCallback)((g,h)=>{t(v=>v.map(b=>b.id===g?{...b,...h}:b))},[]),i=(0,ve.useCallback)(g=>{t(h=>[...h,g])},[]),o=(0,ve.useCallback)(async(g,h,v,b,E)=>{let I=v.name||h.name,R=h.type||"application/octet-stream",M=v.itemType||"file",N=E?.itemId||null,S=E?.itemPath||null,T=E?.storageKey||null,F=E?.uploadToken||null,k=E?.storageWorkerUrl||null;try{if(!b||b==="create"){s(g,{status:"creating",error:null,_failedAt:null});let Q=await C("create",{parent_path:v.parentPath,item_type:M,name:I,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:R}}});if(!Q.id)throw Object.assign(new Error(Q.error||Q.message||"Failed to create file item"),{_step:"create"});if(N=Q.id,S=Q.path,s(g,{itemId:N,itemPath:S}),Q.storage_completed&&Q.file_ref){s(g,{status:"complete",progress:100,fileRef:Q.file_ref}),n.invalidateQueries({queryKey:P.children(v.parentPath)});return}if(T=Q.storage_key,F=Q.upload_token||"",k=Q.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(g,{_storageKey:T,_uploadToken:F,_storageWorkerUrl:k}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!b||b==="create"||b==="upload")&&(s(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((Q,ue)=>{let B=new XMLHttpRequest;s(g,{_xhr:B}),B.open("PUT",`${k}/upload`),B.setRequestHeader("X-Storage-Key",T),B.setRequestHeader("Content-Type",R),F&&B.setRequestHeader("X-Upload-Token",F),B.upload.onprogress=qe=>{qe.lengthComputable&&s(g,{progress:Math.round(qe.loaded/qe.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?Q():ue(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>ue(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>ue(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(h)}),s(g,{progress:100,_xhr:null})),s(g,{status:"confirming",error:null,_failedAt:null});let A=await Ou(N,T,R);s(g,{status:"complete",fileRef:A}),n.invalidateQueries({queryKey:P.children(v.parentPath)})}catch(A){let U=A?.message||String(A),Q=A?._step||"create";s(g,{status:"error",error:U,_failedAt:Q,_xhr:null})}},[s,n]),c=(0,ve.useCallback)((g,h)=>{let v=fd();i({id:v,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(v,g,h)},[i,o]),a=(0,ve.useCallback)((g,h)=>{for(let v of g)c(v,h)},[c]),u=(0,ve.useCallback)(g=>{let h=r.current.find(E=>E.id===g);if(!h||h.status!=="error")return;let v=h._failedAt||"create",b=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,v,b)},[o]),d=(0,ve.useCallback)(g=>{let h=r.current.find(v=>v.id===g);h&&(h._xhr&&h._xhr.abort(),s(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ve.useCallback)(g=>{t(h=>h.filter(v=>v.id!==g))},[]),m=(0,ve.useCallback)(()=>{t(g=>g.filter(h=>h.status!=="complete"))},[]),f=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),y=e.map(({_storageKey:g,_uploadToken:h,_storageWorkerUrl:v,_xhr:b,_failedAt:E,...I})=>I);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:u,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var qu=X(oe(),1);async function Fi(e,t){return await C("resolve-items",{context_id:e,item_type:t})}function Qu(e,t){return(0,qu.useSyncExternalStore)(we,Z,Z),V({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Fi(e,t),enabled:!!(e&&t)})}var Fe=X(oe(),1);function bs(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{a=JSON.parse(u)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return zr(e,s)}function Du(e,t=!0){let[n,r]=(0,Fe.useState)(new Map),[s,i]=(0,Fe.useState)([]),o=(0,Fe.useRef)({artifacts:new Map,timeline:[]});(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Fe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,u=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:u,reset:c}}function Uu(e,t=!0){let[n,r]=(0,Fe.useState)([]);(0,Fe.useEffect)(()=>!e||!t?void 0:bs(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ws=X(oe(),1);function md(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function qi(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 c=(await C("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(hd).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Nu(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=$(),u=(0,ws.useRef)(null),d=c?md(c,n,r,s):["vfs","timeline-history","__disabled__"],p=V({queryKey:d,queryFn:()=>qi(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ws.useEffect)(()=>{if(!c||!i)return;let m=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c&&f.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function hd(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 Ss=X(oe(),1);function Ku(){(0,Ss.useSyncExternalStore)(we,Z,Z);let e=H(),t=ye(),n=In(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=$(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=de({mutationFn:async a=>{let u,d={_scope_path:a.scopePath};if(a.operation==="pin"?u=await C("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?u=await C("delete",{...d,id:a.entry.id}):u=await C("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(a,u,d)=>Ze(r,d.queryKey)}),c=(0,Ss.useCallback)(a=>!i||!e||H()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(u=>u.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(u=>!a.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,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:a=>s.some(u=>u.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return u?c({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}var Rs=X(oe(),1);var vr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Qi(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Di(e,t,n,r){let s=await C("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function Lu(e,t){let n=await Di(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=O();return r.setQueryData(vr(e.scopePath,e.contextId,e.collection),s=>Qi(s,n)),ju(r,e.scopePath),n}function ju(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ze(e,n.queryKey)}function Vu(e,t){let n=(0,Rs.useSyncExternalStore)(we,Z,Z),r=H(),s=$(),i=vr(r,e,t),o=V({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Di(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,m)=>Qi(p,m)}),c=(0,Rs.useRef)(!1),a=de({mutationFn:async p=>{let m=await Di(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(vr(p.scope,p.context,p.collection),f=>Qi(f,m)),m},onSettled:(p,m,f)=>ju(s,f.scope)});async function u(p){if(!r||!e||n!==Z()||H()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(c.current)throw new Error("A section change is still being saved");c.current=!0;try{return await a.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{c.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(m=>m.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:a.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}Ec(Ui);return tl(Ui);})();
|
|
8
8
|
|
|
9
9
|
/* ── Auto-setup: require shim + mount + backward compat globals ── */
|
|
10
10
|
(function() {
|