@ai4b-team/fsaos-gateway-sdk 3.7.0 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/iife/gateway.js +3 -3
- package/dist/iife/gateway.js.map +3 -3
- package/dist/iife/ui.js +1 -1
- package/dist/index.cjs +78 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -2
- package/dist/index.d.ts +53 -2
- package/dist/index.js +78 -19
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/iife/gateway.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-06-
|
|
2
|
-
"use strict";var __FSAOS_GATEWAY__=(()=>{var Eo=Object.create;var At=Object.defineProperty;var xo=Object.getOwnPropertyDescriptor;var To=Object.getOwnPropertyNames;var Oo=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Gs=t=>{throw TypeError(t)};var Io=(t,e,n)=>e in t?At(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mo=(t,e)=>{for(var n in e)At(t,n,{get:e[n],enumerable:!0})},zs=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of To(e))!Fo.call(t,r)&&r!==n&&At(t,r,{get:()=>e[r],enumerable:!(s=xo(e,r))||s.enumerable});return t};var G=(t,e,n)=>(n=t!=null?Eo(Oo(t)):{},zs(e||!t||!t.__esModule?At(n,"default",{value:t,enumerable:!0}):n,t)),ko=t=>zs(At({},"__esModule",{value:!0}),t);var Dt=(t,e,n)=>Io(t,typeof e!="symbol"?e+"":e,n),is=(t,e,n)=>e.has(t)||Gs("Cannot "+n);var o=(t,e,n)=>(is(t,e,"read from private field"),n?n.call(t):e.get(t)),b=(t,e,n)=>e.has(t)?Gs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),y=(t,e,n,s)=>(is(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),R=(t,e,n)=>(is(t,e,"access private method"),n);var Ut=(t,e,n,s)=>({set _(r){y(t,e,r,n)},get _(){return o(t,e,s)}});var Ys=qt((xa,Js)=>{Js.exports={createClient:window.supabase.createClient}});var be=qt((Iu,qr)=>{qr.exports=React});var An=qt((Mu,Dr)=>{Dr.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var di=qt((El,li)=>{li.exports=ReactDOM});var Pi=qt((kl,Ri)=>{Ri.exports=ReactDOM});var $s={};Mo($s,{ComponentRenderer:()=>no,EnforcementDeniedError:()=>rt,KernelProvider:()=>so,QueryClientProvider:()=>Zt,auth:()=>wi,awaitScopeReady:()=>wn,callTool:()=>_i,clearCachedToken:()=>cs,clearSession:()=>fs,createItem:()=>mi,disconnectSSE:()=>Ks,disposeVfsRealtimeWs:()=>es,emitEvent:()=>ci,fetchChannelMessages:()=>Yr,fetchChannelMessagesPage:()=>on,fetchChannelMessagesWithCards:()=>zn,fetchEdgesForItem:()=>Vn,fetchItemHistory:()=>Hn,fetchItemVersions:()=>sn,fetchItems:()=>rn,fetchMemberFocus:()=>$n,fetchOpenEnvelope:()=>Gn,fetchRecentActivity:()=>Wn,fetchTypeDefinitions:()=>jn,fetchVfsChildren:()=>Kn,fetchVfsChildrenPage:()=>Ln,fetchVfsItem:()=>Nn,fetchVfsItemById:()=>Qn,fetchVfsTree:()=>Bn,gatewayCall:()=>P,getAccessToken:()=>we,getAssetUrl:()=>bi,getDefaultSort:()=>bo,getRequiredFormFields:()=>wo,getScope:()=>ae,getScopeVersion:()=>Lt,getSessionEntry:()=>Rn,initSession:()=>Cn,initVfsRealtimeWs:()=>fn,interpretSchema:()=>Hs,invalidateAllVfs:()=>ei,invalidateChannelMessages:()=>ni,invalidateChildren:()=>Un,invalidateItem:()=>Qs,invalidateOpenEnvelope:()=>si,invalidatePathAndParent:()=>Xr,invalidateSubtree:()=>Zr,invalidateTypes:()=>ti,isScopeReady:()=>Sn,listChildren:()=>hi,mount:()=>Si,mountRealtimeScope:()=>pn,normalizeItem:()=>le,ping:()=>ui,pushChanges:()=>yi,queryClient:()=>O,readItem:()=>pi,registerCleanup:()=>Se,resetAllSdkState:()=>ot,resolvePrincipalId:()=>Bs,setCachedToken:()=>er,setScope:()=>Kt,setupRequireShim:()=>Ci,signal:()=>vi,subscribeScope:()=>bn,subscribeToEvents:()=>oe,subscribeToPath:()=>ai,subscribeToScope:()=>Yn,unmountRealtimeScope:()=>Zn,updateItem:()=>gi,uploadFile:()=>So,useAccounts:()=>$i,useAllChannels:()=>ss,useArrangement:()=>_o,useAsset:()=>Gi,useAuth:()=>ns,useChannelMessages:()=>ro,useChannels:()=>oo,useChildren:()=>Ii,useComponent:()=>Vs,useCreate:()=>uo,useDelete:()=>fo,useDmChannels:()=>ao,useEdges:()=>Qi,useEventStream:()=>go,useFileUpload:()=>Ro,useInfiniteChannelMessages:()=>io,useInfiniteChildren:()=>Ui,useInfiniteItems:()=>Di,useItem:()=>Oi,useItemById:()=>Fi,useItemHistory:()=>Bi,useItemVersions:()=>Vi,useItems:()=>qi,useLink:()=>ho,useList:()=>js,useMemberFocus:()=>ji,useMove:()=>po,useMutation:()=>mo,useNotifications:()=>Ws,useOpen:()=>Ki,usePermission:()=>Xi,usePermissions:()=>Zi,usePrincipal:()=>eo,useRealtimeQuery:()=>yo,useRecentActivity:()=>Wi,useResolve:()=>Ai,useScope:()=>Hi,useScopeReady:()=>Ti,useSearch:()=>ki,useTheme:()=>Yi,useTool:()=>to,useTree:()=>Mi,useType:()=>Ni,useTypeHelpers:()=>Li,useTypes:()=>ts,useUnreadCounts:()=>co,useUpdate:()=>lo,vfsKeys:()=>w});var rt=class t extends Error{constructor(n){let s=n.message||t.fallbackMessage(n);super(s);Dt(this,"name","EnforcementDeniedError");Dt(this,"deniedBy");Dt(this,"ruleKey");Dt(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let r=n.enforcement;this.ruleKey=r?.rule_key??void 0,this.displayName=r?.display_name??void 0}static fallbackMessage(n){let s=n.error||"",r=n.denied_by||"";return r==="rule"||s==="RULE_DENIED"?"This feature is not enabled for this workspace.":r==="entitlement"||s==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":r==="access"||s==="ACCESS_DENIED"||s==="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 Xs=G(Ys(),1),os=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Ao=os.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",qo=os.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ie=os.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,Xs.createClient)(Ao,qo,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Nt=null,mn=0,Zs,as,gn=!1;Zs=new Promise(t=>{as=t});k.auth.onAuthStateChange((t,e)=>{e?.access_token?(Nt=e.access_token,mn=e.expires_at??Math.floor(Date.now()/1e3)+3600):(Nt=null,mn=0),gn||(gn=!0,as())});setTimeout(()=>{gn||(gn=!0,as())},5e3);function er(t,e){Nt=t,mn=e??Math.floor(Date.now()/1e3)+3600}function cs(){Nt=null,mn=0}async function we(){return await Zs,Nt}var yn=null,us=0,_n=new Set,ls,ds,vn=!1;ls=new Promise(t=>{ds=t});function Kt(t){let e=yn!==t;yn=t,vn||(vn=!0,ds()),e&&(us++,_n.forEach(n=>{try{n()}catch(s){console.warn("[SDK] Scope listener error:",s)}}))}function ae(){return yn}function Lt(){return us}function bn(t){return _n.add(t),()=>{_n.delete(t)}}function wn(){return ls}function Sn(){return vn}var it=null,Qt=null;async function Cn(){return it||Qt||(Qt=(async()=>{let t=ps(),e=await we(),n={};e&&(n.Authorization=`Bearer ${e}`);let s=await fetch(`${Ie}/d/${t}/init`,{method:"GET",headers:n});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let r=await s.json(),i=r.entry||r;return it={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},it})(),Qt)}function Rn(){return it}function fs(){it=null,Qt=null,yn=null}var tr=[];function Se(t){tr.push(t)}function ot(){fs(),cs(),vn=!1,ls=new Promise(t=>{ds=t}),us++,_n.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Scope listener error:",e)}});for(let t of tr)try{t()}catch(e){console.warn("[SDK] Cleanup function failed:",e)}}function ps(){if(typeof window<"u"){let t=window.__FSAOS_CONFIG__;return t?.hostname?t.hostname:window.location.hostname}return"localhost"}var Do=new Set(["list-memberships","init"]);async function P(t,e={}){let n=ps(),s=`${Ie}/d/${n}`,r={"Content-Type":"application/json"},i=await we();i&&(r.Authorization=`Bearer ${i}`),!Do.has(t)&&!e._scope_path&&await wn();let a={...e},c=Rn();!a.domain_scope_id&&c?.scope_id&&(a.domain_scope_id=c.scope_id);let u=ae();!a._scope_path&&u&&(a._scope_path=u);let l=await fetch(s,{method:"POST",headers:r,body:JSON.stringify({method:t,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let f=await l.json();if(f.success===!1){let h=f.error||"",g=f.denied_by||f.error_type||"";throw g==="rule"||g==="access"||g==="entitlement"||h==="RULE_DENIED"||h==="ACCESS_DENIED"||h==="PERMISSION_DENIED"||h==="ENTITLEMENT_REQUIRED"?new rt(f):new Error(f.message||f.error||`Gateway call ${t} failed`)}return f}var re=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var We,Me,at,nr,Uo=(nr=class extends re{constructor(){super();b(this,We);b(this,Me);b(this,at);y(this,at,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Me)||this.setEventListener(o(this,at))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Me))==null||e.call(this),y(this,Me,void 0))}setEventListener(e){var n;y(this,at,e),(n=o(this,Me))==null||n.call(this),y(this,Me,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){o(this,We)!==e&&(y(this,We,e),this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){return typeof o(this,We)=="boolean"?o(this,We):globalThis.document?.visibilityState!=="hidden"}},We=new WeakMap,Me=new WeakMap,at=new WeakMap,nr),ct=new Uo;var Qo={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},ke,hs,sr,No=(sr=class{constructor(){b(this,ke,Qo);b(this,hs,!1)}setTimeoutProvider(t){y(this,ke,t)}setTimeout(t,e){return o(this,ke).setTimeout(t,e)}clearTimeout(t){o(this,ke).clearTimeout(t)}setInterval(t,e){return o(this,ke).setInterval(t,e)}clearInterval(t){o(this,ke).clearInterval(t)}},ke=new WeakMap,hs=new WeakMap,sr),he=new No;function rr(t){setTimeout(t,0)}var gs=typeof window>"u"||"Deno"in globalThis;function A(){}function ar(t,e){return typeof t=="function"?t(e):t}function jt(t){return typeof t=="number"&&t>=0&&t!==1/0}function Pn(t,e){return Math.max(t+(e||0)-Date.now(),0)}function ce(t,e){return typeof t=="function"?t(e):t}function Y(t,e){return typeof t=="function"?t(e):t}function En(t,e){let{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==Vt(a,e.options))return!1}else if(!He(e.queryKey,a))return!1}if(n!=="all"){let u=e.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||r&&r!==e.state.fetchStatus||i&&!i(e))}function xn(t,e){let{exact:n,status:s,predicate:r,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(me(e.options.mutationKey)!==me(i))return!1}else if(!He(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||r&&!r(e))}function Vt(t,e){return(e?.queryKeyHashFn||me)(t)}function me(t){return JSON.stringify(t,(e,n)=>ms(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function He(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>He(t[n],e[n])):!1}var Ko=Object.prototype.hasOwnProperty;function ys(t,e,n=0){if(t===e)return t;if(n>500)return e;let s=ir(t)&&ir(e);if(!s&&!(ms(t)&&ms(e)))return e;let i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},l=0;for(let f=0;f<c;f++){let h=s?f:a[f],g=t[h],d=e[h];if(g===d){u[h]=g,(s?f<i:Ko.call(t,h))&&l++;continue}if(g===null||d===null||typeof g!="object"||typeof d!="object"){u[h]=d;continue}let v=ys(g,d,n+1);u[h]=v,v===g&&l++}return i===c&&l===i?t:u}function ut(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let n in t)if(t[n]!==e[n])return!1;return!0}function ir(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function ms(t){if(!or(t))return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(!or(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function or(t){return Object.prototype.toString.call(t)==="[object Object]"}function cr(t){return new Promise(e=>{he.setTimeout(e,t)})}function Bt(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?ys(t,e):e}function ur(t,e,n=0){let s=[...t,e];return n&&s.length>n?s.slice(1):s}function lr(t,e,n=0){let s=[e,...t];return n&&s.length>n?s.slice(0,-1):s}var lt=Symbol();function Tn(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===lt?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function dt(t,e){return typeof t=="function"?t(...e):!!t}function dr(t,e,n){let s=!1,r;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(r??(r=e()),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),t}var ge=(()=>{let t=()=>gs;return{isServer(){return t()},setIsServer(e){t=e}}})();function Wt(){let t,e,n=new Promise((r,i)=>{t=r,e=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),t(r)},n.reject=r=>{s({status:"rejected",reason:r}),e(r)},n}var fr=rr;function Lo(){let t=[],e=0,n=c=>{c()},s=c=>{c()},r=fr,i=c=>{e?t.push(c):r(()=>{n(c)})},a=()=>{let c=t;t=[],c.length&&r(()=>{s(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},batchCalls:c=>(...u)=>{i(()=>{c(...u)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{s=c},setScheduler:c=>{r=c}}}var M=Lo();var ft,Ae,pt,pr,jo=(pr=class extends re{constructor(){super();b(this,ft,!0);b(this,Ae);b(this,pt);y(this,pt,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",s)}}})}onSubscribe(){o(this,Ae)||this.setEventListener(o(this,pt))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Ae))==null||e.call(this),y(this,Ae,void 0))}setEventListener(e){var n;y(this,pt,e),(n=o(this,Ae))==null||n.call(this),y(this,Ae,e(this.setOnline.bind(this)))}setOnline(e){o(this,ft)!==e&&(y(this,ft,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return o(this,ft)}},ft=new WeakMap,Ae=new WeakMap,pt=new WeakMap,pr),ht=new jo;function Vo(t){return Math.min(1e3*2**t,3e4)}function _s(t){return(t??"online")==="online"?ht.isOnline():!0}var On=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Fn(t){let e=!1,n=0,s,r=Wt(),i=()=>r.status!=="pending",a=p=>{if(!i()){let m=new On(p);g(m),t.onCancel?.(m)}},c=()=>{e=!0},u=()=>{e=!1},l=()=>ct.isFocused()&&(t.networkMode==="always"||ht.isOnline())&&t.canRun(),f=()=>_s(t.networkMode)&&t.canRun(),h=p=>{i()||(s?.(),r.resolve(p))},g=p=>{i()||(s?.(),r.reject(p))},d=()=>new Promise(p=>{s=m=>{(i()||l())&&p(m)},t.onPause?.()}).then(()=>{s=void 0,i()||t.onContinue?.()}),v=()=>{if(i())return;let p,m=n===0?t.initialPromise:void 0;try{p=m??t.fn()}catch(S){p=Promise.reject(S)}Promise.resolve(p).then(h).catch(S=>{if(i())return;let C=t.retry??(ge.isServer()?0:3),E=t.retryDelay??Vo,U=typeof E=="function"?E(n,S):E,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(e||!L){g(S);return}n++,t.onFail?.(n,S),cr(U).then(()=>l()?void 0:d()).then(()=>{e?g(S):v()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(s?.(),r),cancelRetry:c,continueRetry:u,canStart:f,start:()=>(f()?v():d().then(v),r)}}var $e,hr,In=(hr=class{constructor(){b(this,$e)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),jt(this.gcTime)&&y(this,$e,he.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(ge.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,$e)!==void 0&&(he.clearTimeout(o(this,$e)),y(this,$e,void 0))}},$e=new WeakMap,hr);var Ge,mt,ie,ze,j,Ht,Je,se,vr,Ce,yr,_r=(yr=class extends In{constructor(e){super();b(this,se);b(this,Ge);b(this,mt);b(this,ie);b(this,ze);b(this,j);b(this,Ht);b(this,Je);y(this,Je,!1),y(this,Ht,e.defaultOptions),this.setOptions(e.options),this.observers=[],y(this,ze,e.client),y(this,ie,o(this,ze).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,y(this,Ge,gr(this.options)),this.state=e.state??o(this,Ge),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,j)?.promise}setOptions(e){if(this.options={...o(this,Ht),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=gr(this.options);n.data!==void 0&&(this.setState(mr(n.data,n.dataUpdatedAt)),y(this,Ge,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,ie).remove(this)}setData(e,n){let s=Bt(this.state.data,e,this.options);return R(this,se,Ce).call(this,{data:s,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),s}setState(e,n){R(this,se,Ce).call(this,{type:"setState",state:e,setStateOptions:n})}cancel(e){let n=o(this,j)?.promise;return o(this,j)?.cancel(e),n?n.then(A).catch(A):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,Ge)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ce(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Pn(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),o(this,ie).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(o(this,j)&&(o(this,Je)||R(this,se,vr).call(this)?o(this,j).cancel({revert:!0}):o(this,j).cancelRetry()),this.scheduleGc()),o(this,ie).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||R(this,se,Ce).call(this,{type:"invalidate"})}async fetch(e,n){if(this.state.fetchStatus!=="idle"&&o(this,j)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,j))return o(this,j).continueRetry(),o(this,j).promise}if(e&&this.setOptions(e),!this.options.queryFn){let u=this.observers.find(l=>l.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(y(this,Je,!0),s.signal)})},i=()=>{let u=Tn(this.options,n),f=(()=>{let h={client:o(this,ze),queryKey:this.queryKey,meta:this.meta};return r(h),h})();return y(this,Je,!1),this.options.persister?this.options.persister(u,f,this):u(f)},c=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,ze),state:this.state,fetchFn:i};return r(u),u})();this.options.behavior?.onFetch(c,this),y(this,mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&R(this,se,Ce).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),y(this,j,Fn({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:u=>{u instanceof On&&u.revert&&this.setState({...o(this,mt),fetchStatus:"idle"}),s.abort()},onFail:(u,l)=>{R(this,se,Ce).call(this,{type:"failed",failureCount:u,error:l})},onPause:()=>{R(this,se,Ce).call(this,{type:"pause"})},onContinue:()=>{R(this,se,Ce).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let u=await o(this,j).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),o(this,ie).config.onSuccess?.(u,this),o(this,ie).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof On){if(u.silent)return o(this,j).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw R(this,se,Ce).call(this,{type:"error",error:u}),o(this,ie).config.onError?.(u,this),o(this,ie).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},Ge=new WeakMap,mt=new WeakMap,ie=new WeakMap,ze=new WeakMap,j=new WeakMap,Ht=new WeakMap,Je=new WeakMap,se=new WeakSet,vr=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ce=function(e){let n=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...vs(s.data,this.options),fetchMeta:e.meta??null};case"success":let r={...s,...mr(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return y(this,mt,e.manual?r:void 0),r;case"error":let i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=n(this.state),M.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),o(this,ie).notify({query:this,type:"updated",action:e})})},yr);function vs(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_s(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function mr(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function gr(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,s=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var X,x,Gt,z,Ye,gt,Re,qe,zt,yt,_t,Xe,Ze,De,vt,F,$t,bs,ws,Ss,Cs,Rs,Ps,Es,Cr,Sr,Jt=(Sr=class extends re{constructor(e,n){super();b(this,F);b(this,X);b(this,x);b(this,Gt);b(this,z);b(this,Ye);b(this,gt);b(this,Re);b(this,qe);b(this,zt);b(this,yt);b(this,_t);b(this,Xe);b(this,Ze);b(this,De);b(this,vt,new Set);this.options=n,y(this,X,e),y(this,qe,null),y(this,Re,Wt()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,x).addObserver(this),br(o(this,x),this.options)?R(this,F,$t).call(this):this.updateResult(),R(this,F,Cs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return xs(o(this,x),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return xs(o(this,x),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,R(this,F,Rs).call(this),R(this,F,Ps).call(this),o(this,x).removeObserver(this)}setOptions(e){let n=this.options,s=o(this,x);if(this.options=o(this,X).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Y(this.options.enabled,o(this,x))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");R(this,F,Es).call(this),o(this,x).setOptions(this.options),n._defaulted&&!ut(this.options,n)&&o(this,X).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,x),observer:this});let r=this.hasListeners();r&&wr(o(this,x),s,this.options,n)&&R(this,F,$t).call(this),this.updateResult(),r&&(o(this,x)!==s||Y(this.options.enabled,o(this,x))!==Y(n.enabled,o(this,x))||ce(this.options.staleTime,o(this,x))!==ce(n.staleTime,o(this,x)))&&R(this,F,bs).call(this);let i=R(this,F,ws).call(this);r&&(o(this,x)!==s||Y(this.options.enabled,o(this,x))!==Y(n.enabled,o(this,x))||i!==o(this,De))&&R(this,F,Ss).call(this,i)}getOptimisticResult(e){let n=o(this,X).getQueryCache().build(o(this,X),e),s=this.createResult(n,e);return Wo(this,s)&&(y(this,z,s),y(this,gt,this.options),y(this,Ye,o(this,x).state)),s}getCurrentResult(){return o(this,z)}trackResult(e,n){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),n?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Re).status==="pending"&&o(this,Re).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){o(this,vt).add(e)}getCurrentQuery(){return o(this,x)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let n=o(this,X).defaultQueryOptions(e),s=o(this,X).getQueryCache().build(o(this,X),n);return s.fetch().then(()=>this.createResult(s,n))}fetch(e){return R(this,F,$t).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(e,n){let s=o(this,x),r=this.options,i=o(this,z),a=o(this,Ye),c=o(this,gt),l=e!==s?e.state:o(this,Gt),{state:f}=e,h={...f},g=!1,d;if(n._optimisticResults){let Q=this.hasListeners(),J=!Q&&br(e,n),de=Q&&wr(e,s,n,r);(J||de)&&(h={...h,...vs(f.data,e.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:v,errorUpdatedAt:p,status:m}=h;d=h.data;let S=!1;if(n.placeholderData!==void 0&&d===void 0&&m==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(o(this,_t)?.state.data,o(this,_t)):n.placeholderData,Q!==void 0&&(m="success",d=Bt(i?.data,Q,n),g=!0)}if(n.select&&d!==void 0&&!S)if(i&&d===a?.data&&n.select===o(this,zt))d=o(this,yt);else try{y(this,zt,n.select),d=n.select(d),d=Bt(i?.data,d,n),y(this,yt,d),y(this,qe,null)}catch(Q){y(this,qe,Q)}o(this,qe)&&(v=o(this,qe),d=o(this,yt),p=Date.now(),m="error");let C=h.fetchStatus==="fetching",E=m==="pending",U=m==="error",L=E&&C,B=d!==void 0,ne={status:m,fetchStatus:h.fetchStatus,isPending:E,isSuccess:m==="success",isError:U,isInitialLoading:L,isLoading:L,data:d,dataUpdatedAt:h.dataUpdatedAt,error:v,errorUpdatedAt:p,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:U&&!B,isPaused:h.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:U&&B,isStale:Ts(e,n),refetch:this.refetch,promise:o(this,Re),isEnabled:Y(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let Q=ne.data!==void 0,J=ne.status==="error"&&!Q,de=T=>{J?T.reject(ne.error):Q&&T.resolve(ne.data)},fe=()=>{let T=y(this,Re,ne.promise=Wt());de(T)},pe=o(this,Re);switch(pe.status){case"pending":e.queryHash===s.queryHash&&de(pe);break;case"fulfilled":(J||ne.data!==pe.value)&&fe();break;case"rejected":(!J||ne.error!==pe.reason)&&fe();break}}return ne}updateResult(){let e=o(this,z),n=this.createResult(o(this,x),this.options);if(y(this,Ye,o(this,x).state),y(this,gt,this.options),o(this,Ye).data!==void 0&&y(this,_t,o(this,x)),ut(n,e))return;y(this,z,n);let s=()=>{if(!e)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!o(this,vt).size)return!0;let a=new Set(i??o(this,vt));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(c=>{let u=c;return o(this,z)[u]!==e[u]&&a.has(u)})};R(this,F,Cr).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&R(this,F,Cs).call(this)}},X=new WeakMap,x=new WeakMap,Gt=new WeakMap,z=new WeakMap,Ye=new WeakMap,gt=new WeakMap,Re=new WeakMap,qe=new WeakMap,zt=new WeakMap,yt=new WeakMap,_t=new WeakMap,Xe=new WeakMap,Ze=new WeakMap,De=new WeakMap,vt=new WeakMap,F=new WeakSet,$t=function(e){R(this,F,Es).call(this);let n=o(this,x).fetch(this.options,e);return e?.throwOnError||(n=n.catch(A)),n},bs=function(){R(this,F,Rs).call(this);let e=ce(this.options.staleTime,o(this,x));if(ge.isServer()||o(this,z).isStale||!jt(e))return;let s=Pn(o(this,z).dataUpdatedAt,e)+1;y(this,Xe,he.setTimeout(()=>{o(this,z).isStale||this.updateResult()},s))},ws=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,x)):this.options.refetchInterval)??!1},Ss=function(e){R(this,F,Ps).call(this),y(this,De,e),!(ge.isServer()||Y(this.options.enabled,o(this,x))===!1||!jt(o(this,De))||o(this,De)===0)&&y(this,Ze,he.setInterval(()=>{(this.options.refetchIntervalInBackground||ct.isFocused())&&R(this,F,$t).call(this)},o(this,De)))},Cs=function(){R(this,F,bs).call(this),R(this,F,Ss).call(this,R(this,F,ws).call(this))},Rs=function(){o(this,Xe)!==void 0&&(he.clearTimeout(o(this,Xe)),y(this,Xe,void 0))},Ps=function(){o(this,Ze)!==void 0&&(he.clearInterval(o(this,Ze)),y(this,Ze,void 0))},Es=function(){let e=o(this,X).getQueryCache().build(o(this,X),this.options);if(e===o(this,x))return;let n=o(this,x);y(this,x,e),y(this,Gt,e.state),this.hasListeners()&&(n?.removeObserver(this),e.addObserver(this))},Cr=function(e){M.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,X).getQueryCache().notify({query:o(this,x),type:"observerResultsUpdated"})})},Sr);function Bo(t,e){return Y(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function br(t,e){return Bo(t,e)||t.state.data!==void 0&&xs(t,e,e.refetchOnMount)}function xs(t,e,n){if(Y(e.enabled,t)!==!1&&ce(e.staleTime,t)!=="static"){let s=typeof n=="function"?n(t):n;return s==="always"||s!==!1&&Ts(t,e)}return!1}function wr(t,e,n,s){return(t!==e||Y(s.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&Ts(t,n)}function Ts(t,e){return Y(e.enabled,t)!==!1&&t.isStaleByTime(ce(e.staleTime,t))}function Wo(t,e){return!ut(t.getCurrentResult(),e)}function bt(t){return{onFetch:(e,n)=>{let s=e.options,r=e.fetchOptions?.meta?.fetchMore?.direction,i=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,l=async()=>{let f=!1,h=v=>{dr(v,()=>e.signal,()=>f=!0)},g=Tn(e.options,e.fetchOptions),d=async(v,p,m)=>{if(f)return Promise.reject();if(p==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let B={client:e.client,queryKey:e.queryKey,pageParam:p,direction:m?"backward":"forward",meta:e.options.meta};return h(B),B})(),E=await g(C),{maxPages:U}=e.options,L=m?lr:ur;return{pages:L(v.pages,E,U),pageParams:L(v.pageParams,p,U)}};if(r&&i.length){let v=r==="backward",p=v?Rr:Os,m={pages:i,pageParams:a},S=p(s,m);c=await d(m,S,v)}else{let v=t??i.length;do{let p=u===0?a[0]??s.initialPageParam:Os(s,c);if(u>0&&p==null)break;c=await d(c,p),u++}while(u<v)}return c};e.options.persister?e.fetchFn=()=>e.options.persister?.(l,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=l}}}function Os(t,{pages:e,pageParams:n}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,n[s],n):void 0}function Rr(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}function Pr(t,e){return e?Os(t,e)!=null:!1}function Er(t,e){return!e||!t.getPreviousPageParam?!1:Rr(t,e)!=null}var Fs=class extends Jt{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t){super.setOptions({...t,behavior:bt()})}getOptimisticResult(t){return t.behavior=bt(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){let{state:n}=t,s=super.createResult(t,e),{isFetching:r,isRefetching:i,isError:a,isRefetchError:c}=s,u=n.fetchMeta?.fetchMore?.direction,l=a&&u==="forward",f=r&&u==="forward",h=a&&u==="backward",g=r&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Pr(e,n.data),hasPreviousPage:Er(e,n.data),isFetchNextPageError:l,isFetchingNextPage:f,isFetchPreviousPageError:h,isFetchingPreviousPage:g,isRefetchError:c&&!l&&!h,isRefetching:i&&!f&&!g}}};var Yt,ye,$,et,_e,Ue,xr,Tr=(xr=class extends In{constructor(e){super();b(this,_e);b(this,Yt);b(this,ye);b(this,$);b(this,et);y(this,Yt,e.client),this.mutationId=e.mutationId,y(this,$,e.mutationCache),y(this,ye,[]),this.state=e.state||Is(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){o(this,ye).includes(e)||(o(this,ye).push(e),this.clearGcTimeout(),o(this,$).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){y(this,ye,o(this,ye).filter(n=>n!==e)),this.scheduleGc(),o(this,$).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){o(this,ye).length||(this.state.status==="pending"?this.scheduleGc():o(this,$).remove(this))}continue(){return o(this,et)?.continue()??this.execute(this.state.variables)}async execute(e){let n=()=>{R(this,_e,Ue).call(this,{type:"continue"})},s={client:o(this,Yt),meta:this.options.meta,mutationKey:this.options.mutationKey};y(this,et,Fn({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,c)=>{R(this,_e,Ue).call(this,{type:"failed",failureCount:a,error:c})},onPause:()=>{R(this,_e,Ue).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,$).canRun(this)}));let r=this.state.status==="pending",i=!o(this,et).canStart();try{if(r)n();else{R(this,_e,Ue).call(this,{type:"pending",variables:e,isPaused:i}),o(this,$).config.onMutate&&await o(this,$).config.onMutate(e,this,s);let c=await this.options.onMutate?.(e,s);c!==this.state.context&&R(this,_e,Ue).call(this,{type:"pending",context:c,variables:e,isPaused:i})}let a=await o(this,et).start();return await o(this,$).config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await o(this,$).config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),R(this,_e,Ue).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,$).config.onError?.(a,e,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(c){Promise.reject(c)}try{await o(this,$).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(c){Promise.reject(c)}throw R(this,_e,Ue).call(this,{type:"error",error:a}),a}finally{o(this,$).runNext(this)}}},Yt=new WeakMap,ye=new WeakMap,$=new WeakMap,et=new WeakMap,_e=new WeakSet,Ue=function(e){let n=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),M.batch(()=>{o(this,ye).forEach(s=>{s.onMutationUpdate(e)}),o(this,$).notify({mutation:this,type:"updated",action:e})})},xr);function Is(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Pe,ue,Xt,Or,Fr=(Or=class extends re{constructor(e={}){super();b(this,Pe);b(this,ue);b(this,Xt);this.config=e,y(this,Pe,new Set),y(this,ue,new Map),y(this,Xt,0)}build(e,n,s){let r=new Tr({client:e,mutationCache:this,mutationId:++Ut(this,Xt)._,options:e.defaultMutationOptions(n),state:s});return this.add(r),r}add(e){o(this,Pe).add(e);let n=Mn(e);if(typeof n=="string"){let s=o(this,ue).get(n);s?s.push(e):o(this,ue).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(o(this,Pe).delete(e)){let n=Mn(e);if(typeof n=="string"){let s=o(this,ue).get(n);if(s)if(s.length>1){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&o(this,ue).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){let n=Mn(e);if(typeof n=="string"){let r=o(this,ue).get(n)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){let n=Mn(e);return typeof n=="string"?o(this,ue).get(n)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{o(this,Pe).forEach(e=>{this.notify({type:"removed",mutation:e})}),o(this,Pe).clear(),o(this,ue).clear()})}getAll(){return Array.from(o(this,Pe))}find(e){let n={exact:!0,...e};return this.getAll().find(s=>xn(n,s))}findAll(e={}){return this.getAll().filter(n=>xn(e,n))}notify(e){M.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){let e=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(e.map(n=>n.continue().catch(A))))}},Pe=new WeakMap,ue=new WeakMap,Xt=new WeakMap,Or);function Mn(t){return t.options.scope?.id}var Ee,Qe,Z,xe,Te,kn,Ms,Ir,ks=(Ir=class extends re{constructor(e,n){super();b(this,Te);b(this,Ee);b(this,Qe);b(this,Z);b(this,xe);y(this,Ee,e),this.setOptions(n),this.bindMethods(),R(this,Te,kn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let n=this.options;this.options=o(this,Ee).defaultMutationOptions(e),ut(this.options,n)||o(this,Ee).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,Z),observer:this}),n?.mutationKey&&this.options.mutationKey&&me(n.mutationKey)!==me(this.options.mutationKey)?this.reset():o(this,Z)?.state.status==="pending"&&o(this,Z).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,Z)?.removeObserver(this)}onMutationUpdate(e){R(this,Te,kn).call(this),R(this,Te,Ms).call(this,e)}getCurrentResult(){return o(this,Qe)}reset(){o(this,Z)?.removeObserver(this),y(this,Z,void 0),R(this,Te,kn).call(this),R(this,Te,Ms).call(this)}mutate(e,n){return y(this,xe,n),o(this,Z)?.removeObserver(this),y(this,Z,o(this,Ee).getMutationCache().build(o(this,Ee),this.options)),o(this,Z).addObserver(this),o(this,Z).execute(e)}},Ee=new WeakMap,Qe=new WeakMap,Z=new WeakMap,xe=new WeakMap,Te=new WeakSet,kn=function(){let e=o(this,Z)?.state??Is();y(this,Qe,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},Ms=function(e){M.batch(()=>{if(o(this,xe)&&this.hasListeners()){let n=o(this,Qe).variables,s=o(this,Qe).context,r={client:o(this,Ee),meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{o(this,xe).onSuccess?.(e.data,n,s,r)}catch(i){Promise.reject(i)}try{o(this,xe).onSettled?.(e.data,null,n,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{o(this,xe).onError?.(e.error,n,s,r)}catch(i){Promise.reject(i)}try{o(this,xe).onSettled?.(void 0,e.error,n,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,Qe))})})},Ir);var ve,Mr,kr=(Mr=class extends re{constructor(e={}){super();b(this,ve);this.config=e,y(this,ve,new Map)}build(e,n,s){let r=n.queryKey,i=n.queryHash??Vt(r,n),a=this.get(i);return a||(a=new _r({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(n),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){o(this,ve).has(e.queryHash)||(o(this,ve).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let n=o(this,ve).get(e.queryHash);n&&(e.destroy(),n===e&&o(this,ve).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){M.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return o(this,ve).get(e)}getAll(){return[...o(this,ve).values()]}find(e){let n={exact:!0,...e};return this.getAll().find(s=>En(n,s))}findAll(e={}){let n=this.getAll();return Object.keys(e).length>0?n.filter(s=>En(e,s)):n}notify(e){M.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){M.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ve=new WeakMap,Mr);var q,Ne,Ke,wt,St,Le,Ct,Rt,Ar,As=(Ar=class{constructor(t={}){b(this,q);b(this,Ne);b(this,Ke);b(this,wt);b(this,St);b(this,Le);b(this,Ct);b(this,Rt);y(this,q,t.queryCache||new kr),y(this,Ne,t.mutationCache||new Fr),y(this,Ke,t.defaultOptions||{}),y(this,wt,new Map),y(this,St,new Map),y(this,Le,0)}mount(){Ut(this,Le)._++,o(this,Le)===1&&(y(this,Ct,ct.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,q).onFocus())})),y(this,Rt,ht.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,q).onOnline())})))}unmount(){var t,e;Ut(this,Le)._--,o(this,Le)===0&&((t=o(this,Ct))==null||t.call(this),y(this,Ct,void 0),(e=o(this,Rt))==null||e.call(this),y(this,Rt,void 0))}isFetching(t){return o(this,q).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return o(this,Ne).findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,q).get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),n=o(this,q).build(this,e),s=n.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(ce(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return o(this,q).findAll(t).map(({queryKey:e,state:n})=>{let s=n.data;return[e,s]})}setQueryData(t,e,n){let s=this.defaultQueryOptions({queryKey:t}),i=o(this,q).get(s.queryHash)?.state.data,a=ar(e,i);if(a!==void 0)return o(this,q).build(this,s).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return M.batch(()=>o(this,q).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,n)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,q).get(e.queryHash)?.state}removeQueries(t){let e=o(this,q);M.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){let n=o(this,q);return M.batch(()=>(n.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let n={revert:!0,...e},s=M.batch(()=>o(this,q).findAll(t).map(r=>r.cancel(n)));return Promise.all(s).then(A).catch(A)}invalidateQueries(t,e={}){return M.batch(()=>(o(this,q).findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let n={...e,cancelRefetch:e.cancelRefetch??!0},s=M.batch(()=>o(this,q).findAll(t).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(A)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(A)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let n=o(this,q).build(this,e);return n.isStaleByTime(ce(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(A).catch(A)}fetchInfiniteQuery(t){return t.behavior=bt(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(A).catch(A)}ensureInfiniteQueryData(t){return t.behavior=bt(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return ht.isOnline()?o(this,Ne).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,q)}getMutationCache(){return o(this,Ne)}getDefaultOptions(){return o(this,Ke)}setDefaultOptions(t){y(this,Ke,t)}setQueryDefaults(t,e){o(this,wt).set(me(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...o(this,wt).values()],n={};return e.forEach(s=>{He(t,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(t,e){o(this,St).set(me(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...o(this,St).values()],n={};return e.forEach(s=>{He(t,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;let e={...o(this,Ke).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Vt(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===lt&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...o(this,Ke).mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){o(this,q).clear(),o(this,Ne).clear()}},q=new WeakMap,Ne=new WeakMap,Ke=new WeakMap,wt=new WeakMap,St=new WeakMap,Le=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Ar);var Pt=G(be(),1),Ur=G(An(),1),qs=Pt.createContext(void 0),K=t=>{let e=Pt.useContext(qs);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Zt=({client:t,children:e})=>(Pt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ur.jsx)(qs.Provider,{value:t,children:e}));var qn=G(be(),1),Qr=qn.createContext(!1),Nr=()=>qn.useContext(Qr),Au=Qr.Provider;var en=G(be(),1),Ho=G(An(),1);function $o(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Go=en.createContext($o()),Kr=()=>en.useContext(Go);var Lr=G(be(),1);var jr=(t,e,n)=>{let s=n?.state.error&&typeof t.throwOnError=="function"?dt(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},Vr=t=>{Lr.useEffect(()=>{t.clearReset()},[t])},Br=({result:t,errorResetBoundary:e,throwOnError:n,query:s,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(r&&t.data===void 0||dt(n,[t.error,s]));var Wr=t=>{if(t.suspense){let n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},Hr=(t,e)=>t.isLoading&&t.isFetching&&!e,$r=(t,e)=>t?.suspense&&e.isPending,Ds=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});var je=G(be(),1);function Dn(t,e,n){let s=Nr(),r=Kr(),i=K(n),a=i.defaultQueryOptions(t);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=i.getQueryCache().get(a.queryHash);a._optimisticResults=s?"isRestoring":"optimistic",Wr(a),jr(a,r,c),Vr(r);let u=!i.getQueryCache().get(a.queryHash),[l]=je.useState(()=>new e(i,a)),f=l.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(je.useSyncExternalStore(je.useCallback(g=>{let d=h?l.subscribe(M.batchCalls(g)):A;return l.updateResult(),d},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),je.useEffect(()=>{l.setOptions(a)},[a,l]),$r(a,f))throw Ds(a,l,r);if(Br({result:f,errorResetBoundary:r,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw f.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,f),a.experimental_prefetchInRender&&!ge.isServer()&&Hr(f,s)&&(u?Ds(a,l,r):c?.promise)?.catch(A).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?f:l.trackResult(f)}function D(t,e){return Dn(t,Jt,e)}var Oe=G(be(),1);function Ve(t,e){let n=K(e),[s]=Oe.useState(()=>new ks(n,t));Oe.useEffect(()=>{s.setOptions(t)},[s,t]);let r=Oe.useSyncExternalStore(Oe.useCallback(a=>s.subscribe(M.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=Oe.useCallback((a,c)=>{s.mutate(a,c).catch(A)},[s]);if(r.error&&dt(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function tn(t,e){return Dn(t,Fs,e)}var O=new As({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}});function V(){return ae()??"__unscoped__"}var w={all:()=>["vfs",V()],item:t=>["vfs",V(),"item",t],itemById:t=>["vfs","item-by-id",t],children:t=>["vfs",V(),"children",t],allChildren:()=>["vfs",V(),"children"],types:t=>["vfs","types",t??"default"],edges:t=>["vfs","edges",t],search:(t,e)=>["vfs",V(),"search",t,...e??[]],items:(t,e)=>["vfs",V(),"items",t,JSON.stringify(e??{})],allItems:()=>["vfs",V(),"items"],tree:(t,e)=>["vfs",V(),"tree",t,e??1],openEnvelope:(t,e)=>["vfs",V(),"open",t,e??"__default__"],allOpenEnvelopes:()=>["vfs",V(),"open"],memberFocus:t=>["vfs","member-focus",t],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(t,e,n)=>["vfs",V(),"get-activity-feed",t,e,n],itemVersions:(t,e,n,s)=>["vfs","item-versions",t,e,n,s],itemHistory:(t,e,n)=>["vfs","item-history",t,e,n],channelMessages:(t,e)=>["vfs",V(),"channel-messages",t,e??"__top__"],allChannelMessages:()=>["vfs",V(),"channel-messages"],channels:t=>["vfs",V(),"channels",t??"all"],allChannels:()=>["vfs",V(),"channels"],notifications:(t,e)=>["vfs",V(),"notifications",t??"all",e??200],allNotifications:()=>["vfs",V(),"notifications"],unreadCounts:()=>["vfs",V(),"unread-counts"],memberships:t=>["memberships",t]};function Gr(){return new Date().toISOString()}function zr(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function le(t){let e=t.path||t.item_path||"",n=e.split("/");n.pop();let s=n.join("/"),r=t.type_data||{};return r.allowed_parent_types&&!r.accepts&&(r.accepts=r.allowed_parent_types),delete r.allowed_parent_types,{id:t.id||t.item_id||"",name:t.name||t.item_name||"",item_type:t.item_type||"unknown",path:e,parent_path:s,is_active:t.is_active!==!1,has_children:t.has_children??!1,created_at:t.created_at||Gr(),updated_at:t.updated_at||Gr(),visibility:t.visibility,type_data:r,scope_item_id:t.scope_item_id,fractal_id:t.fractal_id,parent_instance_id:t.parent_instance_id,owner_principal_id:t.owner_principal_id,created_by_principal_id:t.created_by_principal_id,parent_id:t.parent_id,space_item_id:t.space_item_id,account_item_id:t.account_item_id}}function nn(t){return(t.content?.items||t.items||[]).map(le)}async function Qn(t){try{let e=await P("read",{id:t});if(e.item_name||e.item_path){let s=le(e);return s.path&&O.setQueryData(w.item(s.path),s),s}let n=e.item;if(n){let s=le(n);return s.path&&O.setQueryData(w.item(s.path),s),s}return null}catch{return null}}async function Nn(t){try{let e=await P("read",{path:t});if(e.item_name||e.item_path)return le(e);let n=e.item;return n?le(n):null}catch{return null}}async function Kn(t){try{let e=await P("list",{path:t,limit:200}),n=nn(e);for(let s of n)O.setQueryData(w.item(s.path),s);return n}catch(e){return console.error(`[gateway] Failed to fetch children of ${t}:`,e),[]}}async function Ln(t,e,n){try{let s=await P("list",{path:t,limit:e,offset:n}),r=nn(s);for(let i of r)O.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch children page of ${t}:`,s),{items:[],total_hint:0}}}async function jn(t){let n=await P("types-list",t?{scope_id:t}:{}),s=n.content?.items||n.items||[],r=new Map;for(let i of s){let a=i.name,c=i.type_data;!a||!c||r.set(a,{type_key:a,display_name:c.display_name||a,display_name_plural:c.display_name_plural||a+"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 r}async function Vn(t){try{let e=await P("edges",{item_id:t}),n=e.outgoing||[],s=e.incoming||[],r=[];for(let i of n)r.push({id:i.edge_id||zr(),source_item_id:t,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 s)r.push({id:i.edge_id||zr(),source_item_id:i.source_id||"",target_item_id:t,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return r}catch(e){return console.warn(`[gateway] Failed to fetch edges for ${t}:`,e),[]}}async function Bn(t,e=1,n,s){try{let r={path:t,max_depth:e>0?e:999};n?.length&&(r.item_types=n),s&&(r.limit=s);let i=await P("tree",r),a=nn(i);for(let c of a)O.setQueryData(w.item(c.path),c);return a}catch(r){return console.error(`[gateway] Failed to fetch tree at ${t}:`,r),[]}}async function Wn(t,e=50,n=0){try{let s=await P("get-activity-feed",{scope_path:t,limit:e,offset:n});return s.content?.items||s.items||s.entries||[]}catch(s){return console.error(`[gateway] Failed to fetch recent activity for ${t}:`,s),[]}}async function sn(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;try{let i=await P("item-versions",{id:t,limit:n,offset:s,include_snapshots:r});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${t}:`,i),{versions:[],total:0}}}async function Hn(t,e=50,n=0){return sn(t,{limit:e,offset:n})}async function $n(t,e,n){try{let s={scope_id:t};e?.length&&(s.item_types=e),n&&(s.limit=n);let r=await P("member-focus",s),i=nn(r);for(let a of i)O.setQueryData(w.item(a.path),a);return i}catch(s){return console.error(`[gateway] Failed to fetch member focus for scope ${t}:`,s),[]}}async function Gn(t,e){let n={path:t};e?.mode&&(n.mode=e.mode),e?.strategy&&(n.strategy=e.strategy),e?.arguments&&(n.arguments=e.arguments);let r=await P("open",n);return{item_id:r.item_id,item_path:r.item_path,item_name:r.item_name,item_type:r.item_type,render:r.render,compatible_components:r.compatible_components??[],content:r.content,metadata:r.metadata,instructions:r.instructions}}async function rn(t){let e={item_type:t.type};t.scope&&(e.scope_path=t.scope);let n={};if(t.name&&(n.name=t.name),t.tag&&(n.tag=t.tag),t.parent_id&&(n.parent_id=t.parent_id),t.sort_by&&(n.sort_by=t.sort_by),t.sort_dir&&(n.sort_dir=t.sort_dir),t.offset!=null&&(n.offset=t.offset),t.fields)for(let[s,r]of Object.entries(t.fields))n[`field.${s}`]=String(r);Object.keys(n).length>0&&(e.filters=n),t.limit!=null&&(e.limit=t.limit);try{let s=await P("query",e),r=nn(s);for(let i of r)O.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch items of type ${t.type}:`,s),{items:[],total_hint:0}}}function Jr(t){return t.filter(e=>e.item_type==="card").map(e=>{let n=e.type_data||{},s=n.payload||{};return{id:e.id||"",path:e.path||"",name:e.name||(e.path||"").split("/").pop()||"",createdAt:e.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:(e.name||"").startsWith("card-")?(e.name||"").substring(5):void 0,parentMessagePath:e.parent_message_path||void 0,visibility:n.visibility||"private",openWith:s.open_with||void 0,hostBundled:s.host_bundled===!0?!0:void 0,bundleExport:s.bundle_export||void 0,launchArguments:s.launch_arguments||void 0,requiresUserAttention:s.requires_user_attention===!0?!0:void 0}}).sort((e,n)=>e.createdAt.localeCompare(n.createdAt))}function Us(t){return t.filter(e=>e.item_type==="message").map(e=>{let n=e.type_data||{},s="user";n.role==="assistant"?s="assistant":n.role==="system"&&(s="system");let r=n.metadata||{};return{id:e.id||"",path:e.path||"",content:n.message||n.content||"",created_at:e.created_at||"",role:s,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:r.intent_card,metadata:Object.keys(r).length>0?r:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((e,n)=>e.seq-n.seq)}async function Yr(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await P("get-channel-messages",n),i=r.messages||r.content?.items||r.items||[];return Us(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${t}:`,n),[]}}async function zn(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await P("get-channel-messages",n),i=r.messages||[],a=Us(i),c=Jr(i),u=new Map,l=[];for(let f of c)if(f.parentMessagePath){let h=u.get(f.parentMessagePath)||[];h.push(f),u.set(f.parentMessagePath,h)}else l.push(f);return{messages:a,messageCards:u,siblingCards:l,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function on(t,e){try{let n={channel_path:t};e?.parentMessageId&&(n.parent_message_id=e.parentMessageId),e?.limit&&(n.limit=e.limit),e?.before_seq!=null&&(n.before_seq=e.before_seq),e?.after_seq!=null&&(n.after_seq=e.after_seq);let r=await P("get-channel-messages",n),i=r.messages||[],a=Jr(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:Us(i),messageCards:c,siblingCards:u,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Un(t){O.invalidateQueries({queryKey:w.children(t)})}function Qs(t){O.invalidateQueries({queryKey:w.item(t)})}function Xr(t,e){Qs(t),Un(t);let n=t.split("/");n.pop();let s=n.join("/")||e;s&&Un(s)}function Zr(t){let e=t+"/";O.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]!=="vfs"?!1:s.some(r=>typeof r=="string"&&(r===t||r.startsWith(e)))}})}function ei(){O.invalidateQueries({queryKey:w.all()})}function ti(t){O.invalidateQueries({queryKey:w.types(t)})}function ni(t,e){t?O.invalidateQueries({queryKey:w.channelMessages(t,e)}):O.invalidateQueries({queryKey:w.allChannelMessages()})}function si(t,e){t&&e?O.invalidateQueries({queryKey:w.openEnvelope(t,e)}):t?O.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]==="vfs"&&s[2]==="open"&&s[3]===t}}):O.invalidateQueries({queryKey:w.allOpenEnvelopes()})}var zo=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...t){zo&&console.log("[WS]",...t)}var I=null,Et=null,xt=null,an=0,Jo=3e4,ri=1e4,Ot=!1,Yo=3e4,Jn=null,ii=!1;function Xo(){un(),Jn=setInterval(()=>{Fe({type:"ping"})},Yo)}function un(){Jn&&(clearInterval(Jn),Jn=null)}function Zo(){typeof document>"u"||(document.hidden?un():cn()&&(W("Tab visible, reconnecting..."),ln()))}function ea(){ii||typeof document>"u"||(document.addEventListener("visibilitychange",Zo),ii=!0)}var ee={},Tt=[],Ft=new Map,tt=new Map;function ta(){return Object.keys(ee).some(e=>ee[e]&&ee[e].length>0)||Tt.length>0}function cn(){return Ft.size>0||tt.size>0}async function ln(){if(!cn()){W("ensureConnection: no active subscriptions, skipping");return}if(I&&I.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Et)return W("ensureConnection: connection already in flight, waiting..."),Et;if(I){W("ensureConnection: killing stale WS in state",I.readyState);try{I.close()}catch{}I=null}return Ot=!1,Et=(async()=>{try{let t=typeof window<"u"&&window.__FSAOS_CONFIG__||{},e=Ie,s=t.embedToken||null;if(s||(s=await we()),!s){W("ensureConnection: no token available, will retry"),oi();return}let r=e.startsWith("https")?"wss":"ws",i=e.replace(/^https?:\/\//,""),a=`${r}://${i}/ws`;a+=`?token=${encodeURIComponent(s)}`,W("ensureConnection: opening WS to",a.substring(0,50)+"..."),I=new WebSocket(a),await new Promise((c,u)=>{if(!I)return u(new Error("WebSocket not created"));let l=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",ri,"ms"),I&&I.readyState!==WebSocket.OPEN){try{I.close()}catch{}I=null}u(new Error("WebSocket connection timeout"))},ri);I.onopen=()=>{clearTimeout(l),W("ensureConnection: CONNECTED"),an=0,na(),(typeof document>"u"||!document.hidden)&&Xo(),ea(),c()},I.onmessage=f=>{sa(f.data)},I.onerror=()=>{W("ensureConnection: WS error event")},I.onclose=f=>{clearTimeout(l),W("ensureConnection: WS closed, code:",f.code,"reason:",f.reason),I=null,un(),!Ot&&cn()&&oi(),u(new Error(`WebSocket closed: ${f.code}`))}})}catch(t){W("ensureConnection: failed -",t?.message||t)}finally{Et=null}})(),Et}function oi(){if(xt||typeof document<"u"&&document.hidden)return;let t=Math.min(1e3*Math.pow(2,an)+Math.random()*1e3,Jo);an++,W("scheduleReconnect: attempt",an,"in",Math.round(t),"ms"),xt=setTimeout(()=>{xt=null,cn()&&ln()},t)}function na(){for(let t of Ft.values())W("resubscribeAll: scope",t.scope_id),Fe({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of tt.values())W("resubscribeAll: path",t.path),Fe({type:"subscribe_path",path:t.path,event_types:t.event_types})}function Fe(t){I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify(t))}function sa(t){try{let e=JSON.parse(t);if(e.type==="subscribed"||e.type==="subscribed_path"||e.type==="unsubscribed"||e.type==="unsubscribed_path"||e.type==="pong")return;if(e.type==="error"){console.warn("[WS] Server error:",e.message);return}if(e.type==="event"||e.event_type){let n=e.event_type||"message",s=e.data||e;s.path&&ee[s.path]&&ee[s.path].forEach(r=>r(s)),ee["*"]&&ee["*"].forEach(r=>r(s));for(let r of Tt)r.eventType!=="*"&&r.eventType!==n||r.filter&&!r.filter(s)||r.callback(s)}}catch{}}function Ns(){!ta()&&Ft.size===0&&tt.size===0&&I&&(Ot=!0,un(),I.close(),I=null,Ot=!1)}function ai(t,e){return ee[t]||(ee[t]=[]),ee[t].push(e),tt.has(t)||(tt.set(t,{path:t,event_types:["token_stream"]}),I&&I.readyState===WebSocket.OPEN&&Fe({type:"subscribe_path",path:t,event_types:["token_stream"]})),ln(),()=>{let n=ee[t];if(n){let s=n.indexOf(e);s!==-1&&n.splice(s,1),n.length===0&&(delete ee[t],tt.delete(t),Fe({type:"unsubscribe_path",path:t}))}Ns()}}function oe(t,e,n){let r=(Array.isArray(t)?t:[t]).map(i=>({eventType:i,callback:e,filter:n}));return Tt.push(...r),cn()&&ln(),()=>{for(let i of r){let a=Tt.indexOf(i);a!==-1&&Tt.splice(a,1)}Ns()}}function Yn(t,e=["vfs_change","ccm_change"]){return W("subscribeToScope:",t,e),Ft.set(t,{scope_id:t,event_types:e}),I&&I.readyState===WebSocket.OPEN&&Fe({type:"subscribe",scope_id:t,event_types:e}),ln(),()=>{Ft.delete(t),Fe({type:"unsubscribe",scope_id:t}),Ns()}}function ci(t,e,n={}){Fe({type:"emit",scope_id:t,event_type:e,payload:n})}function Ks(){W("disconnectSSE: tearing down"),Ot=!0,un(),I&&(I.close(),I=null),xt&&(clearTimeout(xt),xt=null),Et=null,Ot=!1,an=0;for(let t of Object.keys(ee))delete ee[t];Tt.length=0,Ft.clear(),tt.clear()}function ui(){Fe({type:"ping"})}Se(Ks);var It=new Map,Xn=null,dn=new Map,ra=250;function fn(t){es(),pn(t),Xn=oe("vfs_change",e=>ia(e))}function pn(t){if(It.has(t))return;let e=Yn(t,["vfs_change","ccm_change"]);It.set(t,e)}function Zn(t){let e=It.get(t);e&&(e(),It.delete(t))}function es(){for(let[,t]of It)t();It.clear(),Xn&&(Xn(),Xn=null),dn.forEach(t=>clearTimeout(t)),dn.clear()}Se(es);function ia(t){let e=t.path,n=t.action;if(!e)return;let s=e.split("/");s.pop();let r=s.join("/")||"/root",i=dn.get(r);i&&clearTimeout(i);let a=setTimeout(()=>{dn.delete(r),oa(n,e,t,r)},ra);dn.set(r,a)}function oa(t,e,n,s){if((t||"").toUpperCase()==="DELETE")O.removeQueries({queryKey:w.item(e)}),O.removeQueries({queryKey:w.children(e)}),O.removeQueries({queryKey:w.tree(e)});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},a=le(i);a&&a.id&&O.setQueryData(w.item(e),a)}catch{}O.invalidateQueries({queryKey:w.children(s)}),O.invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let c=a[2];return e.startsWith(c+"/")||e===c}}),n.item_id&&O.invalidateQueries({queryKey:w.itemById(n.item_id)})}var Ls=G(be(),1),fi=G(di(),1);function pi(t){return P("read",{path:t})}function hi(t,e){return P("list",{path:t,...e})}function mi(t){return P("create",t)}function gi(t){return P("update",t)}function yi(t){return P("create",t)}function _i(t,e){let s=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return P("tools/call",{name:t,instance_path:s,...e||{}})}function vi(t,e,n){return P("signal",{target_id:t,event_name:e,payload:n||{}})}function bi(t){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+t}var wi={signIn:t=>t.provider?k.auth.signInWithOAuth({provider:t.provider,options:{redirectTo:t.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:t.email,password:t.password}),signUp:t=>k.auth.signUp({email:t.email,password:t.password,options:{data:t.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),ot(),O.clear()},getSession:()=>k.auth.getSession().then(t=>t.data.session),getUser:()=>k.auth.getUser().then(t=>t.data.user),onAuthStateChange:t=>{let{data:{subscription:e}}=k.auth.onAuthStateChange((n,s)=>{t({event:n,session:s,user:s?.user??null})});return()=>e?.unsubscribe()},resetPassword:t=>k.auth.resetPasswordForEmail(t),signInWithMagicLink:(t,e)=>k.auth.signInWithOtp({email:t,options:{emailRedirectTo:e||window.location.href}})};function Si(){let t=document.getElementById("root");if(t)try{let e=window.__FSAOS_COMPONENT__;if(!e){t.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=e.default||e,s=window.__FSAOS_ITEM_DATA__||null,r=s?{item:s,...s}:{};(0,fi.createRoot)(t).render((0,Ls.createElement)(Zt,{client:O},(0,Ls.createElement)(n,r)))}catch(e){console.error("[FSAOS] Failed to mount root component:",e),t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(e.message||e)+"</pre></div>"}}function Ci(){let t=window.React,e=window.ReactDOM,n=window.__FSAOS_GATEWAY__,s=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let r={react:t,"react-dom":e,"react-dom/client":e,"react/jsx-runtime":{jsx:t?.createElement,jsxs:t?.createElement,Fragment:t?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":s||{}};window.require=function(a){if(r[a])return r[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var _=G(be(),1),aa=G(Pi(),1),ca=G(An(),1);function N(){return(0,_.useSyncExternalStore)(bn,Lt,Lt)}function Ti(){return N(),Sn()}function Oi(t){return N(),D({queryKey:w.item(t),queryFn:()=>Nn(t),enabled:!!t})}function Fi(t){return N(),D({queryKey:w.itemById(t),queryFn:()=>Qn(t),enabled:!!t})}function js(t){return N(),D({queryKey:w.children(t),queryFn:()=>Kn(t),enabled:!!t})}function Ii(t){let e=js(t);return{...e,children:e.data??[]}}function Mi(t,e=1){return N(),D({queryKey:w.tree(t,e),queryFn:()=>Bn(t,e),enabled:!!t})}function ki(t,e){return N(),D({queryKey:w.search(t,e),queryFn:async()=>{let n={query:t};e?.length&&(n.item_types=e);let s=await P("search",n);return(s.content?.items||s.items||[]).map(le)},enabled:!!t&&t.length>0})}function Ai(t){N();let e=(0,_.useMemo)(()=>t,[JSON.stringify(t)]);return D({queryKey:["vfs",ae()??"__unscoped__","resolve",JSON.stringify(e??{})],queryFn:async()=>await P("resolve",e),enabled:!!e?.query&&e.query.length>0})}function qi(t){N();let e=(0,_.useMemo)(()=>t,[JSON.stringify(t)]);return D({queryKey:w.items(e?.type??"",e),queryFn:()=>rn(e),enabled:!!e?.type,select:n=>n.items})}function Di(t){N();let e=t?.limit??20,n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),s=tn({queryKey:["vfs",ae()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>rn({...n,limit:e,offset:i}),initialPageParam:0,getNextPageParam:(i,a,c)=>{if(!(i.items.length<e))return c+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!s.data?.pages)return[];let i=new Set,a=[];for(let c of s.data.pages)for(let u of c.items)u.id&&!i.has(u.id)&&(i.add(u.id),a.push(u));return a},[s.data?.pages]),fetchNextPage:s.fetchNextPage,isFetchingNextPage:s.isFetchingNextPage,isExhausted:!s.hasNextPage,isLoading:s.isLoading,isFetching:s.isFetching,error:s.error,totalHint:s.data?.pages?.[0]?.total_hint}}function Ui(t){N();let e=20,n=tn({queryKey:["vfs",ae()??"__unscoped__","infinite-children",t??""],queryFn:async({pageParam:r=0})=>Ln(t,e,r),initialPageParam:0,getNextPageParam:(r,i,a)=>{if(!(r.items.length<e))return a+r.items.length},enabled:!!t});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let r=new Set,i=[];for(let a of n.data.pages)for(let c of a.items)c.id&&!r.has(c.id)&&(r.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 Qi(t){return N(),D({queryKey:w.edges(t),queryFn:()=>Vn(t),enabled:!!t})}function ts(t){return N(),D({queryKey:w.types(t),queryFn:()=>jn(t)})}function Ni(t,e){let n=ts(e);return{...n,data:n.data?.get(t)??void 0}}function Ki(t,e){N();let n=(0,_.useMemo)(()=>e?.arguments,[JSON.stringify(e?.arguments)]),s=e?.mode,r=e?.strategy,i=e?.width;return D({queryKey:[...w.openEnvelope(t,r),i],queryFn:async()=>{let a=await Gn(t,{mode:s,strategy:r,arguments:n});if(i&&a.render?.props?.url){let c=a.render.props.url,u=c.includes("?")?"&":"?";a.render.props.url=`${c}${u}w=${i}`}return a},enabled:!!t})}var Ei={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 Li(t){let e=ts(t),n=e.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:d=>n.get(d.item_type)?.is_container??!1,isScope:d=>n.get(d.item_type)?.is_scope??!1,isScopeType:d=>n.get(d)?.is_scope??!1,isContainerType:d=>n.get(d)?.is_container??!1,getTypeDefinition:d=>n.get(d),getTypeColor:d=>n.get(d)?.color??"gray",getTypeIcon:d=>n.get(d)?.icon??"File",getTypeDisplayName:d=>n.get(d)?.display_name??d,getKnownEdgeTypes:()=>Object.entries(Ei).map(([d,v])=>({key:d,label:v})),getEdgeTypeLabel:d=>Ei[d]??d.replace(/_/g," "),allTypes:n,loading:e.isLoading}),[n,e.isLoading])}function ji(t,e,n){return N(),D({queryKey:w.memberFocus(t),queryFn:()=>$n(t,e,n),enabled:!!t})}function Vi(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;return D({queryKey:w.itemVersions(t,String(n),String(s),String(r)),queryFn:()=>sn(t,{limit:n,offset:s,include_snapshots:r}),enabled:!!t})}function Bi(t,e=50,n=0){return D({queryKey:w.itemHistory(t,String(e),String(n)),queryFn:()=>Hn(t,e,n),enabled:!!t})}function Wi(t,e=50,n=0){return N(),D({queryKey:w.recentActivity(t,String(e),String(n)),queryFn:()=>Wn(t,e,n),enabled:!!t})}function Hi(){let[t,e]=(0,_.useState)(null),[n,s]=(0,_.useState)(!0),[r,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let a=!1;return Cn().then(c=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};e({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:u.componentPath||"",isEmbed:!!u.embedToken}),s(!1)}}).catch(c=>{a||(i(c instanceof Error?c:new Error(String(c))),s(!1))}),()=>{a=!0}},[]),{data:t,loading:n,error:r}}function $i(){let{user:t}=ns(),[e,n]=(0,_.useState)(null),[s,r]=(0,_.useState)(null),i=(0,_.useRef)(!1),a=D({queryKey:w.memberships(t?.id??"anonymous"),queryFn:async()=>((await P("list-memberships",{})).memberships||[]).map(d=>({accountId:d.account_id,path:d.account_path,name:d.account_name,role:d.role||"member",typeData:d.account_type_data||{},joinedAt:d.joined_at,via:d.via,placement:d.placement,subordinateTo:d.subordinate_to??null,cascadeAnchorId:d.cascade_anchor_id??null,isAccount:d.is_account??void 0,isSpace:d.is_space??void 0,isOwner:d.is_owner??void 0,billingResponsible:d.billing_responsible??void 0,grantedVia:d.granted_via??null,grantedUnderAccountId:d.granted_under_account_id??null,personalSpaceId:d.personal_space_id??null,personalSpacePath:d.personal_space_path??null})),enabled:!!t?.id,staleTime:1e3*60*2}),c=a.data??[],u=(0,_.useMemo)(()=>c.filter(h=>h.placement!==void 0?h.placement==="switcher_entry"&&h.isAccount===!0:!0),[c]);(0,_.useEffect)(()=>{if(!t?.id){i.current=!1,n(null),r(null);return}i.current||u.length!==0&&(u.length===1?(n(u[0]),Kt(u[0].path),fn(u[0].accountId),i.current=!0):u.length>1&&(i.current=!0))},[t?.id,u]);let l=(0,_.useCallback)(h=>{let g=u.find(d=>d.path===h);g&&(n(g),Kt(g.path),fn(g.accountId),r(null))},[u]),f=(0,_.useCallback)(h=>{s&&Zn(s),r(h),pn(h)},[s]);return{accounts:u,allMemberships:c,currentAccount:e,mountedScope:s,switchAccount:l,mountScope:f,loading:a.isLoading,error:a.error}}function ns(){let[t,e]=(0,_.useState)(null),[n,s]=(0,_.useState)(null),[r,i]=(0,_.useState)(!0),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{k.auth.getSession().then(({data:d,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(d?.session??null),e(d?.session?.user??null),i(!1)}).catch(d=>{console.warn("[useAuth] getSession threw, clearing stale session:",d?.message),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1)});let{data:{subscription:g}}=k.auth.onAuthStateChange((d,v)=>{if(d==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(v),e(v?.user??null),i(!1)});return a.current=g,()=>{g?.unsubscribe()}},[]);let c=(0,_.useCallback)(async g=>g.provider?k.auth.signInWithOAuth({provider:g.provider,options:g.redirectTo?{redirectTo:g.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:g.email,password:g.password}),[]),u=(0,_.useCallback)(async g=>k.auth.signUp({email:g.email,password:g.password,options:{data:g.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await k.auth.signOut(),ot(),O.clear()},[]),f=(0,_.useCallback)(async g=>{let{error:d}=await k.auth.resetPasswordForEmail(g);if(d)throw d},[]),h=(0,_.useCallback)(async(g,d)=>{let{error:v}=await k.auth.signInWithOtp({email:g,options:d?{emailRedirectTo:d}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:t,session:n,loading:r,signIn:c,signUp:u,signOut:l,resetPassword:f,signInWithMagicLink:h}}function Gi(t){let[e,n]=(0,_.useState)(null),[s,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!t){n(null),r(!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(t))r(!0),P("resolve-asset",{asset_id:t}).then(u=>{u.success&&u.public_url?n({url:u.public_url,id:u.asset_id,name:u.name,mimeType:u.mime_type,width:u.width,height:u.height,sizeBytes:u.size_bytes}):a(new Error(u.error||"Asset not found")),r(!1)}).catch(u=>{a(u instanceof Error?u:new Error(String(u))),r(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+t}),r(!1)}},[t]),{data:e,loading:s,error:i}}var hn={},xi={};Se(()=>{for(let t of Object.keys(hn))delete hn[t]});var zi=null;function Ji(t){zi=t,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=t)}function ua(t){switch(t){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||aa;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}:ca;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||zi||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${t}`),{}}}function la(t,e){return t.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,s,r,i)=>`${s}.${e}${i}`)}async function da(t,e){if(!xi[t])try{let n=await fetch(t);if(!n.ok)return;let s=await n.text();if(!s.trim()||s.includes("No CSS bundle for this component"))return;e&&!s.includes(`.fsaos-c-${e}`)&&(s=la(s,`fsaos-c-${e}`));let r=document.createElement("style");r.setAttribute("data-fsaos-component-css",t),e&&r.setAttribute("data-fsaos-component-id",e),r.textContent=s,document.head.appendChild(r),xi[t]=r}catch{}}function fa(t){let e=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=s=>{e=s};try{let s=["var require = arguments[0];",t,"return window.__FSAOS_COMPONENT__;"].join(`
|
|
3
|
-
`),i=new Function(s)(ua),a=e??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Vs(t){let[e,n]=(0,_.useState)(null),[s,r]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!t)return;let c=!1;r(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let f=1,h=t+"@v1",g=l+t+"/__bundle.js";try{let S=await fetch(l+t+"/__meta",{cache:"no-store"});S.ok&&(f=(await S.json()).version||1,h=t+"@v"+f,g=l+t+"/__bundle.v"+f+".js")}catch{g=l+t+"/__bundle.js?v="+Date.now()}if(c)return;if(hn[h]){n(()=>hn[h]),r(!1);return}let d=await fetch(g);if(!d.ok)throw new Error(`Failed to fetch bundle: ${d.status} ${d.statusText} (${g})`);let v=await d.text();if(c)return;let p=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");da(p).catch(()=>{});let m=fa(v);if(!m)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof m!="function")throw new Error(`Bundle export is not a React component (got ${typeof m})`);hn[h]=m,c||(n(()=>m),r(!1))}catch(f){c||(a(f instanceof Error?f:new Error(String(f))),r(!1))}})(),()=>{c=!0}},[t]),{Component:e,loading:s,error:i}}var pa=["--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 Yi(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let e={},n=getComputedStyle(document.documentElement);return pa.forEach(s=>{e[s]=n.getPropertyValue(s).trim()}),{tokens:e}},[]),loading:!1,error:null}}function Xi(t,e){return{data:{allowed:!0},loading:!1,error:null}}function Zi(t,e){let n={};return(e||[]).forEach(s=>{n[s]=!0}),{data:n,loading:!1,error:null}}var nt=null,Mt=null;Se(()=>{nt=null,Mt=null});async function Bs(t){let e=t;if(!e){let{data:n}=await k.auth.getSession();e=n?.session?.user?.id}return e?nt&&nt.authUserId===e?nt.principalId:Mt||(Mt=(async()=>{try{let{data:n,error:s}=await k.from("os_principals").select("id").eq("auth_user_id",e).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal_id:",s.message),null;let r=n?.id??null;return nt={authUserId:e,principalId:r},r}finally{Mt=null}})(),Mt):null}function eo(){let t=ns(),e=t.user,[n,s]=(0,_.useState)((nt?.authUserId===e?.id?nt?.principalId:null)??null),r=(0,_.useRef)(null);return(0,_.useEffect)(()=>{if(!e?.id){s(null),r.current=null;return}r.current===e.id&&n!==null||(r.current=e.id,Bs(e.id).then(i=>{s(i)}))},[e?.id]),t.loading?{data:null,loading:!0,error:null}:e?{data:{id:e.id,principalId:n,email:e.email,role:e.role||e.app_metadata?.role||"user",authenticated:!0,metadata:e.user_metadata||{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function to(){return{data:null,loading:!1,error:null}}function no(t){let{path:e,...n}=t,s=Vs(e),r=s.Component,{loading:i,error:a}=s;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):a?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):r?(0,_.createElement)(r,n):null}function so(t){return t.children}function ro(t){let e=N(),{channelPath:n,parentMessageId:s,realtime:r=!0,enabled:i}=t,a=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>w.channelMessages(n??"",s),[n,s,e]),u=K(),l=(0,_.useRef)(null),f=D({queryKey:c,queryFn:()=>zn(n,s),enabled:a});(0,_.useEffect)(()=>{if(!r||!a)return;let p=oe("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:c})},500)},m=>(m.item_type==="message"||m.item_type==="card")&&typeof m.path=="string"&&m.path.startsWith(n));return()=>{p(),l.current&&clearTimeout(l.current)}},[r,a,n,c,u]);let h=f.data,g=h?.messages??[],d=h?.messageCards??new Map,v=h?.siblingCards??[];return{messages:g,messageCards:d,siblingCards:v,threads:(0,_.useMemo)(()=>g.filter(p=>p.reply_count>0),[g]),isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}}function io(t){N();let{channelPath:e,parentMessageId:n,limit:s=50,realtime:r=!0,enabled:i=!0}=t,a=!!n,c=i&&!!e,u=tn({queryKey:[...w.channelMessages(e||"",n),"infinite",s],queryFn:async({pageParam:p})=>on(e,{parentMessageId:n,limit:s,before_seq:a?void 0:p,after_seq:a?p:void 0}),initialPageParam:void 0,getNextPageParam:p=>!a||p.messages.length<s?void 0:p.messages[p.messages.length-1]?.seq,getPreviousPageParam:p=>a||p.messages.length<s?void 0:p.messages[0]?.seq,enabled:c}),l=(0,_.useMemo)(()=>{if(!u.data?.pages)return[];let p=new Set,m=[];for(let S of u.data.pages)for(let C of S.messages)p.has(C.id)||(p.add(C.id),m.push(C));return m.sort((S,C)=>S.seq-C.seq)},[u.data?.pages]),{messageCards:f,siblingCards:h}=(0,_.useMemo)(()=>{let p=new Map,m=[];if(!u.data?.pages)return{messageCards:p,siblingCards:m};let S=new Set;for(let C of u.data.pages){for(let[E,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let B=p.get(E)||[];B.push(L),p.set(E,B)}for(let E of C.siblingCards)S.has(E.id)||(S.add(E.id),m.push(E))}return{messageCards:p,siblingCards:m}},[u.data?.pages]),g=K(),d=(0,_.useRef)(null),v=(0,_.useMemo)(()=>[...w.channelMessages(e||"",n),"infinite",s],[e,n,s]);return(0,_.useEffect)(()=>{if(!r||!e||!c)return;let p=oe("vfs_change",()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{let m=g.getQueryData(v);if(!m?.pages?.length){g.invalidateQueries({queryKey:v});return}let S=0;for(let C of m.pages)for(let E of C.messages)E.seq>S&&(S=E.seq);if(S===0){g.invalidateQueries({queryKey:v});return}try{let C=await on(e,{parentMessageId:n,limit:s,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){g.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let E=Math.min(...C.messages.map(U=>U.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),g.invalidateQueries({queryKey:v});return}}g.setQueryData(v,E=>{if(!E)return E;let U=[...E.pages],L=U.length-1,B=U[L],st=new Set(B.messages.map(T=>T.id)),ne=C.messages.filter(T=>!st.has(T.id)),Q=[...B.messages,...ne].sort((T,Be)=>T.seq-Be.seq),J=new Map(B.messageCards);for(let[T,Be]of C.messageCards){let H=J.get(T)||[],kt=new Set(H.map(rs=>rs.id)),Po=Be.filter(rs=>!kt.has(rs.id));J.set(T,[...H,...Po])}let de=new Set(B.siblingCards.map(T=>T.id)),fe=C.siblingCards.filter(T=>!de.has(T.id)),pe=[...B.siblingCards,...fe];return U[L]={...B,messages:Q,messageCards:J,siblingCards:pe},{...E,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),g.invalidateQueries({queryKey:v})}},500)},m=>(m.item_type==="message"||m.item_type==="card")&&typeof m.path=="string"&&m.path.startsWith(e));return()=>{p(),d.current&&clearTimeout(d.current)}},[r,e,c,v,g,n,s]),{messages:l,messageCards:f,siblingCards:h,threads:l.filter(p=>p.reply_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasPreviousPage??!1,fetchPreviousPage:u.fetchPreviousPage,isFetchingPreviousPage:u.isFetchingPreviousPage??!1,hasNextPage:u.hasNextPage??!1,fetchNextPage:u.fetchNextPage,isFetchingNextPage:u.isFetchingNextPage??!1}}function ha(t){return t==="on"||t==="auto"?"on":"off"}function ma(t){let e=t.type_data||{};return{id:t.channel_id||"",path:t.channel_path||"",name:t.channel_name||"",displayName:t.display_name||t.channel_name||"",aiMode:ha(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:t.updated_at||"",chatScopePath:t.chat_scope_path||"",contextId:t.context_id||"",contextPath:t.context_path||"",contextType:t.context_type||"",contextName:t.context_name||"",contextDisplayName:t.context_display_name||"",contextPrincipalId:t.context_principal_id,accountId:t.account_id||"",accountPath:t.account_path||"",accountDisplayName:t.account_display_name||"",memberRole:t.member_role||"member",memberPath:t.member_path||"",modePath:t.mode_path||"",autoPilot:t.auto_pilot||e.auto_pilot||!1}}function ss(t={}){let e=N(),{realtime:n=!0,enabled:s=!0}=t,r=K(),i=(0,_.useRef)(null),a=(0,_.useMemo)(()=>w.channels("all"),[e]),c=D({queryKey:a,queryFn:async()=>((await P("list-channels",{})).channels||[]).map(ma),enabled:s});return(0,_.useEffect)(()=>{if(!n||!s)return;let l=oe("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message"),f=oe("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message");return()=>{l(),f(),i.current&&clearTimeout(i.current)}},[n,s,a,r]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function oo(t={}){let e=ss(t),n=(0,_.useMemo)(()=>e.channels.filter(s=>!s.isDm),[e.channels]);return{...e,channels:n}}function ao(t={}){let e=ss(t),n=(0,_.useMemo)(()=>e.channels.filter(s=>s.isDm),[e.channels]);return{...e,channels:n}}function Ws(t={}){let e=N(),{filter:n="all",limit:s=200,realtime:r=!0,enabled:i=!0}=t,a=K(),c=(0,_.useRef)(null),u=(0,_.useMemo)(()=>w.notifications(n,s),[n,s,e]),l=D({queryKey:u,queryFn:async()=>{let h={limit:s};return n==="unread"&&(h.filter="unread"),(await P("get-notifications",h)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!r||!i)return;let h=["vfs_change","ccm_change"].map(g=>oe(g,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},d=>d.item_type==="notification"||d.item_type==="message"));return()=>{h.forEach(g=>g()),c.current&&clearTimeout(c.current)}},[r,i,u,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function co(t={}){let{channels:e,realtime:n=!0,enabled:s=!0}=t,{notifications:r,isLoading:i,isFetching:a,error:c,refetch:u}=Ws({filter:"unread",limit:200,realtime:n,enabled:s}),l=(0,_.useMemo)(()=>{let d=new Map;for(let v of r)v.is_unread&&v.channel_id&&d.set(v.channel_id,(d.get(v.channel_id)||0)+1);return d},[r]),f=(0,_.useMemo)(()=>{let d=0;return l.forEach(v=>{d+=v}),d},[l]),{dmUnread:h,channelUnread:g}=(0,_.useMemo)(()=>{if(!e)return{dmUnread:0,channelUnread:0};let d=new Set(e.filter(m=>m.isDm).map(m=>m.id)),v=0,p=0;return l.forEach((m,S)=>{d.has(S)?v+=m:p+=m}),{dmUnread:v,channelUnread:p}},[e,l]);return{unreadByChannel:l,totalUnread:f,dmUnread:h,channelUnread:g,isLoading:i,isFetching:a,error:c,refetch:u}}function uo(){let t=K();return Ve({mutationFn:e=>P("create",e),onSuccess:(e,n)=>{let s=n.parent_path;s&&t.invalidateQueries({queryKey:w.children(s)})}})}function lo(){let t=K();return Ve({mutationFn:e=>P("update",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.invalidateQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function fo(){let t=K();return Ve({mutationFn:e=>P("delete",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.removeQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function po(){let t=K();return Ve({mutationFn:e=>P("move",e),onSuccess:(e,n)=>{let s=n.path,r=n.new_parent_path;if(s){t.invalidateQueries({queryKey:w.item(s)});let i=s.split("/");i.pop();let a=i.join("/");a&&t.invalidateQueries({queryKey:w.children(a)})}r&&t.invalidateQueries({queryKey:w.children(r)})}})}function ho(){let t=K();return Ve({mutationFn:e=>P("link",e),onSuccess:(e,n)=>{let s=n.source_id,r=n.target_id;s&&t.invalidateQueries({queryKey:w.edges(s)}),r&&t.invalidateQueries({queryKey:w.edges(r)})}})}function mo(t,e){let n=K(),{optimistic:s,...r}=e??{};return Ve({mutationFn:i=>P(t,i),onMutate:s?async i=>{await n.cancelQueries({queryKey:s.queryKey});let a=n.getQueryData(s.queryKey);return n.setQueryData(s.queryKey,c=>s.update(c,i)),{previous:a}}:void 0,onError:(i,a,c)=>{s&&c?.previous!==void 0&&n.setQueryData(s.queryKey,c.previous),r.onError?.(i)},onSuccess:r.onSuccess,onSettled:s?()=>{n.invalidateQueries({queryKey:s.queryKey})}:void 0})}function go(t,e,n){let s,r,i,a=!0;if(typeof t=="string")s=t,r=e,i=n;else{r=t;let l=e;s=l.eventType,i=l.filter,a=l.enabled??!0}let c=(0,_.useRef)(r),u=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=r,u.current=i},[r,i]),(0,_.useEffect)(()=>a?oe(s,f=>c.current(f),u.current?f=>u.current(f):void 0):void 0,[s,a])}function yo(t){let{queryKey:e,queryFn:n,eventType:s,filter:r,enabled:i=!0,debounceMs:a=500}=t,c=K(),u=(0,_.useRef)(null),l=D({queryKey:e,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let f=oe(s,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:e})},a)},r);return()=>{f(),u.current&&clearTimeout(u.current)}},[s,i,a,c,JSON.stringify(e)]),l}function _o(t){N();let e=(0,_.useMemo)(()=>t?typeof t=="string"?{path:t}:t:null,[typeof t=="string"?t:JSON.stringify(t)]),n=!!e&&!!(e.key||e.path||e.item_id),s=e?.key??e?.path??e?.item_id??"",r=D({queryKey:["vfs",ae()??"__unscoped__","arrangement",s],queryFn:async()=>{if(!e)return null;let f=await P("resolve-arrangement",e);return f?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",f?.error),null):f??null},enabled:n}),i=r.data??null,a=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),c=i?.resolution_level??null,u=(0,_.useMemo)(()=>{let h=(i?.type_data??null)?.order;return Array.isArray(h)?h:null},[i]),l=(0,_.useCallback)(f=>{if(!u||!f?.length)return f??[];let h=p=>p.id??p.name??"",g=new Map(u.map((p,m)=>[p,m])),d=[],v=[];for(let p of f)(g.has(h(p))?d:v).push(p);return d.sort((p,m)=>g.get(h(p))-g.get(h(m))),[...d,...v]},[u]);return{...r,arrangement:i,resolvedChildren:a,resolutionLevel:c,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function ga(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ya(t,e){return e&&e.length>0?"select":t==="boolean"?"toggle":t==="integer"||t==="number"?"range":t==="string"?"text":"none"}function _a(t,e){return!(t==="object"||t==="array")}function va(t){return["string","number","integer","boolean"].includes(t)}function ba(t){return t!=="object"&&t!=="array"}function vo(t,e,n,s){let r=t?.properties;if(!r||typeof r!="object")return[];let i=[];for(let[a,c]of Object.entries(r)){let u=c.type||"string",l=c.enum,f=_a(u,l),h=va(u),g=ya(u,l);i.push({key:a,label:c.title||ga(a),type:u,description:c.description,enum_values:l,default_value:n[a]??s[a]??c.default,editable:e,filterable:f,sortable:h,filter_widget:g})}return i}function Hs(t){let e=t.default_data||{},n=t.field_defaults||{},s=vo(t.input_schema,!0,e,n),r=vo(t.system_schema,!1,e,n),i=[...s,...r],a=i.filter(l=>ba(l.type)),c=i.filter(l=>l.filterable),u=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:c,sortable:u,form_fields:s,system_fields:r}}function bo(t){return{field:"updated_at",direction:"desc"}}function wo(t){let e=Hs(t),n=new Set(t.input_schema?.required||[]);return e.form_fields.filter(s=>n.has(s.key)||s.default_value===void 0)}var te=G(be(),1);var wa=0;function Sa(){return`upload_${Date.now()}_${++wa}`}async function So(t,e,n,s){let r=e.name||(t instanceof File?t.name:`file-${Date.now()}`),i=t.type||"application/octet-stream",a=e.itemType||"file",u=await P("create",{parent_path:e.parentPath,item_type:a,name:r,type_data:{...e.typeData||{},file_source:{type:"upload",content_type:i}}});if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let l=u.id,f=u.path;if(u.storage_completed&&u.file_ref)return{itemId:l,itemPath:f,fileRef:u.file_ref};let h=u.storage_key,g=u.upload_token,d=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!h)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Ca(d,h,g,t,i,n,s);let v=await Co(l,h,i);return{itemId:l,itemPath:f,fileRef:v}}function Ca(t,e,n,s,r,i,a){return new Promise((c,u)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${t}/upload`),l.setRequestHeader("X-Storage-Key",e),l.setRequestHeader("Content-Type",r),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=f=>{f.lengthComputable&&i&&i(Math.round(f.loaded/f.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():u(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>u(new Error("Storage upload network error")),l.ontimeout=()=>u(new Error("Storage upload timed out")),a){if(a.aborted){u(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),u(new Error("Upload cancelled"))})}l.send(s)})}async function Co(t,e,n){let s=await we(),r=await fetch(`${Ie}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({item_id:t,storage_key:e,content_type:n})});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${r.status} \u2014 ${a.slice(0,300)}`)}let i=await r.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function Ro(){let[t,e]=(0,te.useState)([]),n=K(),s=(0,te.useRef)(t);s.current=t;let r=(0,te.useCallback)((p,m)=>{e(S=>S.map(C=>C.id===p?{...C,...m}:C))},[]),i=(0,te.useCallback)(p=>{e(m=>[...m,p])},[]),a=(0,te.useCallback)(async(p,m,S,C,E)=>{let U=S.name||m.name,L=m.type||"application/octet-stream",B=S.itemType||"file",st=E?.itemId||null,ne=E?.itemPath||null,Q=E?.storageKey||null,J=E?.uploadToken||null,de=E?.storageWorkerUrl||null;try{if(!C||C==="create"){r(p,{status:"creating",error:null,_failedAt:null});let T=await P("create",{parent_path:S.parentPath,item_type:B,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!T.id)throw Object.assign(new Error(T.error||T.message||"Failed to create file item"),{_step:"create"});if(st=T.id,ne=T.path,r(p,{itemId:st,itemPath:ne}),T.storage_completed&&T.file_ref){r(p,{status:"complete",progress:100,fileRef:T.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=T.storage_key,J=T.upload_token||"",de=T.storage_worker_url||"https://fsaos-storage.radns.workers.dev",r(p,{_storageKey:Q,_uploadToken:J,_storageWorkerUrl:de}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(r(p,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((T,Be)=>{let H=new XMLHttpRequest;r(p,{_xhr:H}),H.open("PUT",`${de}/upload`),H.setRequestHeader("X-Storage-Key",Q),H.setRequestHeader("Content-Type",L),J&&H.setRequestHeader("X-Upload-Token",J),H.upload.onprogress=kt=>{kt.lengthComputable&&r(p,{progress:Math.round(kt.loaded/kt.total*100)})},H.onload=()=>{H.status>=200&&H.status<300?T():Be(Object.assign(new Error(`Storage upload failed: HTTP ${H.status}`),{_step:"upload"}))},H.onerror=()=>Be(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),H.ontimeout=()=>Be(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),H.send(m)}),r(p,{progress:100,_xhr:null})),r(p,{status:"confirming",error:null,_failedAt:null});let fe=await Co(st,Q,L);r(p,{status:"complete",fileRef:fe}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(fe){let pe=fe?.message||String(fe),T=fe?._step||"create";r(p,{status:"error",error:pe,_failedAt:T,_xhr:null})}},[r,n]),c=(0,te.useCallback)((p,m)=>{let S=Sa();i({id:S,file:p,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:m,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,p,m)},[i,a]),u=(0,te.useCallback)((p,m)=>{for(let S of p)c(S,m)},[c]),l=(0,te.useCallback)(p=>{let m=s.current.find(E=>E.id===p);if(!m||m.status!=="error")return;let S=m._failedAt||"create",C=m._storageKey&&m.itemId?{storageKey:m._storageKey,uploadToken:m._uploadToken||"",storageWorkerUrl:m._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:m.itemId,itemPath:m.itemPath||""}:void 0;a(p,m.file,m.options,S,C)},[a]),f=(0,te.useCallback)(p=>{let m=s.current.find(S=>S.id===p);m&&(m._xhr&&m._xhr.abort(),r(p,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[r]),h=(0,te.useCallback)(p=>{e(m=>m.filter(S=>S.id!==p))},[]),g=(0,te.useCallback)(()=>{e(p=>p.filter(m=>m.status!=="complete"))},[]),d=t.some(p=>p.status==="creating"||p.status==="uploading"||p.status==="confirming"),v=t.map(({_storageKey:p,_uploadToken:m,_storageWorkerUrl:S,_xhr:C,_failedAt:E,...U})=>U);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:f,removeUpload:h,clearCompleted:g,isUploading:d}}Ji($s);return ko($s);})();
|
|
1
|
+
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-06-26T12:41:58.858Z */
|
|
2
|
+
"use strict";var __FSAOS_GATEWAY__=(()=>{var Oo=Object.create;var At=Object.defineProperty;var Fo=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var Mo=Object.getPrototypeOf,ko=Object.prototype.hasOwnProperty;var Gs=t=>{throw TypeError(t)};var Ao=(t,e,n)=>e in t?At(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),qo=(t,e)=>{for(var n in e)At(t,n,{get:e[n],enumerable:!0})},zs=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Io(e))!ko.call(t,r)&&r!==n&&At(t,r,{get:()=>e[r],enumerable:!(s=Fo(e,r))||s.enumerable});return t};var G=(t,e,n)=>(n=t!=null?Oo(Mo(t)):{},zs(e||!t||!t.__esModule?At(n,"default",{value:t,enumerable:!0}):n,t)),Do=t=>zs(At({},"__esModule",{value:!0}),t);var Dt=(t,e,n)=>Ao(t,typeof e!="symbol"?e+"":e,n),is=(t,e,n)=>e.has(t)||Gs("Cannot "+n);var o=(t,e,n)=>(is(t,e,"read from private field"),n?n.call(t):e.get(t)),b=(t,e,n)=>e.has(t)?Gs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),_=(t,e,n,s)=>(is(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),R=(t,e,n)=>(is(t,e,"access private method"),n);var Ut=(t,e,n,s)=>({set _(r){_(t,e,r,n)},get _(){return o(t,e,s)}});var Ys=qt((Ia,Js)=>{Js.exports={createClient:window.supabase.createClient}});var we=qt((qu,qr)=>{qr.exports=React});var An=qt((Du,Dr)=>{Dr.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var di=qt((Fl,li)=>{li.exports=ReactDOM});var Pi=qt((Ul,Ri)=>{Ri.exports=ReactDOM});var $s={};qo($s,{ComponentRenderer:()=>ro,EnforcementDeniedError:()=>rt,KernelProvider:()=>io,QueryClientProvider:()=>Zt,auth:()=>wi,awaitScopeReady:()=>wn,callTool:()=>_i,clearCachedToken:()=>cs,clearSession:()=>fs,createItem:()=>mi,disconnectSSE:()=>Ks,disposeVfsRealtimeWs:()=>es,emitEvent:()=>ci,fetchChannelMessages:()=>Yr,fetchChannelMessagesPage:()=>on,fetchChannelMessagesWithCards:()=>zn,fetchEdgesForItem:()=>Vn,fetchItemHistory:()=>Hn,fetchItemVersions:()=>sn,fetchItems:()=>rn,fetchMemberFocus:()=>$n,fetchOpenEnvelope:()=>Gn,fetchRecentActivity:()=>Wn,fetchTypeDefinitions:()=>jn,fetchVfsChildren:()=>Kn,fetchVfsChildrenPage:()=>Ln,fetchVfsItem:()=>Nn,fetchVfsItemById:()=>Qn,fetchVfsTree:()=>Bn,gatewayCall:()=>P,getAccessToken:()=>Se,getAssetUrl:()=>bi,getDefaultSort:()=>Co,getRequiredFormFields:()=>Ro,getScope:()=>ce,getScopeVersion:()=>Lt,getSessionEntry:()=>Rn,initSession:()=>Cn,initVfsRealtimeWs:()=>fn,interpretSchema:()=>Hs,invalidateAllVfs:()=>ei,invalidateChannelMessages:()=>ni,invalidateChildren:()=>Un,invalidateItem:()=>Qs,invalidateOpenEnvelope:()=>si,invalidatePathAndParent:()=>Xr,invalidateSubtree:()=>Zr,invalidateTypes:()=>ti,isScopeReady:()=>Sn,listChildren:()=>hi,mount:()=>Si,mountRealtimeScope:()=>pn,normalizeItem:()=>de,ping:()=>ui,pushChanges:()=>yi,queryClient:()=>O,readItem:()=>pi,registerCleanup:()=>Ce,resetAllSdkState:()=>ot,resolvePrincipalId:()=>to,setCachedToken:()=>er,setScope:()=>Kt,setupRequireShim:()=>Ci,signal:()=>vi,subscribeScope:()=>bn,subscribeToEvents:()=>ae,subscribeToPath:()=>ai,subscribeToScope:()=>Yn,unmountRealtimeScope:()=>Zn,updateItem:()=>gi,uploadFile:()=>Po,useAccounts:()=>$i,useAllChannels:()=>ss,useArrangement:()=>wo,useAsset:()=>Gi,useAuth:()=>ns,useChannelMessages:()=>oo,useChannels:()=>co,useChildren:()=>Ii,useComponent:()=>Bs,useCreate:()=>fo,useDelete:()=>mo,useDmChannels:()=>uo,useEdges:()=>Qi,useEventStream:()=>vo,useFileUpload:()=>xo,useInfiniteChannelMessages:()=>ao,useInfiniteChildren:()=>Ui,useInfiniteItems:()=>Di,useItem:()=>Oi,useItemById:()=>Fi,useItemHistory:()=>Bi,useItemVersions:()=>Vi,useItems:()=>qi,useLink:()=>yo,useList:()=>Vs,useMemberFocus:()=>ji,useMove:()=>go,useMutation:()=>_o,useNotifications:()=>Ws,useOpen:()=>Ki,usePermission:()=>Xi,usePermissions:()=>Zi,usePrincipal:()=>no,useRealtimeQuery:()=>bo,useRecentActivity:()=>Wi,useResolve:()=>Ai,useScope:()=>Hi,useScopeReady:()=>Ti,useSearch:()=>ki,useTheme:()=>Yi,useTool:()=>so,useTree:()=>Mi,useType:()=>Ni,useTypeHelpers:()=>Li,useTypes:()=>ts,useUnreadCounts:()=>lo,useUpdate:()=>po,useUpdatePrincipal:()=>ho,vfsKeys:()=>w});var rt=class t extends Error{constructor(n){let s=n.message||t.fallbackMessage(n);super(s);Dt(this,"name","EnforcementDeniedError");Dt(this,"deniedBy");Dt(this,"ruleKey");Dt(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let r=n.enforcement;this.ruleKey=r?.rule_key??void 0,this.displayName=r?.display_name??void 0}static fallbackMessage(n){let s=n.error||"",r=n.denied_by||"";return r==="rule"||s==="RULE_DENIED"?"This feature is not enabled for this workspace.":r==="entitlement"||s==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":r==="access"||s==="ACCESS_DENIED"||s==="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 Xs=G(Ys(),1),os=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Uo=os.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Qo=os.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ke=os.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,Xs.createClient)(Uo,Qo,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Nt=null,mn=0,Zs,as,gn=!1;Zs=new Promise(t=>{as=t});k.auth.onAuthStateChange((t,e)=>{e?.access_token?(Nt=e.access_token,mn=e.expires_at??Math.floor(Date.now()/1e3)+3600):(Nt=null,mn=0),gn||(gn=!0,as())});setTimeout(()=>{gn||(gn=!0,as())},5e3);function er(t,e){Nt=t,mn=e??Math.floor(Date.now()/1e3)+3600}function cs(){Nt=null,mn=0}async function Se(){return await Zs,Nt}var yn=null,us=0,_n=new Set,ls,ds,vn=!1;ls=new Promise(t=>{ds=t});function Kt(t){let e=yn!==t;yn=t,vn||(vn=!0,ds()),e&&(us++,_n.forEach(n=>{try{n()}catch(s){console.warn("[SDK] Scope listener error:",s)}}))}function ce(){return yn}function Lt(){return us}function bn(t){return _n.add(t),()=>{_n.delete(t)}}function wn(){return ls}function Sn(){return vn}var it=null,Qt=null;async function Cn(){return it||Qt||(Qt=(async()=>{let t=ps(),e=await Se(),n={};e&&(n.Authorization=`Bearer ${e}`);let s=await fetch(`${ke}/d/${t}/init`,{method:"GET",headers:n});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let r=await s.json(),i=r.entry||r;return it={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},it})(),Qt)}function Rn(){return it}function fs(){it=null,Qt=null,yn=null}var tr=[];function Ce(t){tr.push(t)}function ot(){fs(),cs(),vn=!1,ls=new Promise(t=>{ds=t}),us++,_n.forEach(t=>{try{t()}catch(e){console.warn("[SDK] Scope listener error:",e)}});for(let t of tr)try{t()}catch(e){console.warn("[SDK] Cleanup function failed:",e)}}function ps(){if(typeof window<"u"){let t=window.__FSAOS_CONFIG__;return t?.hostname?t.hostname:window.location.hostname}return"localhost"}var No=new Set(["list-memberships","init"]);async function P(t,e={}){let n=ps(),s=`${ke}/d/${n}`,r={"Content-Type":"application/json"},i=await Se();i&&(r.Authorization=`Bearer ${i}`),!No.has(t)&&!e._scope_path&&await wn();let a={...e},c=Rn();!a.domain_scope_id&&c?.scope_id&&(a.domain_scope_id=c.scope_id);let u=ce();!a._scope_path&&u&&(a._scope_path=u);let l=await fetch(s,{method:"POST",headers:r,body:JSON.stringify({method:t,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let f=await l.json();if(f.success===!1){let h=f.error||"",g=f.denied_by||f.error_type||"";throw g==="rule"||g==="access"||g==="entitlement"||h==="RULE_DENIED"||h==="ACCESS_DENIED"||h==="PERMISSION_DENIED"||h==="ENTITLEMENT_REQUIRED"?new rt(f):new Error(f.message||f.error||`Gateway call ${t} failed`)}return f}var ie=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var He,Ae,at,nr,Ko=(nr=class extends ie{constructor(){super();b(this,He);b(this,Ae);b(this,at);_(this,at,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Ae)||this.setEventListener(o(this,at))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,Ae))==null||e.call(this),_(this,Ae,void 0))}setEventListener(e){var n;_(this,at,e),(n=o(this,Ae))==null||n.call(this),_(this,Ae,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){o(this,He)!==e&&(_(this,He,e),this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){return typeof o(this,He)=="boolean"?o(this,He):globalThis.document?.visibilityState!=="hidden"}},He=new WeakMap,Ae=new WeakMap,at=new WeakMap,nr),ct=new Ko;var Lo={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},qe,hs,sr,jo=(sr=class{constructor(){b(this,qe,Lo);b(this,hs,!1)}setTimeoutProvider(t){_(this,qe,t)}setTimeout(t,e){return o(this,qe).setTimeout(t,e)}clearTimeout(t){o(this,qe).clearTimeout(t)}setInterval(t,e){return o(this,qe).setInterval(t,e)}clearInterval(t){o(this,qe).clearInterval(t)}},qe=new WeakMap,hs=new WeakMap,sr),me=new jo;function rr(t){setTimeout(t,0)}var gs=typeof window>"u"||"Deno"in globalThis;function A(){}function ar(t,e){return typeof t=="function"?t(e):t}function jt(t){return typeof t=="number"&&t>=0&&t!==1/0}function Pn(t,e){return Math.max(t+(e||0)-Date.now(),0)}function ue(t,e){return typeof t=="function"?t(e):t}function Y(t,e){return typeof t=="function"?t(e):t}function En(t,e){let{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==Vt(a,e.options))return!1}else if(!$e(e.queryKey,a))return!1}if(n!=="all"){let u=e.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||r&&r!==e.state.fetchStatus||i&&!i(e))}function xn(t,e){let{exact:n,status:s,predicate:r,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(ge(e.options.mutationKey)!==ge(i))return!1}else if(!$e(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||r&&!r(e))}function Vt(t,e){return(e?.queryKeyHashFn||ge)(t)}function ge(t){return JSON.stringify(t,(e,n)=>ms(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function $e(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>$e(t[n],e[n])):!1}var Vo=Object.prototype.hasOwnProperty;function ys(t,e,n=0){if(t===e)return t;if(n>500)return e;let s=ir(t)&&ir(e);if(!s&&!(ms(t)&&ms(e)))return e;let i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},l=0;for(let f=0;f<c;f++){let h=s?f:a[f],g=t[h],d=e[h];if(g===d){u[h]=g,(s?f<i:Vo.call(t,h))&&l++;continue}if(g===null||d===null||typeof g!="object"||typeof d!="object"){u[h]=d;continue}let v=ys(g,d,n+1);u[h]=v,v===g&&l++}return i===c&&l===i?t:u}function ut(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let n in t)if(t[n]!==e[n])return!1;return!0}function ir(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function ms(t){if(!or(t))return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(!or(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function or(t){return Object.prototype.toString.call(t)==="[object Object]"}function cr(t){return new Promise(e=>{me.setTimeout(e,t)})}function Bt(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?ys(t,e):e}function ur(t,e,n=0){let s=[...t,e];return n&&s.length>n?s.slice(1):s}function lr(t,e,n=0){let s=[e,...t];return n&&s.length>n?s.slice(0,-1):s}var lt=Symbol();function Tn(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===lt?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function dt(t,e){return typeof t=="function"?t(...e):!!t}function dr(t,e,n){let s=!1,r;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(r??(r=e()),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),t}var ye=(()=>{let t=()=>gs;return{isServer(){return t()},setIsServer(e){t=e}}})();function Wt(){let t,e,n=new Promise((r,i)=>{t=r,e=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),t(r)},n.reject=r=>{s({status:"rejected",reason:r}),e(r)},n}var fr=rr;function Bo(){let t=[],e=0,n=c=>{c()},s=c=>{c()},r=fr,i=c=>{e?t.push(c):r(()=>{n(c)})},a=()=>{let c=t;t=[],c.length&&r(()=>{s(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},batchCalls:c=>(...u)=>{i(()=>{c(...u)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{s=c},setScheduler:c=>{r=c}}}var M=Bo();var ft,De,pt,pr,Wo=(pr=class extends ie{constructor(){super();b(this,ft,!0);b(this,De);b(this,pt);_(this,pt,e=>{if(typeof window<"u"&&window.addEventListener){let n=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",s)}}})}onSubscribe(){o(this,De)||this.setEventListener(o(this,pt))}onUnsubscribe(){var e;this.hasListeners()||((e=o(this,De))==null||e.call(this),_(this,De,void 0))}setEventListener(e){var n;_(this,pt,e),(n=o(this,De))==null||n.call(this),_(this,De,e(this.setOnline.bind(this)))}setOnline(e){o(this,ft)!==e&&(_(this,ft,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return o(this,ft)}},ft=new WeakMap,De=new WeakMap,pt=new WeakMap,pr),ht=new Wo;function Ho(t){return Math.min(1e3*2**t,3e4)}function _s(t){return(t??"online")==="online"?ht.isOnline():!0}var On=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Fn(t){let e=!1,n=0,s,r=Wt(),i=()=>r.status!=="pending",a=p=>{if(!i()){let m=new On(p);g(m),t.onCancel?.(m)}},c=()=>{e=!0},u=()=>{e=!1},l=()=>ct.isFocused()&&(t.networkMode==="always"||ht.isOnline())&&t.canRun(),f=()=>_s(t.networkMode)&&t.canRun(),h=p=>{i()||(s?.(),r.resolve(p))},g=p=>{i()||(s?.(),r.reject(p))},d=()=>new Promise(p=>{s=m=>{(i()||l())&&p(m)},t.onPause?.()}).then(()=>{s=void 0,i()||t.onContinue?.()}),v=()=>{if(i())return;let p,m=n===0?t.initialPromise:void 0;try{p=m??t.fn()}catch(S){p=Promise.reject(S)}Promise.resolve(p).then(h).catch(S=>{if(i())return;let C=t.retry??(ye.isServer()?0:3),E=t.retryDelay??Ho,U=typeof E=="function"?E(n,S):E,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(e||!L){g(S);return}n++,t.onFail?.(n,S),cr(U).then(()=>l()?void 0:d()).then(()=>{e?g(S):v()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(s?.(),r),cancelRetry:c,continueRetry:u,canStart:f,start:()=>(f()?v():d().then(v),r)}}var Ge,hr,In=(hr=class{constructor(){b(this,Ge)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),jt(this.gcTime)&&_(this,Ge,me.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(ye.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,Ge)!==void 0&&(me.clearTimeout(o(this,Ge)),_(this,Ge,void 0))}},Ge=new WeakMap,hr);var ze,mt,oe,Je,j,Ht,Ye,se,vr,Re,yr,_r=(yr=class extends In{constructor(e){super();b(this,se);b(this,ze);b(this,mt);b(this,oe);b(this,Je);b(this,j);b(this,Ht);b(this,Ye);_(this,Ye,!1),_(this,Ht,e.defaultOptions),this.setOptions(e.options),this.observers=[],_(this,Je,e.client),_(this,oe,o(this,Je).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_(this,ze,gr(this.options)),this.state=e.state??o(this,ze),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,j)?.promise}setOptions(e){if(this.options={...o(this,Ht),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=gr(this.options);n.data!==void 0&&(this.setState(mr(n.data,n.dataUpdatedAt)),_(this,ze,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,oe).remove(this)}setData(e,n){let s=Bt(this.state.data,e,this.options);return R(this,se,Re).call(this,{data:s,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),s}setState(e,n){R(this,se,Re).call(this,{type:"setState",state:e,setStateOptions:n})}cancel(e){let n=o(this,j)?.promise;return o(this,j)?.cancel(e),n?n.then(A).catch(A):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,ze)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ue(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Pn(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,j)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),o(this,oe).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(o(this,j)&&(o(this,Ye)||R(this,se,vr).call(this)?o(this,j).cancel({revert:!0}):o(this,j).cancelRetry()),this.scheduleGc()),o(this,oe).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||R(this,se,Re).call(this,{type:"invalidate"})}async fetch(e,n){if(this.state.fetchStatus!=="idle"&&o(this,j)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,j))return o(this,j).continueRetry(),o(this,j).promise}if(e&&this.setOptions(e),!this.options.queryFn){let u=this.observers.find(l=>l.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(_(this,Ye,!0),s.signal)})},i=()=>{let u=Tn(this.options,n),f=(()=>{let h={client:o(this,Je),queryKey:this.queryKey,meta:this.meta};return r(h),h})();return _(this,Ye,!1),this.options.persister?this.options.persister(u,f,this):u(f)},c=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,Je),state:this.state,fetchFn:i};return r(u),u})();this.options.behavior?.onFetch(c,this),_(this,mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&R(this,se,Re).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),_(this,j,Fn({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:u=>{u instanceof On&&u.revert&&this.setState({...o(this,mt),fetchStatus:"idle"}),s.abort()},onFail:(u,l)=>{R(this,se,Re).call(this,{type:"failed",failureCount:u,error:l})},onPause:()=>{R(this,se,Re).call(this,{type:"pause"})},onContinue:()=>{R(this,se,Re).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let u=await o(this,j).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),o(this,oe).config.onSuccess?.(u,this),o(this,oe).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof On){if(u.silent)return o(this,j).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw R(this,se,Re).call(this,{type:"error",error:u}),o(this,oe).config.onError?.(u,this),o(this,oe).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},ze=new WeakMap,mt=new WeakMap,oe=new WeakMap,Je=new WeakMap,j=new WeakMap,Ht=new WeakMap,Ye=new WeakMap,se=new WeakSet,vr=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Re=function(e){let n=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...vs(s.data,this.options),fetchMeta:e.meta??null};case"success":let r={...s,...mr(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return _(this,mt,e.manual?r:void 0),r;case"error":let i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=n(this.state),M.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),o(this,oe).notify({query:this,type:"updated",action:e})})},yr);function vs(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_s(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function mr(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function gr(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,s=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var X,x,Gt,z,Xe,gt,Pe,Ue,zt,yt,_t,Ze,et,Qe,vt,F,$t,bs,ws,Ss,Cs,Rs,Ps,Es,Cr,Sr,Jt=(Sr=class extends ie{constructor(e,n){super();b(this,F);b(this,X);b(this,x);b(this,Gt);b(this,z);b(this,Xe);b(this,gt);b(this,Pe);b(this,Ue);b(this,zt);b(this,yt);b(this,_t);b(this,Ze);b(this,et);b(this,Qe);b(this,vt,new Set);this.options=n,_(this,X,e),_(this,Ue,null),_(this,Pe,Wt()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,x).addObserver(this),br(o(this,x),this.options)?R(this,F,$t).call(this):this.updateResult(),R(this,F,Cs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return xs(o(this,x),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return xs(o(this,x),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,R(this,F,Rs).call(this),R(this,F,Ps).call(this),o(this,x).removeObserver(this)}setOptions(e){let n=this.options,s=o(this,x);if(this.options=o(this,X).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Y(this.options.enabled,o(this,x))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");R(this,F,Es).call(this),o(this,x).setOptions(this.options),n._defaulted&&!ut(this.options,n)&&o(this,X).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,x),observer:this});let r=this.hasListeners();r&&wr(o(this,x),s,this.options,n)&&R(this,F,$t).call(this),this.updateResult(),r&&(o(this,x)!==s||Y(this.options.enabled,o(this,x))!==Y(n.enabled,o(this,x))||ue(this.options.staleTime,o(this,x))!==ue(n.staleTime,o(this,x)))&&R(this,F,bs).call(this);let i=R(this,F,ws).call(this);r&&(o(this,x)!==s||Y(this.options.enabled,o(this,x))!==Y(n.enabled,o(this,x))||i!==o(this,Qe))&&R(this,F,Ss).call(this,i)}getOptimisticResult(e){let n=o(this,X).getQueryCache().build(o(this,X),e),s=this.createResult(n,e);return Go(this,s)&&(_(this,z,s),_(this,gt,this.options),_(this,Xe,o(this,x).state)),s}getCurrentResult(){return o(this,z)}trackResult(e,n){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),n?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Pe).status==="pending"&&o(this,Pe).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){o(this,vt).add(e)}getCurrentQuery(){return o(this,x)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let n=o(this,X).defaultQueryOptions(e),s=o(this,X).getQueryCache().build(o(this,X),n);return s.fetch().then(()=>this.createResult(s,n))}fetch(e){return R(this,F,$t).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(e,n){let s=o(this,x),r=this.options,i=o(this,z),a=o(this,Xe),c=o(this,gt),l=e!==s?e.state:o(this,Gt),{state:f}=e,h={...f},g=!1,d;if(n._optimisticResults){let Q=this.hasListeners(),J=!Q&&br(e,n),fe=Q&&wr(e,s,n,r);(J||fe)&&(h={...h,...vs(f.data,e.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:v,errorUpdatedAt:p,status:m}=h;d=h.data;let S=!1;if(n.placeholderData!==void 0&&d===void 0&&m==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(o(this,_t)?.state.data,o(this,_t)):n.placeholderData,Q!==void 0&&(m="success",d=Bt(i?.data,Q,n),g=!0)}if(n.select&&d!==void 0&&!S)if(i&&d===a?.data&&n.select===o(this,zt))d=o(this,yt);else try{_(this,zt,n.select),d=n.select(d),d=Bt(i?.data,d,n),_(this,yt,d),_(this,Ue,null)}catch(Q){_(this,Ue,Q)}o(this,Ue)&&(v=o(this,Ue),d=o(this,yt),p=Date.now(),m="error");let C=h.fetchStatus==="fetching",E=m==="pending",U=m==="error",L=E&&C,B=d!==void 0,ne={status:m,fetchStatus:h.fetchStatus,isPending:E,isSuccess:m==="success",isError:U,isInitialLoading:L,isLoading:L,data:d,dataUpdatedAt:h.dataUpdatedAt,error:v,errorUpdatedAt:p,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:U&&!B,isPaused:h.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:U&&B,isStale:Ts(e,n),refetch:this.refetch,promise:o(this,Pe),isEnabled:Y(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let Q=ne.data!==void 0,J=ne.status==="error"&&!Q,fe=T=>{J?T.reject(ne.error):Q&&T.resolve(ne.data)},pe=()=>{let T=_(this,Pe,ne.promise=Wt());fe(T)},he=o(this,Pe);switch(he.status){case"pending":e.queryHash===s.queryHash&&fe(he);break;case"fulfilled":(J||ne.data!==he.value)&&pe();break;case"rejected":(!J||ne.error!==he.reason)&&pe();break}}return ne}updateResult(){let e=o(this,z),n=this.createResult(o(this,x),this.options);if(_(this,Xe,o(this,x).state),_(this,gt,this.options),o(this,Xe).data!==void 0&&_(this,_t,o(this,x)),ut(n,e))return;_(this,z,n);let s=()=>{if(!e)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!o(this,vt).size)return!0;let a=new Set(i??o(this,vt));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(c=>{let u=c;return o(this,z)[u]!==e[u]&&a.has(u)})};R(this,F,Cr).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&R(this,F,Cs).call(this)}},X=new WeakMap,x=new WeakMap,Gt=new WeakMap,z=new WeakMap,Xe=new WeakMap,gt=new WeakMap,Pe=new WeakMap,Ue=new WeakMap,zt=new WeakMap,yt=new WeakMap,_t=new WeakMap,Ze=new WeakMap,et=new WeakMap,Qe=new WeakMap,vt=new WeakMap,F=new WeakSet,$t=function(e){R(this,F,Es).call(this);let n=o(this,x).fetch(this.options,e);return e?.throwOnError||(n=n.catch(A)),n},bs=function(){R(this,F,Rs).call(this);let e=ue(this.options.staleTime,o(this,x));if(ye.isServer()||o(this,z).isStale||!jt(e))return;let s=Pn(o(this,z).dataUpdatedAt,e)+1;_(this,Ze,me.setTimeout(()=>{o(this,z).isStale||this.updateResult()},s))},ws=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,x)):this.options.refetchInterval)??!1},Ss=function(e){R(this,F,Ps).call(this),_(this,Qe,e),!(ye.isServer()||Y(this.options.enabled,o(this,x))===!1||!jt(o(this,Qe))||o(this,Qe)===0)&&_(this,et,me.setInterval(()=>{(this.options.refetchIntervalInBackground||ct.isFocused())&&R(this,F,$t).call(this)},o(this,Qe)))},Cs=function(){R(this,F,bs).call(this),R(this,F,Ss).call(this,R(this,F,ws).call(this))},Rs=function(){o(this,Ze)!==void 0&&(me.clearTimeout(o(this,Ze)),_(this,Ze,void 0))},Ps=function(){o(this,et)!==void 0&&(me.clearInterval(o(this,et)),_(this,et,void 0))},Es=function(){let e=o(this,X).getQueryCache().build(o(this,X),this.options);if(e===o(this,x))return;let n=o(this,x);_(this,x,e),_(this,Gt,e.state),this.hasListeners()&&(n?.removeObserver(this),e.addObserver(this))},Cr=function(e){M.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,X).getQueryCache().notify({query:o(this,x),type:"observerResultsUpdated"})})},Sr);function $o(t,e){return Y(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function br(t,e){return $o(t,e)||t.state.data!==void 0&&xs(t,e,e.refetchOnMount)}function xs(t,e,n){if(Y(e.enabled,t)!==!1&&ue(e.staleTime,t)!=="static"){let s=typeof n=="function"?n(t):n;return s==="always"||s!==!1&&Ts(t,e)}return!1}function wr(t,e,n,s){return(t!==e||Y(s.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&Ts(t,n)}function Ts(t,e){return Y(e.enabled,t)!==!1&&t.isStaleByTime(ue(e.staleTime,t))}function Go(t,e){return!ut(t.getCurrentResult(),e)}function bt(t){return{onFetch:(e,n)=>{let s=e.options,r=e.fetchOptions?.meta?.fetchMore?.direction,i=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,l=async()=>{let f=!1,h=v=>{dr(v,()=>e.signal,()=>f=!0)},g=Tn(e.options,e.fetchOptions),d=async(v,p,m)=>{if(f)return Promise.reject();if(p==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let B={client:e.client,queryKey:e.queryKey,pageParam:p,direction:m?"backward":"forward",meta:e.options.meta};return h(B),B})(),E=await g(C),{maxPages:U}=e.options,L=m?lr:ur;return{pages:L(v.pages,E,U),pageParams:L(v.pageParams,p,U)}};if(r&&i.length){let v=r==="backward",p=v?Rr:Os,m={pages:i,pageParams:a},S=p(s,m);c=await d(m,S,v)}else{let v=t??i.length;do{let p=u===0?a[0]??s.initialPageParam:Os(s,c);if(u>0&&p==null)break;c=await d(c,p),u++}while(u<v)}return c};e.options.persister?e.fetchFn=()=>e.options.persister?.(l,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=l}}}function Os(t,{pages:e,pageParams:n}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,n[s],n):void 0}function Rr(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}function Pr(t,e){return e?Os(t,e)!=null:!1}function Er(t,e){return!e||!t.getPreviousPageParam?!1:Rr(t,e)!=null}var Fs=class extends Jt{constructor(t,e){super(t,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(t){super.setOptions({...t,behavior:bt()})}getOptimisticResult(t){return t.behavior=bt(),super.getOptimisticResult(t)}fetchNextPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(t){return this.fetch({...t,meta:{fetchMore:{direction:"backward"}}})}createResult(t,e){let{state:n}=t,s=super.createResult(t,e),{isFetching:r,isRefetching:i,isError:a,isRefetchError:c}=s,u=n.fetchMeta?.fetchMore?.direction,l=a&&u==="forward",f=r&&u==="forward",h=a&&u==="backward",g=r&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Pr(e,n.data),hasPreviousPage:Er(e,n.data),isFetchNextPageError:l,isFetchingNextPage:f,isFetchPreviousPageError:h,isFetchingPreviousPage:g,isRefetchError:c&&!l&&!h,isRefetching:i&&!f&&!g}}};var Yt,_e,$,tt,ve,Ne,xr,Tr=(xr=class extends In{constructor(e){super();b(this,ve);b(this,Yt);b(this,_e);b(this,$);b(this,tt);_(this,Yt,e.client),this.mutationId=e.mutationId,_(this,$,e.mutationCache),_(this,_e,[]),this.state=e.state||Is(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){o(this,_e).includes(e)||(o(this,_e).push(e),this.clearGcTimeout(),o(this,$).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_(this,_e,o(this,_e).filter(n=>n!==e)),this.scheduleGc(),o(this,$).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){o(this,_e).length||(this.state.status==="pending"?this.scheduleGc():o(this,$).remove(this))}continue(){return o(this,tt)?.continue()??this.execute(this.state.variables)}async execute(e){let n=()=>{R(this,ve,Ne).call(this,{type:"continue"})},s={client:o(this,Yt),meta:this.options.meta,mutationKey:this.options.mutationKey};_(this,tt,Fn({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,c)=>{R(this,ve,Ne).call(this,{type:"failed",failureCount:a,error:c})},onPause:()=>{R(this,ve,Ne).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,$).canRun(this)}));let r=this.state.status==="pending",i=!o(this,tt).canStart();try{if(r)n();else{R(this,ve,Ne).call(this,{type:"pending",variables:e,isPaused:i}),o(this,$).config.onMutate&&await o(this,$).config.onMutate(e,this,s);let c=await this.options.onMutate?.(e,s);c!==this.state.context&&R(this,ve,Ne).call(this,{type:"pending",context:c,variables:e,isPaused:i})}let a=await o(this,tt).start();return await o(this,$).config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await o(this,$).config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),R(this,ve,Ne).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,$).config.onError?.(a,e,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(c){Promise.reject(c)}try{await o(this,$).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(c){Promise.reject(c)}throw R(this,ve,Ne).call(this,{type:"error",error:a}),a}finally{o(this,$).runNext(this)}}},Yt=new WeakMap,_e=new WeakMap,$=new WeakMap,tt=new WeakMap,ve=new WeakSet,Ne=function(e){let n=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),M.batch(()=>{o(this,_e).forEach(s=>{s.onMutationUpdate(e)}),o(this,$).notify({mutation:this,type:"updated",action:e})})},xr);function Is(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ee,le,Xt,Or,Fr=(Or=class extends ie{constructor(e={}){super();b(this,Ee);b(this,le);b(this,Xt);this.config=e,_(this,Ee,new Set),_(this,le,new Map),_(this,Xt,0)}build(e,n,s){let r=new Tr({client:e,mutationCache:this,mutationId:++Ut(this,Xt)._,options:e.defaultMutationOptions(n),state:s});return this.add(r),r}add(e){o(this,Ee).add(e);let n=Mn(e);if(typeof n=="string"){let s=o(this,le).get(n);s?s.push(e):o(this,le).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(o(this,Ee).delete(e)){let n=Mn(e);if(typeof n=="string"){let s=o(this,le).get(n);if(s)if(s.length>1){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&o(this,le).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){let n=Mn(e);if(typeof n=="string"){let r=o(this,le).get(n)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){let n=Mn(e);return typeof n=="string"?o(this,le).get(n)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{o(this,Ee).forEach(e=>{this.notify({type:"removed",mutation:e})}),o(this,Ee).clear(),o(this,le).clear()})}getAll(){return Array.from(o(this,Ee))}find(e){let n={exact:!0,...e};return this.getAll().find(s=>xn(n,s))}findAll(e={}){return this.getAll().filter(n=>xn(e,n))}notify(e){M.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){let e=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(e.map(n=>n.continue().catch(A))))}},Ee=new WeakMap,le=new WeakMap,Xt=new WeakMap,Or);function Mn(t){return t.options.scope?.id}var xe,Ke,Z,Te,Oe,kn,Ms,Ir,ks=(Ir=class extends ie{constructor(e,n){super();b(this,Oe);b(this,xe);b(this,Ke);b(this,Z);b(this,Te);_(this,xe,e),this.setOptions(n),this.bindMethods(),R(this,Oe,kn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let n=this.options;this.options=o(this,xe).defaultMutationOptions(e),ut(this.options,n)||o(this,xe).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,Z),observer:this}),n?.mutationKey&&this.options.mutationKey&&ge(n.mutationKey)!==ge(this.options.mutationKey)?this.reset():o(this,Z)?.state.status==="pending"&&o(this,Z).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,Z)?.removeObserver(this)}onMutationUpdate(e){R(this,Oe,kn).call(this),R(this,Oe,Ms).call(this,e)}getCurrentResult(){return o(this,Ke)}reset(){o(this,Z)?.removeObserver(this),_(this,Z,void 0),R(this,Oe,kn).call(this),R(this,Oe,Ms).call(this)}mutate(e,n){return _(this,Te,n),o(this,Z)?.removeObserver(this),_(this,Z,o(this,xe).getMutationCache().build(o(this,xe),this.options)),o(this,Z).addObserver(this),o(this,Z).execute(e)}},xe=new WeakMap,Ke=new WeakMap,Z=new WeakMap,Te=new WeakMap,Oe=new WeakSet,kn=function(){let e=o(this,Z)?.state??Is();_(this,Ke,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},Ms=function(e){M.batch(()=>{if(o(this,Te)&&this.hasListeners()){let n=o(this,Ke).variables,s=o(this,Ke).context,r={client:o(this,xe),meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{o(this,Te).onSuccess?.(e.data,n,s,r)}catch(i){Promise.reject(i)}try{o(this,Te).onSettled?.(e.data,null,n,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{o(this,Te).onError?.(e.error,n,s,r)}catch(i){Promise.reject(i)}try{o(this,Te).onSettled?.(void 0,e.error,n,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,Ke))})})},Ir);var be,Mr,kr=(Mr=class extends ie{constructor(e={}){super();b(this,be);this.config=e,_(this,be,new Map)}build(e,n,s){let r=n.queryKey,i=n.queryHash??Vt(r,n),a=this.get(i);return a||(a=new _r({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(n),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){o(this,be).has(e.queryHash)||(o(this,be).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let n=o(this,be).get(e.queryHash);n&&(e.destroy(),n===e&&o(this,be).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){M.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return o(this,be).get(e)}getAll(){return[...o(this,be).values()]}find(e){let n={exact:!0,...e};return this.getAll().find(s=>En(n,s))}findAll(e={}){let n=this.getAll();return Object.keys(e).length>0?n.filter(s=>En(e,s)):n}notify(e){M.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){M.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},be=new WeakMap,Mr);var q,Le,je,wt,St,Ve,Ct,Rt,Ar,As=(Ar=class{constructor(t={}){b(this,q);b(this,Le);b(this,je);b(this,wt);b(this,St);b(this,Ve);b(this,Ct);b(this,Rt);_(this,q,t.queryCache||new kr),_(this,Le,t.mutationCache||new Fr),_(this,je,t.defaultOptions||{}),_(this,wt,new Map),_(this,St,new Map),_(this,Ve,0)}mount(){Ut(this,Ve)._++,o(this,Ve)===1&&(_(this,Ct,ct.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,q).onFocus())})),_(this,Rt,ht.subscribe(async t=>{t&&(await this.resumePausedMutations(),o(this,q).onOnline())})))}unmount(){var t,e;Ut(this,Ve)._--,o(this,Ve)===0&&((t=o(this,Ct))==null||t.call(this),_(this,Ct,void 0),(e=o(this,Rt))==null||e.call(this),_(this,Rt,void 0))}isFetching(t){return o(this,q).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return o(this,Le).findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,q).get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),n=o(this,q).build(this,e),s=n.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(ue(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return o(this,q).findAll(t).map(({queryKey:e,state:n})=>{let s=n.data;return[e,s]})}setQueryData(t,e,n){let s=this.defaultQueryOptions({queryKey:t}),i=o(this,q).get(s.queryHash)?.state.data,a=ar(e,i);if(a!==void 0)return o(this,q).build(this,s).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return M.batch(()=>o(this,q).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,n)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return o(this,q).get(e.queryHash)?.state}removeQueries(t){let e=o(this,q);M.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){let n=o(this,q);return M.batch(()=>(n.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let n={revert:!0,...e},s=M.batch(()=>o(this,q).findAll(t).map(r=>r.cancel(n)));return Promise.all(s).then(A).catch(A)}invalidateQueries(t,e={}){return M.batch(()=>(o(this,q).findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let n={...e,cancelRefetch:e.cancelRefetch??!0},s=M.batch(()=>o(this,q).findAll(t).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(A)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(A)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let n=o(this,q).build(this,e);return n.isStaleByTime(ue(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(A).catch(A)}fetchInfiniteQuery(t){return t.behavior=bt(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(A).catch(A)}ensureInfiniteQueryData(t){return t.behavior=bt(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return ht.isOnline()?o(this,Le).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,q)}getMutationCache(){return o(this,Le)}getDefaultOptions(){return o(this,je)}setDefaultOptions(t){_(this,je,t)}setQueryDefaults(t,e){o(this,wt).set(ge(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...o(this,wt).values()],n={};return e.forEach(s=>{$e(t,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(t,e){o(this,St).set(ge(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...o(this,St).values()],n={};return e.forEach(s=>{$e(t,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;let e={...o(this,je).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Vt(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===lt&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...o(this,je).mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){o(this,q).clear(),o(this,Le).clear()}},q=new WeakMap,Le=new WeakMap,je=new WeakMap,wt=new WeakMap,St=new WeakMap,Ve=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Ar);var Pt=G(we(),1),Ur=G(An(),1),qs=Pt.createContext(void 0),K=t=>{let e=Pt.useContext(qs);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Zt=({client:t,children:e})=>(Pt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ur.jsx)(qs.Provider,{value:t,children:e}));var qn=G(we(),1),Qr=qn.createContext(!1),Nr=()=>qn.useContext(Qr),Qu=Qr.Provider;var en=G(we(),1),zo=G(An(),1);function Jo(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Yo=en.createContext(Jo()),Kr=()=>en.useContext(Yo);var Lr=G(we(),1);var jr=(t,e,n)=>{let s=n?.state.error&&typeof t.throwOnError=="function"?dt(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},Vr=t=>{Lr.useEffect(()=>{t.clearReset()},[t])},Br=({result:t,errorResetBoundary:e,throwOnError:n,query:s,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(r&&t.data===void 0||dt(n,[t.error,s]));var Wr=t=>{if(t.suspense){let n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},Hr=(t,e)=>t.isLoading&&t.isFetching&&!e,$r=(t,e)=>t?.suspense&&e.isPending,Ds=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});var Be=G(we(),1);function Dn(t,e,n){let s=Nr(),r=Kr(),i=K(n),a=i.defaultQueryOptions(t);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=i.getQueryCache().get(a.queryHash);a._optimisticResults=s?"isRestoring":"optimistic",Wr(a),jr(a,r,c),Vr(r);let u=!i.getQueryCache().get(a.queryHash),[l]=Be.useState(()=>new e(i,a)),f=l.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(Be.useSyncExternalStore(Be.useCallback(g=>{let d=h?l.subscribe(M.batchCalls(g)):A;return l.updateResult(),d},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Be.useEffect(()=>{l.setOptions(a)},[a,l]),$r(a,f))throw Ds(a,l,r);if(Br({result:f,errorResetBoundary:r,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw f.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,f),a.experimental_prefetchInRender&&!ye.isServer()&&Hr(f,s)&&(u?Ds(a,l,r):c?.promise)?.catch(A).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?f:l.trackResult(f)}function D(t,e){return Dn(t,Jt,e)}var Fe=G(we(),1);function Ie(t,e){let n=K(e),[s]=Fe.useState(()=>new ks(n,t));Fe.useEffect(()=>{s.setOptions(t)},[s,t]);let r=Fe.useSyncExternalStore(Fe.useCallback(a=>s.subscribe(M.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=Fe.useCallback((a,c)=>{s.mutate(a,c).catch(A)},[s]);if(r.error&&dt(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function tn(t,e){return Dn(t,Fs,e)}var O=new As({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}});function V(){return ce()??"__unscoped__"}var w={all:()=>["vfs",V()],item:t=>["vfs",V(),"item",t],itemById:t=>["vfs","item-by-id",t],children:t=>["vfs",V(),"children",t],allChildren:()=>["vfs",V(),"children"],types:t=>["vfs","types",t??"default"],edges:t=>["vfs","edges",t],search:(t,e)=>["vfs",V(),"search",t,...e??[]],items:(t,e)=>["vfs",V(),"items",t,JSON.stringify(e??{})],allItems:()=>["vfs",V(),"items"],tree:(t,e)=>["vfs",V(),"tree",t,e??1],openEnvelope:(t,e)=>["vfs",V(),"open",t,e??"__default__"],allOpenEnvelopes:()=>["vfs",V(),"open"],memberFocus:t=>["vfs","member-focus",t],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(t,e,n)=>["vfs",V(),"get-activity-feed",t,e,n],itemVersions:(t,e,n,s)=>["vfs","item-versions",t,e,n,s],itemHistory:(t,e,n)=>["vfs","item-history",t,e,n],channelMessages:(t,e)=>["vfs",V(),"channel-messages",t,e??"__top__"],allChannelMessages:()=>["vfs",V(),"channel-messages"],channels:t=>["vfs",V(),"channels",t??"all"],allChannels:()=>["vfs",V(),"channels"],notifications:(t,e)=>["vfs",V(),"notifications",t??"all",e??200],allNotifications:()=>["vfs",V(),"notifications"],unreadCounts:()=>["vfs",V(),"unread-counts"],memberships:t=>["memberships",t]};function Gr(){return new Date().toISOString()}function zr(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function de(t){let e=t.path||t.item_path||"",n=e.split("/");n.pop();let s=n.join("/"),r=t.type_data||{};return r.allowed_parent_types&&!r.accepts&&(r.accepts=r.allowed_parent_types),delete r.allowed_parent_types,{id:t.id||t.item_id||"",name:t.name||t.item_name||"",item_type:t.item_type||"unknown",path:e,parent_path:s,is_active:t.is_active!==!1,has_children:t.has_children??!1,created_at:t.created_at||Gr(),updated_at:t.updated_at||Gr(),visibility:t.visibility,type_data:r,scope_item_id:t.scope_item_id,fractal_id:t.fractal_id,parent_instance_id:t.parent_instance_id,owner_principal_id:t.owner_principal_id,created_by_principal_id:t.created_by_principal_id,parent_id:t.parent_id,space_item_id:t.space_item_id,account_item_id:t.account_item_id}}function nn(t){return(t.content?.items||t.items||[]).map(de)}async function Qn(t){try{let e=await P("read",{id:t});if(e.item_name||e.item_path){let s=de(e);return s.path&&O.setQueryData(w.item(s.path),s),s}let n=e.item;if(n){let s=de(n);return s.path&&O.setQueryData(w.item(s.path),s),s}return null}catch{return null}}async function Nn(t){try{let e=await P("read",{path:t});if(e.item_name||e.item_path)return de(e);let n=e.item;return n?de(n):null}catch{return null}}async function Kn(t){try{let e=await P("list",{path:t,limit:200}),n=nn(e);for(let s of n)O.setQueryData(w.item(s.path),s);return n}catch(e){return console.error(`[gateway] Failed to fetch children of ${t}:`,e),[]}}async function Ln(t,e,n){try{let s=await P("list",{path:t,limit:e,offset:n}),r=nn(s);for(let i of r)O.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch children page of ${t}:`,s),{items:[],total_hint:0}}}async function jn(t){let n=await P("types-list",t?{scope_id:t}:{}),s=n.content?.items||n.items||[],r=new Map;for(let i of s){let a=i.name,c=i.type_data;!a||!c||r.set(a,{type_key:a,display_name:c.display_name||a,display_name_plural:c.display_name_plural||a+"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 r}async function Vn(t){try{let e=await P("edges",{item_id:t}),n=e.outgoing||[],s=e.incoming||[],r=[];for(let i of n)r.push({id:i.edge_id||zr(),source_item_id:t,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 s)r.push({id:i.edge_id||zr(),source_item_id:i.source_id||"",target_item_id:t,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return r}catch(e){return console.warn(`[gateway] Failed to fetch edges for ${t}:`,e),[]}}async function Bn(t,e=1,n,s){try{let r={path:t,max_depth:e>0?e:999};n?.length&&(r.item_types=n),s&&(r.limit=s);let i=await P("tree",r),a=nn(i);for(let c of a)O.setQueryData(w.item(c.path),c);return a}catch(r){return console.error(`[gateway] Failed to fetch tree at ${t}:`,r),[]}}async function Wn(t,e=50,n=0){try{let s=await P("get-activity-feed",{scope_path:t,limit:e,offset:n});return s.content?.items||s.items||s.entries||[]}catch(s){return console.error(`[gateway] Failed to fetch recent activity for ${t}:`,s),[]}}async function sn(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;try{let i=await P("item-versions",{id:t,limit:n,offset:s,include_snapshots:r});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${t}:`,i),{versions:[],total:0}}}async function Hn(t,e=50,n=0){return sn(t,{limit:e,offset:n})}async function $n(t,e,n){try{let s={scope_id:t};e?.length&&(s.item_types=e),n&&(s.limit=n);let r=await P("member-focus",s),i=nn(r);for(let a of i)O.setQueryData(w.item(a.path),a);return i}catch(s){return console.error(`[gateway] Failed to fetch member focus for scope ${t}:`,s),[]}}async function Gn(t,e){let n={path:t};e?.mode&&(n.mode=e.mode),e?.strategy&&(n.strategy=e.strategy),e?.arguments&&(n.arguments=e.arguments);let r=await P("open",n);return{item_id:r.item_id,item_path:r.item_path,item_name:r.item_name,item_type:r.item_type,render:r.render,compatible_components:r.compatible_components??[],content:r.content,metadata:r.metadata,instructions:r.instructions}}async function rn(t){let e={item_type:t.type};t.scope&&(e.scope_path=t.scope);let n={};if(t.name&&(n.name=t.name),t.tag&&(n.tag=t.tag),t.parent_id&&(n.parent_id=t.parent_id),t.sort_by&&(n.sort_by=t.sort_by),t.sort_dir&&(n.sort_dir=t.sort_dir),t.offset!=null&&(n.offset=t.offset),t.fields)for(let[s,r]of Object.entries(t.fields))n[`field.${s}`]=String(r);Object.keys(n).length>0&&(e.filters=n),t.limit!=null&&(e.limit=t.limit);try{let s=await P("query",e),r=nn(s);for(let i of r)O.setQueryData(w.item(i.path),i);return{items:r,total_hint:s.total??s.content?.total??r.length}}catch(s){return console.error(`[gateway] Failed to fetch items of type ${t.type}:`,s),{items:[],total_hint:0}}}function Jr(t){return t.filter(e=>e.item_type==="card").map(e=>{let n=e.type_data||{},s=n.payload||{};return{id:e.id||"",path:e.path||"",name:e.name||(e.path||"").split("/").pop()||"",createdAt:e.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:(e.name||"").startsWith("card-")?(e.name||"").substring(5):void 0,parentMessagePath:e.parent_message_path||void 0,visibility:n.visibility||"private",openWith:s.open_with||void 0,hostBundled:s.host_bundled===!0?!0:void 0,bundleExport:s.bundle_export||void 0,launchArguments:s.launch_arguments||void 0,requiresUserAttention:s.requires_user_attention===!0?!0:void 0}}).sort((e,n)=>e.createdAt.localeCompare(n.createdAt))}function Us(t){return t.filter(e=>e.item_type==="message").map(e=>{let n=e.type_data||{},s="user";n.role==="assistant"?s="assistant":n.role==="system"&&(s="system");let r=n.metadata||{};return{id:e.id||"",path:e.path||"",content:n.message||n.content||"",created_at:e.created_at||"",role:s,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:r.intent_card,metadata:Object.keys(r).length>0?r:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((e,n)=>e.seq-n.seq)}async function Yr(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await P("get-channel-messages",n),i=r.messages||r.content?.items||r.items||[];return Us(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${t}:`,n),[]}}async function zn(t,e){try{let n={channel_path:t};e&&(n.parent_message_id=e);let r=await P("get-channel-messages",n),i=r.messages||[],a=Us(i),c=Jr(i),u=new Map,l=[];for(let f of c)if(f.parentMessagePath){let h=u.get(f.parentMessagePath)||[];h.push(f),u.set(f.parentMessagePath,h)}else l.push(f);return{messages:a,messageCards:u,siblingCards:l,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function on(t,e){try{let n={channel_path:t};e?.parentMessageId&&(n.parent_message_id=e.parentMessageId),e?.limit&&(n.limit=e.limit),e?.before_seq!=null&&(n.before_seq=e.before_seq),e?.after_seq!=null&&(n.after_seq=e.after_seq);let r=await P("get-channel-messages",n),i=r.messages||[],a=Jr(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:Us(i),messageCards:c,siblingCards:u,mode:r.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${t}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Un(t){O.invalidateQueries({queryKey:w.children(t)})}function Qs(t){O.invalidateQueries({queryKey:w.item(t)})}function Xr(t,e){Qs(t),Un(t);let n=t.split("/");n.pop();let s=n.join("/")||e;s&&Un(s)}function Zr(t){let e=t+"/";O.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]!=="vfs"?!1:s.some(r=>typeof r=="string"&&(r===t||r.startsWith(e)))}})}function ei(){O.invalidateQueries({queryKey:w.all()})}function ti(t){O.invalidateQueries({queryKey:w.types(t)})}function ni(t,e){t?O.invalidateQueries({queryKey:w.channelMessages(t,e)}):O.invalidateQueries({queryKey:w.allChannelMessages()})}function si(t,e){t&&e?O.invalidateQueries({queryKey:w.openEnvelope(t,e)}):t?O.invalidateQueries({predicate:n=>{let s=n.queryKey;return s[0]==="vfs"&&s[2]==="open"&&s[3]===t}}):O.invalidateQueries({queryKey:w.allOpenEnvelopes()})}var Xo=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...t){Xo&&console.log("[WS]",...t)}var I=null,Et=null,xt=null,an=0,Zo=3e4,ri=1e4,Ot=!1,ea=3e4,Jn=null,ii=!1;function ta(){un(),Jn=setInterval(()=>{Me({type:"ping"})},ea)}function un(){Jn&&(clearInterval(Jn),Jn=null)}function na(){typeof document>"u"||(document.hidden?un():cn()&&(W("Tab visible, reconnecting..."),ln()))}function sa(){ii||typeof document>"u"||(document.addEventListener("visibilitychange",na),ii=!0)}var ee={},Tt=[],Ft=new Map,nt=new Map;function ra(){return Object.keys(ee).some(e=>ee[e]&&ee[e].length>0)||Tt.length>0}function cn(){return Ft.size>0||nt.size>0}async function ln(){if(!cn()){W("ensureConnection: no active subscriptions, skipping");return}if(I&&I.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Et)return W("ensureConnection: connection already in flight, waiting..."),Et;if(I){W("ensureConnection: killing stale WS in state",I.readyState);try{I.close()}catch{}I=null}return Ot=!1,Et=(async()=>{try{let t=typeof window<"u"&&window.__FSAOS_CONFIG__||{},e=ke,s=t.embedToken||null;if(s||(s=await Se()),!s){W("ensureConnection: no token available, will retry"),oi();return}let r=e.startsWith("https")?"wss":"ws",i=e.replace(/^https?:\/\//,""),a=`${r}://${i}/ws`;a+=`?token=${encodeURIComponent(s)}`,W("ensureConnection: opening WS to",a.substring(0,50)+"..."),I=new WebSocket(a),await new Promise((c,u)=>{if(!I)return u(new Error("WebSocket not created"));let l=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",ri,"ms"),I&&I.readyState!==WebSocket.OPEN){try{I.close()}catch{}I=null}u(new Error("WebSocket connection timeout"))},ri);I.onopen=()=>{clearTimeout(l),W("ensureConnection: CONNECTED"),an=0,ia(),(typeof document>"u"||!document.hidden)&&ta(),sa(),c()},I.onmessage=f=>{oa(f.data)},I.onerror=()=>{W("ensureConnection: WS error event")},I.onclose=f=>{clearTimeout(l),W("ensureConnection: WS closed, code:",f.code,"reason:",f.reason),I=null,un(),!Ot&&cn()&&oi(),u(new Error(`WebSocket closed: ${f.code}`))}})}catch(t){W("ensureConnection: failed -",t?.message||t)}finally{Et=null}})(),Et}function oi(){if(xt||typeof document<"u"&&document.hidden)return;let t=Math.min(1e3*Math.pow(2,an)+Math.random()*1e3,Zo);an++,W("scheduleReconnect: attempt",an,"in",Math.round(t),"ms"),xt=setTimeout(()=>{xt=null,cn()&&ln()},t)}function ia(){for(let t of Ft.values())W("resubscribeAll: scope",t.scope_id),Me({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of nt.values())W("resubscribeAll: path",t.path),Me({type:"subscribe_path",path:t.path,event_types:t.event_types})}function Me(t){I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify(t))}function oa(t){try{let e=JSON.parse(t);if(e.type==="subscribed"||e.type==="subscribed_path"||e.type==="unsubscribed"||e.type==="unsubscribed_path"||e.type==="pong")return;if(e.type==="error"){console.warn("[WS] Server error:",e.message);return}if(e.type==="event"||e.event_type){let n=e.event_type||"message",s=e.data||e;s.path&&ee[s.path]&&ee[s.path].forEach(r=>r(s)),ee["*"]&&ee["*"].forEach(r=>r(s));for(let r of Tt)r.eventType!=="*"&&r.eventType!==n||r.filter&&!r.filter(s)||r.callback(s)}}catch{}}function Ns(){!ra()&&Ft.size===0&&nt.size===0&&I&&(Ot=!0,un(),I.close(),I=null,Ot=!1)}function ai(t,e){return ee[t]||(ee[t]=[]),ee[t].push(e),nt.has(t)||(nt.set(t,{path:t,event_types:["token_stream"]}),I&&I.readyState===WebSocket.OPEN&&Me({type:"subscribe_path",path:t,event_types:["token_stream"]})),ln(),()=>{let n=ee[t];if(n){let s=n.indexOf(e);s!==-1&&n.splice(s,1),n.length===0&&(delete ee[t],nt.delete(t),Me({type:"unsubscribe_path",path:t}))}Ns()}}function ae(t,e,n){let r=(Array.isArray(t)?t:[t]).map(i=>({eventType:i,callback:e,filter:n}));return Tt.push(...r),cn()&&ln(),()=>{for(let i of r){let a=Tt.indexOf(i);a!==-1&&Tt.splice(a,1)}Ns()}}function Yn(t,e=["vfs_change","ccm_change"]){return W("subscribeToScope:",t,e),Ft.set(t,{scope_id:t,event_types:e}),I&&I.readyState===WebSocket.OPEN&&Me({type:"subscribe",scope_id:t,event_types:e}),ln(),()=>{Ft.delete(t),Me({type:"unsubscribe",scope_id:t}),Ns()}}function ci(t,e,n={}){Me({type:"emit",scope_id:t,event_type:e,payload:n})}function Ks(){W("disconnectSSE: tearing down"),Ot=!0,un(),I&&(I.close(),I=null),xt&&(clearTimeout(xt),xt=null),Et=null,Ot=!1,an=0;for(let t of Object.keys(ee))delete ee[t];Tt.length=0,Ft.clear(),nt.clear()}function ui(){Me({type:"ping"})}Ce(Ks);var It=new Map,Xn=null,dn=new Map,aa=250;function fn(t){es(),pn(t),Xn=ae("vfs_change",e=>ca(e))}function pn(t){if(It.has(t))return;let e=Yn(t,["vfs_change","ccm_change"]);It.set(t,e)}function Zn(t){let e=It.get(t);e&&(e(),It.delete(t))}function es(){for(let[,t]of It)t();It.clear(),Xn&&(Xn(),Xn=null),dn.forEach(t=>clearTimeout(t)),dn.clear()}Ce(es);function ca(t){let e=t.path,n=t.action;if(!e)return;let s=e.split("/");s.pop();let r=s.join("/")||"/root",i=dn.get(r);i&&clearTimeout(i);let a=setTimeout(()=>{dn.delete(r),ua(n,e,t,r)},aa);dn.set(r,a)}function ua(t,e,n,s){if((t||"").toUpperCase()==="DELETE")O.removeQueries({queryKey:w.item(e)}),O.removeQueries({queryKey:w.children(e)}),O.removeQueries({queryKey:w.tree(e)});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},a=de(i);a&&a.id&&O.setQueryData(w.item(e),a)}catch{}O.invalidateQueries({queryKey:w.children(s)}),O.invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let c=a[2];return e.startsWith(c+"/")||e===c}}),n.item_id&&O.invalidateQueries({queryKey:w.itemById(n.item_id)})}var Ls=G(we(),1),fi=G(di(),1);function pi(t){return P("read",{path:t})}function hi(t,e){return P("list",{path:t,...e})}function mi(t){return P("create",t)}function gi(t){return P("update",t)}function yi(t){return P("create",t)}function _i(t,e){let s=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return P("tools/call",{name:t,instance_path:s,...e||{}})}function vi(t,e,n){return P("signal",{target_id:t,event_name:e,payload:n||{}})}function bi(t){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+t}var wi={signIn:t=>t.provider?k.auth.signInWithOAuth({provider:t.provider,options:{redirectTo:t.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:t.email,password:t.password}),signUp:t=>k.auth.signUp({email:t.email,password:t.password,options:{data:t.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),ot(),O.clear()},getSession:()=>k.auth.getSession().then(t=>t.data.session),getUser:()=>k.auth.getUser().then(t=>t.data.user),onAuthStateChange:t=>{let{data:{subscription:e}}=k.auth.onAuthStateChange((n,s)=>{t({event:n,session:s,user:s?.user??null})});return()=>e?.unsubscribe()},resetPassword:t=>k.auth.resetPasswordForEmail(t),signInWithMagicLink:(t,e)=>k.auth.signInWithOtp({email:t,options:{emailRedirectTo:e||window.location.href}})};function Si(){let t=document.getElementById("root");if(t)try{let e=window.__FSAOS_COMPONENT__;if(!e){t.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=e.default||e,s=window.__FSAOS_ITEM_DATA__||null,r=s?{item:s,...s}:{};(0,fi.createRoot)(t).render((0,Ls.createElement)(Zt,{client:O},(0,Ls.createElement)(n,r)))}catch(e){console.error("[FSAOS] Failed to mount root component:",e),t.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(e.message||e)+"</pre></div>"}}function Ci(){let t=window.React,e=window.ReactDOM,n=window.__FSAOS_GATEWAY__,s=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let r={react:t,"react-dom":e,"react-dom/client":e,"react/jsx-runtime":{jsx:t?.createElement,jsxs:t?.createElement,Fragment:t?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":s||{}};window.require=function(a){if(r[a])return r[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=G(we(),1),la=G(Pi(),1),da=G(An(),1);function N(){return(0,y.useSyncExternalStore)(bn,Lt,Lt)}function Ti(){return N(),Sn()}function Oi(t){return N(),D({queryKey:w.item(t),queryFn:()=>Nn(t),enabled:!!t})}function Fi(t){return N(),D({queryKey:w.itemById(t),queryFn:()=>Qn(t),enabled:!!t})}function Vs(t){return N(),D({queryKey:w.children(t),queryFn:()=>Kn(t),enabled:!!t})}function Ii(t){let e=Vs(t);return{...e,children:e.data??[]}}function Mi(t,e=1){return N(),D({queryKey:w.tree(t,e),queryFn:()=>Bn(t,e),enabled:!!t})}function ki(t,e){return N(),D({queryKey:w.search(t,e),queryFn:async()=>{let n={query:t};e?.length&&(n.item_types=e);let s=await P("search",n);return(s.content?.items||s.items||[]).map(de)},enabled:!!t&&t.length>0})}function Ai(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return D({queryKey:["vfs",ce()??"__unscoped__","resolve",JSON.stringify(e??{})],queryFn:async()=>await P("resolve",e),enabled:!!e?.query&&e.query.length>0})}function qi(t){N();let e=(0,y.useMemo)(()=>t,[JSON.stringify(t)]);return D({queryKey:w.items(e?.type??"",e),queryFn:()=>rn(e),enabled:!!e?.type,select:n=>n.items})}function Di(t){N();let e=t?.limit??20,n=(0,y.useMemo)(()=>t,[JSON.stringify(t)]),s=tn({queryKey:["vfs",ce()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>rn({...n,limit:e,offset:i}),initialPageParam:0,getNextPageParam:(i,a,c)=>{if(!(i.items.length<e))return c+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!s.data?.pages)return[];let i=new Set,a=[];for(let c of s.data.pages)for(let u of c.items)u.id&&!i.has(u.id)&&(i.add(u.id),a.push(u));return a},[s.data?.pages]),fetchNextPage:s.fetchNextPage,isFetchingNextPage:s.isFetchingNextPage,isExhausted:!s.hasNextPage,isLoading:s.isLoading,isFetching:s.isFetching,error:s.error,totalHint:s.data?.pages?.[0]?.total_hint}}function Ui(t){N();let e=20,n=tn({queryKey:["vfs",ce()??"__unscoped__","infinite-children",t??""],queryFn:async({pageParam:r=0})=>Ln(t,e,r),initialPageParam:0,getNextPageParam:(r,i,a)=>{if(!(r.items.length<e))return a+r.items.length},enabled:!!t});return{allItems:(0,y.useMemo)(()=>{if(!n.data?.pages)return[];let r=new Set,i=[];for(let a of n.data.pages)for(let c of a.items)c.id&&!r.has(c.id)&&(r.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 Qi(t){return N(),D({queryKey:w.edges(t),queryFn:()=>Vn(t),enabled:!!t})}function ts(t){return N(),D({queryKey:w.types(t),queryFn:()=>jn(t)})}function Ni(t,e){let n=ts(e);return{...n,data:n.data?.get(t)??void 0}}function Ki(t,e){N();let n=(0,y.useMemo)(()=>e?.arguments,[JSON.stringify(e?.arguments)]),s=e?.mode,r=e?.strategy,i=e?.width;return D({queryKey:[...w.openEnvelope(t,r),i],queryFn:async()=>{let a=await Gn(t,{mode:s,strategy:r,arguments:n});if(i&&a.render?.props?.url){let c=a.render.props.url,u=c.includes("?")?"&":"?";a.render.props.url=`${c}${u}w=${i}`}return a},enabled:!!t})}var Ei={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 Li(t){let e=ts(t),n=e.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:d=>n.get(d.item_type)?.is_container??!1,isScope:d=>n.get(d.item_type)?.is_scope??!1,isScopeType:d=>n.get(d)?.is_scope??!1,isContainerType:d=>n.get(d)?.is_container??!1,getTypeDefinition:d=>n.get(d),getTypeColor:d=>n.get(d)?.color??"gray",getTypeIcon:d=>n.get(d)?.icon??"File",getTypeDisplayName:d=>n.get(d)?.display_name??d,getKnownEdgeTypes:()=>Object.entries(Ei).map(([d,v])=>({key:d,label:v})),getEdgeTypeLabel:d=>Ei[d]??d.replace(/_/g," "),allTypes:n,loading:e.isLoading}),[n,e.isLoading])}function ji(t,e,n){return N(),D({queryKey:w.memberFocus(t),queryFn:()=>$n(t,e,n),enabled:!!t})}function Vi(t,e={}){let{limit:n=50,offset:s=0,include_snapshots:r=!1}=e;return D({queryKey:w.itemVersions(t,String(n),String(s),String(r)),queryFn:()=>sn(t,{limit:n,offset:s,include_snapshots:r}),enabled:!!t})}function Bi(t,e=50,n=0){return D({queryKey:w.itemHistory(t,String(e),String(n)),queryFn:()=>Hn(t,e,n),enabled:!!t})}function Wi(t,e=50,n=0){return N(),D({queryKey:w.recentActivity(t,String(e),String(n)),queryFn:()=>Wn(t,e,n),enabled:!!t})}function Hi(){let[t,e]=(0,y.useState)(null),[n,s]=(0,y.useState)(!0),[r,i]=(0,y.useState)(null);return(0,y.useEffect)(()=>{let a=!1;return Cn().then(c=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};e({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:u.componentPath||"",isEmbed:!!u.embedToken}),s(!1)}}).catch(c=>{a||(i(c instanceof Error?c:new Error(String(c))),s(!1))}),()=>{a=!0}},[]),{data:t,loading:n,error:r}}function $i(){let{user:t}=ns(),[e,n]=(0,y.useState)(null),[s,r]=(0,y.useState)(null),i=(0,y.useRef)(!1),a=D({queryKey:w.memberships(t?.id??"anonymous"),queryFn:async()=>((await P("list-memberships",{})).memberships||[]).map(d=>({accountId:d.account_id,path:d.account_path,name:d.account_name,role:d.role||"member",typeData:d.account_type_data||{},joinedAt:d.joined_at,via:d.via,placement:d.placement,subordinateTo:d.subordinate_to??null,cascadeAnchorId:d.cascade_anchor_id??null,isAccount:d.is_account??void 0,isSpace:d.is_space??void 0,isOwner:d.is_owner??void 0,billingResponsible:d.billing_responsible??void 0,grantedVia:d.granted_via??null,grantedUnderAccountId:d.granted_under_account_id??null,personalSpaceId:d.personal_space_id??null,personalSpacePath:d.personal_space_path??null})),enabled:!!t?.id,staleTime:1e3*60*2}),c=a.data??[],u=(0,y.useMemo)(()=>c.filter(h=>h.placement!==void 0?h.placement==="switcher_entry"&&h.isAccount===!0:!0),[c]);(0,y.useEffect)(()=>{if(!t?.id){i.current=!1,n(null),r(null);return}i.current||u.length!==0&&(u.length===1?(n(u[0]),Kt(u[0].path),fn(u[0].accountId),i.current=!0):u.length>1&&(i.current=!0))},[t?.id,u]);let l=(0,y.useCallback)(h=>{let g=u.find(d=>d.path===h);g&&(n(g),Kt(g.path),fn(g.accountId),r(null))},[u]),f=(0,y.useCallback)(h=>{s&&Zn(s),r(h),pn(h)},[s]);return{accounts:u,allMemberships:c,currentAccount:e,mountedScope:s,switchAccount:l,mountScope:f,loading:a.isLoading,error:a.error}}function ns(){let[t,e]=(0,y.useState)(null),[n,s]=(0,y.useState)(null),[r,i]=(0,y.useState)(!0),a=(0,y.useRef)(null);(0,y.useEffect)(()=>{k.auth.getSession().then(({data:d,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(d?.session??null),e(d?.session?.user??null),i(!1)}).catch(d=>{console.warn("[useAuth] getSession threw, clearing stale session:",d?.message),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1)});let{data:{subscription:g}}=k.auth.onAuthStateChange((d,v)=>{if(d==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),s(null),e(null),i(!1);return}s(v),e(v?.user??null),i(!1)});return a.current=g,()=>{g?.unsubscribe()}},[]);let c=(0,y.useCallback)(async g=>g.provider?k.auth.signInWithOAuth({provider:g.provider,options:g.redirectTo?{redirectTo:g.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:g.email,password:g.password}),[]),u=(0,y.useCallback)(async g=>k.auth.signUp({email:g.email,password:g.password,options:{data:g.metadata||{}}}),[]),l=(0,y.useCallback)(async()=>{await k.auth.signOut(),ot(),O.clear()},[]),f=(0,y.useCallback)(async g=>{let{error:d}=await k.auth.resetPasswordForEmail(g);if(d)throw d},[]),h=(0,y.useCallback)(async(g,d)=>{let{error:v}=await k.auth.signInWithOtp({email:g,options:d?{emailRedirectTo:d}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:t,session:n,loading:r,signIn:c,signUp:u,signOut:l,resetPassword:f,signInWithMagicLink:h}}function Gi(t){let[e,n]=(0,y.useState)(null),[s,r]=(0,y.useState)(!1),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t){n(null),r(!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(t))r(!0),P("resolve-asset",{asset_id:t}).then(u=>{u.success&&u.public_url?n({url:u.public_url,id:u.asset_id,name:u.name,mimeType:u.mime_type,width:u.width,height:u.height,sizeBytes:u.size_bytes}):a(new Error(u.error||"Asset not found")),r(!1)}).catch(u=>{a(u instanceof Error?u:new Error(String(u))),r(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+t}),r(!1)}},[t]),{data:e,loading:s,error:i}}var hn={},xi={};Ce(()=>{for(let t of Object.keys(hn))delete hn[t]});var zi=null;function Ji(t){zi=t,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=t)}function fa(t){switch(t){case"react":return typeof window<"u"&&window.React||y.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||la;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}:da;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||zi||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${t}`),{}}}function pa(t,e){return t.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,s,r,i)=>`${s}.${e}${i}`)}async function ha(t,e){if(!xi[t])try{let n=await fetch(t);if(!n.ok)return;let s=await n.text();if(!s.trim()||s.includes("No CSS bundle for this component"))return;e&&!s.includes(`.fsaos-c-${e}`)&&(s=pa(s,`fsaos-c-${e}`));let r=document.createElement("style");r.setAttribute("data-fsaos-component-css",t),e&&r.setAttribute("data-fsaos-component-id",e),r.textContent=s,document.head.appendChild(r),xi[t]=r}catch{}}function ma(t){let e=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=s=>{e=s};try{let s=["var require = arguments[0];",t,"return window.__FSAOS_COMPONENT__;"].join(`
|
|
3
|
+
`),i=new Function(s)(fa),a=e??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Bs(t){let[e,n]=(0,y.useState)(null),[s,r]=(0,y.useState)(!0),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!t)return;let c=!1;r(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let f=1,h=t+"@v1",g=l+t+"/__bundle.js";try{let S=await fetch(l+t+"/__meta",{cache:"no-store"});S.ok&&(f=(await S.json()).version||1,h=t+"@v"+f,g=l+t+"/__bundle.v"+f+".js")}catch{g=l+t+"/__bundle.js?v="+Date.now()}if(c)return;if(hn[h]){n(()=>hn[h]),r(!1);return}let d=await fetch(g);if(!d.ok)throw new Error(`Failed to fetch bundle: ${d.status} ${d.statusText} (${g})`);let v=await d.text();if(c)return;let p=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");ha(p).catch(()=>{});let m=ma(v);if(!m)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof m!="function")throw new Error(`Bundle export is not a React component (got ${typeof m})`);hn[h]=m,c||(n(()=>m),r(!1))}catch(f){c||(a(f instanceof Error?f:new Error(String(f))),r(!1))}})(),()=>{c=!0}},[t]),{Component:e,loading:s,error:i}}var ga=["--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 Yi(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let e={},n=getComputedStyle(document.documentElement);return ga.forEach(s=>{e[s]=n.getPropertyValue(s).trim()}),{tokens:e}},[]),loading:!1,error:null}}function Xi(t,e){return{data:{allowed:!0},loading:!1,error:null}}function Zi(t,e){let n={};return(e||[]).forEach(s=>{n[s]=!0}),{data:n,loading:!1,error:null}}var re=null,Mt=null,js=new Set;function ya(){js.forEach(t=>t())}Ce(()=>{re=null,Mt=null});async function eo(t){let e=t;if(!e){let{data:s}=await k.auth.getSession();e=s?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null};if(!e)return n;if(re&&re.authUserId===e){let{principalId:s,displayName:r,createdAt:i,metadata:a}=re;return{principalId:s,displayName:r,createdAt:i,metadata:a}}return Mt||(Mt=(async()=>{try{let{data:s,error:r}=await k.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",e).eq("principal_type","user").maybeSingle();if(r)return console.warn("[SDK] Could not resolve principal:",r.message),n;let i={principalId:s?.id??null,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null};return re={authUserId:e,...i},i}finally{Mt=null}})(),Mt)}async function to(t){return(await eo(t)).principalId}function no(){let t=ns(),e=t.user,n=re?.authUserId===e?.id?re:null,[s,r]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let c=re;c&&c.authUserId===e?.id&&r({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata})};return js.add(a),()=>{js.delete(a)}},[e?.id]),(0,y.useEffect)(()=>{if(!e?.id){r(null),i.current=null;return}i.current===e.id&&s?.principalId!=null||(i.current=e.id,eo(e.id).then(a=>{r(a)}))},[e?.id]),t.loading?{data:null,loading:!0,error:null}:e?{data:{id:e.id,principalId:s?.principalId??null,email:e.email,display_name:s?.displayName??void 0,created_at:s?.createdAt??void 0,role:e.role||e.app_metadata?.role||"user",authenticated:!0,metadata:s?.metadata??e.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function so(){return{data:null,loading:!1,error:null}}function ro(t){let{path:e,...n}=t,s=Bs(e),r=s.Component,{loading:i,error:a}=s;return i?(0,y.createElement)("div",{className:"fsaos-loading"},""):a?(0,y.createElement)("div",{className:"fsaos-error"},"Failed to load component"):r?(0,y.createElement)(r,n):null}function io(t){return t.children}function oo(t){let e=N(),{channelPath:n,parentMessageId:s,realtime:r=!0,enabled:i}=t,a=i!==void 0?i&&!!n:!!n,c=(0,y.useMemo)(()=>w.channelMessages(n??"",s),[n,s,e]),u=K(),l=(0,y.useRef)(null),f=D({queryKey:c,queryFn:()=>zn(n,s),enabled:a});(0,y.useEffect)(()=>{if(!r||!a)return;let p=ae("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:c})},500)},m=>(m.item_type==="message"||m.item_type==="card")&&typeof m.path=="string"&&m.path.startsWith(n));return()=>{p(),l.current&&clearTimeout(l.current)}},[r,a,n,c,u]);let h=f.data,g=h?.messages??[],d=h?.messageCards??new Map,v=h?.siblingCards??[];return{messages:g,messageCards:d,siblingCards:v,threads:(0,y.useMemo)(()=>g.filter(p=>p.reply_count>0),[g]),isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}}function ao(t){N();let{channelPath:e,parentMessageId:n,limit:s=50,realtime:r=!0,enabled:i=!0}=t,a=!!n,c=i&&!!e,u=tn({queryKey:[...w.channelMessages(e||"",n),"infinite",s],queryFn:async({pageParam:p})=>on(e,{parentMessageId:n,limit:s,before_seq:a?void 0:p,after_seq:a?p:void 0}),initialPageParam:void 0,getNextPageParam:p=>!a||p.messages.length<s?void 0:p.messages[p.messages.length-1]?.seq,getPreviousPageParam:p=>a||p.messages.length<s?void 0:p.messages[0]?.seq,enabled:c}),l=(0,y.useMemo)(()=>{if(!u.data?.pages)return[];let p=new Set,m=[];for(let S of u.data.pages)for(let C of S.messages)p.has(C.id)||(p.add(C.id),m.push(C));return m.sort((S,C)=>S.seq-C.seq)},[u.data?.pages]),{messageCards:f,siblingCards:h}=(0,y.useMemo)(()=>{let p=new Map,m=[];if(!u.data?.pages)return{messageCards:p,siblingCards:m};let S=new Set;for(let C of u.data.pages){for(let[E,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let B=p.get(E)||[];B.push(L),p.set(E,B)}for(let E of C.siblingCards)S.has(E.id)||(S.add(E.id),m.push(E))}return{messageCards:p,siblingCards:m}},[u.data?.pages]),g=K(),d=(0,y.useRef)(null),v=(0,y.useMemo)(()=>[...w.channelMessages(e||"",n),"infinite",s],[e,n,s]);return(0,y.useEffect)(()=>{if(!r||!e||!c)return;let p=ae("vfs_change",()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{let m=g.getQueryData(v);if(!m?.pages?.length){g.invalidateQueries({queryKey:v});return}let S=0;for(let C of m.pages)for(let E of C.messages)E.seq>S&&(S=E.seq);if(S===0){g.invalidateQueries({queryKey:v});return}try{let C=await on(e,{parentMessageId:n,limit:s,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){g.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let E=Math.min(...C.messages.map(U=>U.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),g.invalidateQueries({queryKey:v});return}}g.setQueryData(v,E=>{if(!E)return E;let U=[...E.pages],L=U.length-1,B=U[L],st=new Set(B.messages.map(T=>T.id)),ne=C.messages.filter(T=>!st.has(T.id)),Q=[...B.messages,...ne].sort((T,We)=>T.seq-We.seq),J=new Map(B.messageCards);for(let[T,We]of C.messageCards){let H=J.get(T)||[],kt=new Set(H.map(rs=>rs.id)),To=We.filter(rs=>!kt.has(rs.id));J.set(T,[...H,...To])}let fe=new Set(B.siblingCards.map(T=>T.id)),pe=C.siblingCards.filter(T=>!fe.has(T.id)),he=[...B.siblingCards,...pe];return U[L]={...B,messages:Q,messageCards:J,siblingCards:he},{...E,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),g.invalidateQueries({queryKey:v})}},500)},m=>(m.item_type==="message"||m.item_type==="card")&&typeof m.path=="string"&&m.path.startsWith(e));return()=>{p(),d.current&&clearTimeout(d.current)}},[r,e,c,v,g,n,s]),{messages:l,messageCards:f,siblingCards:h,threads:l.filter(p=>p.reply_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasPreviousPage??!1,fetchPreviousPage:u.fetchPreviousPage,isFetchingPreviousPage:u.isFetchingPreviousPage??!1,hasNextPage:u.hasNextPage??!1,fetchNextPage:u.fetchNextPage,isFetchingNextPage:u.isFetchingNextPage??!1}}function _a(t){return t==="on"||t==="auto"?"on":"off"}function va(t){let e=t.type_data||{};return{id:t.channel_id||"",path:t.channel_path||"",name:t.channel_name||"",displayName:t.display_name||t.channel_name||"",aiMode:_a(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:t.updated_at||"",chatScopePath:t.chat_scope_path||"",contextId:t.context_id||"",contextPath:t.context_path||"",contextType:t.context_type||"",contextName:t.context_name||"",contextDisplayName:t.context_display_name||"",contextPrincipalId:t.context_principal_id,accountId:t.account_id||"",accountPath:t.account_path||"",accountDisplayName:t.account_display_name||"",memberRole:t.member_role||"member",memberPath:t.member_path||"",modePath:t.mode_path||"",autoPilot:t.auto_pilot||e.auto_pilot||!1}}function ss(t={}){let e=N(),{realtime:n=!0,enabled:s=!0}=t,r=K(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[e]),c=D({queryKey:a,queryFn:async()=>((await P("list-channels",{})).channels||[]).map(va),enabled:s});return(0,y.useEffect)(()=>{if(!n||!s)return;let l=ae("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message"),f=ae("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message");return()=>{l(),f(),i.current&&clearTimeout(i.current)}},[n,s,a,r]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function co(t={}){let e=ss(t),n=(0,y.useMemo)(()=>e.channels.filter(s=>!s.isDm),[e.channels]);return{...e,channels:n}}function uo(t={}){let e=ss(t),n=(0,y.useMemo)(()=>e.channels.filter(s=>s.isDm),[e.channels]);return{...e,channels:n}}function Ws(t={}){let e=N(),{filter:n="all",limit:s=200,realtime:r=!0,enabled:i=!0}=t,a=K(),c=(0,y.useRef)(null),u=(0,y.useMemo)(()=>w.notifications(n,s),[n,s,e]),l=D({queryKey:u,queryFn:async()=>{let h={limit:s};return n==="unread"&&(h.filter="unread"),(await P("get-notifications",h)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!r||!i)return;let h=["vfs_change","ccm_change"].map(g=>ae(g,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},d=>d.item_type==="notification"||d.item_type==="message"));return()=>{h.forEach(g=>g()),c.current&&clearTimeout(c.current)}},[r,i,u,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function lo(t={}){let{channels:e,realtime:n=!0,enabled:s=!0}=t,{notifications:r,isLoading:i,isFetching:a,error:c,refetch:u}=Ws({filter:"unread",limit:200,realtime:n,enabled:s}),l=(0,y.useMemo)(()=>{let d=new Map;for(let v of r)v.is_unread&&v.channel_id&&d.set(v.channel_id,(d.get(v.channel_id)||0)+1);return d},[r]),f=(0,y.useMemo)(()=>{let d=0;return l.forEach(v=>{d+=v}),d},[l]),{dmUnread:h,channelUnread:g}=(0,y.useMemo)(()=>{if(!e)return{dmUnread:0,channelUnread:0};let d=new Set(e.filter(m=>m.isDm).map(m=>m.id)),v=0,p=0;return l.forEach((m,S)=>{d.has(S)?v+=m:p+=m}),{dmUnread:v,channelUnread:p}},[e,l]);return{unreadByChannel:l,totalUnread:f,dmUnread:h,channelUnread:g,isLoading:i,isFetching:a,error:c,refetch:u}}function fo(){let t=K();return Ie({mutationFn:e=>P("create",e),onSuccess:(e,n)=>{let s=n.parent_path;s&&t.invalidateQueries({queryKey:w.children(s)})}})}function po(){let t=K();return Ie({mutationFn:e=>P("update",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.invalidateQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function ho(){return Ie({mutationFn:t=>P("update-principal",t),onSuccess:(t,e)=>{if(!re)return;let n=t&&typeof t=="object"&&t.metadata?t.metadata:{...re.metadata??{},...typeof e.language=="string"?{language:e.language}:{},...typeof e.timezone=="string"?{timezone:e.timezone}:{},..."avatar_file_id"in e?{avatar_file_id:e.avatar_file_id}:{}};re={...re,displayName:typeof e.display_name=="string"?e.display_name:re.displayName,metadata:n},ya()}})}function mo(){let t=K();return Ie({mutationFn:e=>P("delete",e),onSuccess:(e,n)=>{let s=n.path;if(s){t.removeQueries({queryKey:w.item(s)});let r=s.split("/");r.pop();let i=r.join("/");i&&t.invalidateQueries({queryKey:w.children(i)})}}})}function go(){let t=K();return Ie({mutationFn:e=>P("move",e),onSuccess:(e,n)=>{let s=n.path,r=n.new_parent_path;if(s){t.invalidateQueries({queryKey:w.item(s)});let i=s.split("/");i.pop();let a=i.join("/");a&&t.invalidateQueries({queryKey:w.children(a)})}r&&t.invalidateQueries({queryKey:w.children(r)})}})}function yo(){let t=K();return Ie({mutationFn:e=>P("link",e),onSuccess:(e,n)=>{let s=n.source_id,r=n.target_id;s&&t.invalidateQueries({queryKey:w.edges(s)}),r&&t.invalidateQueries({queryKey:w.edges(r)})}})}function _o(t,e){let n=K(),{optimistic:s,...r}=e??{};return Ie({mutationFn:i=>P(t,i),onMutate:s?async i=>{await n.cancelQueries({queryKey:s.queryKey});let a=n.getQueryData(s.queryKey);return n.setQueryData(s.queryKey,c=>s.update(c,i)),{previous:a}}:void 0,onError:(i,a,c)=>{s&&c?.previous!==void 0&&n.setQueryData(s.queryKey,c.previous),r.onError?.(i)},onSuccess:r.onSuccess,onSettled:s?()=>{n.invalidateQueries({queryKey:s.queryKey})}:void 0})}function vo(t,e,n){let s,r,i,a=!0;if(typeof t=="string")s=t,r=e,i=n;else{r=t;let l=e;s=l.eventType,i=l.filter,a=l.enabled??!0}let c=(0,y.useRef)(r),u=(0,y.useRef)(i);(0,y.useEffect)(()=>{c.current=r,u.current=i},[r,i]),(0,y.useEffect)(()=>a?ae(s,f=>c.current(f),u.current?f=>u.current(f):void 0):void 0,[s,a])}function bo(t){let{queryKey:e,queryFn:n,eventType:s,filter:r,enabled:i=!0,debounceMs:a=500}=t,c=K(),u=(0,y.useRef)(null),l=D({queryKey:e,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let f=ae(s,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:e})},a)},r);return()=>{f(),u.current&&clearTimeout(u.current)}},[s,i,a,c,JSON.stringify(e)]),l}function wo(t){N();let e=(0,y.useMemo)(()=>t?typeof t=="string"?{path:t}:t:null,[typeof t=="string"?t:JSON.stringify(t)]),n=!!e&&!!(e.key||e.path||e.item_id),s=e?.key??e?.path??e?.item_id??"",r=D({queryKey:["vfs",ce()??"__unscoped__","arrangement",s],queryFn:async()=>{if(!e)return null;let f=await P("resolve-arrangement",e);return f?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",f?.error),null):f??null},enabled:n}),i=r.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),c=i?.resolution_level??null,u=(0,y.useMemo)(()=>{let h=(i?.type_data??null)?.order;return Array.isArray(h)?h:null},[i]),l=(0,y.useCallback)(f=>{if(!u||!f?.length)return f??[];let h=p=>p.id??p.name??"",g=new Map(u.map((p,m)=>[p,m])),d=[],v=[];for(let p of f)(g.has(h(p))?d:v).push(p);return d.sort((p,m)=>g.get(h(p))-g.get(h(m))),[...d,...v]},[u]);return{...r,arrangement:i,resolvedChildren:a,resolutionLevel:c,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function ba(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function wa(t,e){return e&&e.length>0?"select":t==="boolean"?"toggle":t==="integer"||t==="number"?"range":t==="string"?"text":"none"}function Sa(t,e){return!(t==="object"||t==="array")}function Ca(t){return["string","number","integer","boolean"].includes(t)}function Ra(t){return t!=="object"&&t!=="array"}function So(t,e,n,s){let r=t?.properties;if(!r||typeof r!="object")return[];let i=[];for(let[a,c]of Object.entries(r)){let u=c.type||"string",l=c.enum,f=Sa(u,l),h=Ca(u),g=wa(u,l);i.push({key:a,label:c.title||ba(a),type:u,description:c.description,enum_values:l,default_value:n[a]??s[a]??c.default,editable:e,filterable:f,sortable:h,filter_widget:g})}return i}function Hs(t){let e=t.default_data||{},n=t.field_defaults||{},s=So(t.input_schema,!0,e,n),r=So(t.system_schema,!1,e,n),i=[...s,...r],a=i.filter(l=>Ra(l.type)),c=i.filter(l=>l.filterable),u=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:c,sortable:u,form_fields:s,system_fields:r}}function Co(t){return{field:"updated_at",direction:"desc"}}function Ro(t){let e=Hs(t),n=new Set(t.input_schema?.required||[]);return e.form_fields.filter(s=>n.has(s.key)||s.default_value===void 0)}var te=G(we(),1);var Pa=0;function Ea(){return`upload_${Date.now()}_${++Pa}`}async function Po(t,e,n,s){let r=e.name||(t instanceof File?t.name:`file-${Date.now()}`),i=t.type||"application/octet-stream",a=e.itemType||"file",u=await P("create",{parent_path:e.parentPath,item_type:a,name:r,type_data:{...e.typeData||{},file_source:{type:"upload",content_type:i}}});if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let l=u.id,f=u.path;if(u.storage_completed&&u.file_ref)return{itemId:l,itemPath:f,fileRef:u.file_ref};let h=u.storage_key,g=u.upload_token,d=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!h)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await xa(d,h,g,t,i,n,s);let v=await Eo(l,h,i);return{itemId:l,itemPath:f,fileRef:v}}function xa(t,e,n,s,r,i,a){return new Promise((c,u)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${t}/upload`),l.setRequestHeader("X-Storage-Key",e),l.setRequestHeader("Content-Type",r),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=f=>{f.lengthComputable&&i&&i(Math.round(f.loaded/f.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():u(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>u(new Error("Storage upload network error")),l.ontimeout=()=>u(new Error("Storage upload timed out")),a){if(a.aborted){u(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),u(new Error("Upload cancelled"))})}l.send(s)})}async function Eo(t,e,n){let s=await Se(),r=await fetch(`${ke}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({item_id:t,storage_key:e,content_type:n})});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${r.status} \u2014 ${a.slice(0,300)}`)}let i=await r.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function xo(){let[t,e]=(0,te.useState)([]),n=K(),s=(0,te.useRef)(t);s.current=t;let r=(0,te.useCallback)((p,m)=>{e(S=>S.map(C=>C.id===p?{...C,...m}:C))},[]),i=(0,te.useCallback)(p=>{e(m=>[...m,p])},[]),a=(0,te.useCallback)(async(p,m,S,C,E)=>{let U=S.name||m.name,L=m.type||"application/octet-stream",B=S.itemType||"file",st=E?.itemId||null,ne=E?.itemPath||null,Q=E?.storageKey||null,J=E?.uploadToken||null,fe=E?.storageWorkerUrl||null;try{if(!C||C==="create"){r(p,{status:"creating",error:null,_failedAt:null});let T=await P("create",{parent_path:S.parentPath,item_type:B,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!T.id)throw Object.assign(new Error(T.error||T.message||"Failed to create file item"),{_step:"create"});if(st=T.id,ne=T.path,r(p,{itemId:st,itemPath:ne}),T.storage_completed&&T.file_ref){r(p,{status:"complete",progress:100,fileRef:T.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=T.storage_key,J=T.upload_token||"",fe=T.storage_worker_url||"https://fsaos-storage.radns.workers.dev",r(p,{_storageKey:Q,_uploadToken:J,_storageWorkerUrl:fe}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(r(p,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((T,We)=>{let H=new XMLHttpRequest;r(p,{_xhr:H}),H.open("PUT",`${fe}/upload`),H.setRequestHeader("X-Storage-Key",Q),H.setRequestHeader("Content-Type",L),J&&H.setRequestHeader("X-Upload-Token",J),H.upload.onprogress=kt=>{kt.lengthComputable&&r(p,{progress:Math.round(kt.loaded/kt.total*100)})},H.onload=()=>{H.status>=200&&H.status<300?T():We(Object.assign(new Error(`Storage upload failed: HTTP ${H.status}`),{_step:"upload"}))},H.onerror=()=>We(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),H.ontimeout=()=>We(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),H.send(m)}),r(p,{progress:100,_xhr:null})),r(p,{status:"confirming",error:null,_failedAt:null});let pe=await Eo(st,Q,L);r(p,{status:"complete",fileRef:pe}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(pe){let he=pe?.message||String(pe),T=pe?._step||"create";r(p,{status:"error",error:he,_failedAt:T,_xhr:null})}},[r,n]),c=(0,te.useCallback)((p,m)=>{let S=Ea();i({id:S,file:p,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:m,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,p,m)},[i,a]),u=(0,te.useCallback)((p,m)=>{for(let S of p)c(S,m)},[c]),l=(0,te.useCallback)(p=>{let m=s.current.find(E=>E.id===p);if(!m||m.status!=="error")return;let S=m._failedAt||"create",C=m._storageKey&&m.itemId?{storageKey:m._storageKey,uploadToken:m._uploadToken||"",storageWorkerUrl:m._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:m.itemId,itemPath:m.itemPath||""}:void 0;a(p,m.file,m.options,S,C)},[a]),f=(0,te.useCallback)(p=>{let m=s.current.find(S=>S.id===p);m&&(m._xhr&&m._xhr.abort(),r(p,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[r]),h=(0,te.useCallback)(p=>{e(m=>m.filter(S=>S.id!==p))},[]),g=(0,te.useCallback)(()=>{e(p=>p.filter(m=>m.status!=="complete"))},[]),d=t.some(p=>p.status==="creating"||p.status==="uploading"||p.status==="confirming"),v=t.map(({_storageKey:p,_uploadToken:m,_storageWorkerUrl:S,_xhr:C,_failedAt:E,...U})=>U);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:f,removeUpload:h,clearCompleted:g,isUploading:d}}Ji($s);return Do($s);})();
|
|
4
4
|
|
|
5
5
|
/* ── Auto-setup: require shim + mount + backward compat globals ── */
|
|
6
6
|
(function() {
|