@omniviewdev/runtime 0.6.0 → 0.7.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.
@@ -3,6 +3,8 @@ type VariantType = 'default' | 'success' | 'error' | 'warning' | 'info';
3
3
  type SnackbarContextType = {
4
4
  showSnackbar(message: string, status: VariantType, icon?: string, details?: string): void;
5
5
  showSnackbar(options: ShowSnackbarOptions): void;
6
+ openNotifications(): void;
7
+ notificationCount: number;
6
8
  };
7
9
  type SnackbarProviderProps = {
8
10
  children: ReactNode;
package/dist/index.cjs CHANGED
@@ -1,2 +1,4 @@
1
- "use strict";var ot=Object.defineProperty;var it=(t,e,n)=>e in t?ot(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var L=(t,e,n)=>it(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("react/jsx-runtime"),l=require("react"),H=require("react-router-dom");require("./index-D_aIcqH0.cjs");const E=require("./graphservice-CWIVejHl.cjs"),N=require("./models-CGYstu7u.cjs"),D=require("./events-CtgYnKmS.cjs"),S=require("@tanstack/react-query"),at=require("@omniviewdev/base-ui"),ct=require("./legacyEnum-DkV5yRdA.cjs"),te=l.createContext(void 0),F={PLUGIN_NOT_FOUND:"omniview:plugin/not-found",PLUGIN_NOT_LOADED:"omniview:plugin/not-loaded",PLUGIN_ALREADY_LOADED:"omniview:plugin/already-loaded",PLUGIN_INSTALL_FAILED:"omniview:plugin/install-failed",PLUGIN_LOAD_FAILED:"omniview:plugin/load-failed",PLUGIN_BUILD_FAILED:"omniview:plugin/build-failed",PLUGIN_COMMITTED_CLEANUP_PENDING:"omniview:plugin/committed-cleanup-pending",PLUGIN_COMMIT_UNCERTAIN:"omniview:plugin/commit-uncertain",SETTINGS_MISSING_CONFIG:"omniview:settings/missing-config",SETTINGS_INVALID_CONFIG:"omniview:settings/invalid-config",RESOURCE_NOT_FOUND:"omniview:resource/not-found",RESOURCE_FORBIDDEN:"omniview:resource/forbidden",RESOURCE_UNAUTHORIZED:"omniview:resource/unauthorized",RESOURCE_CONFLICT:"omniview:resource/conflict",RESOURCE_TIMEOUT:"omniview:resource/timeout",RESOURCE_LIMIT:"omniview:resource/limit",RESOURCE_CONTINUATION_EXPIRED:"omniview:resource/continuation-expired",RESOURCE_RESET_REQUIRED:"omniview:resource/reset-required",RESOURCE_PARTIAL:"omniview:resource/partial",RESOURCE_PROVIDER_ERROR:"omniview:resource/provider-error",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",SESSION_NOT_FOUND:"omniview:session/not-found",SESSION_FAILED:"omniview:session/failed",CANCELLED:"omniview:cancelled",INTERNAL:"omniview:internal",VALIDATION:"omniview:validation",NOT_IMPLEMENTED:"omniview:not-implemented"},Re={INVALID_REQUEST:[F.VALIDATION,400,"correctRequest"],UNSUPPORTED:[F.NOT_IMPLEMENTED,501,"refreshContract"],FORBIDDEN:[F.RESOURCE_FORBIDDEN,403,"none"],UNAUTHORIZED:[F.RESOURCE_UNAUTHORIZED,401,"none"],NOT_FOUND:[F.RESOURCE_NOT_FOUND,404,"none"],CONFLICT:[F.RESOURCE_CONFLICT,409,"refreshContract"],ALREADY_EXISTS:[F.RESOURCE_CONFLICT,409,"refreshContract"],CANCELLED:[F.CANCELLED,499,"none"],TIMEOUT:[F.RESOURCE_TIMEOUT,408,"none"],UNAVAILABLE:[F.CONNECTION_FAILED,503,"reconnect"],CONNECTION_ERROR:[F.CONNECTION_FAILED,503,"reconnect"],CERTIFICATE_ERROR:[F.CONNECTION_FAILED,502,"reconnect"],RESOURCE_LIMIT:[F.RESOURCE_LIMIT,429,"correctRequest"],CONTINUATION_EXPIRED:[F.RESOURCE_CONTINUATION_EXPIRED,410,"restartQuery"],RESET_REQUIRED:[F.RESOURCE_RESET_REQUIRED,409,"restartQuery"],PARTIAL_RESULT:[F.RESOURCE_PARTIAL,422,"none"],PROVIDER_ERROR:[F.RESOURCE_PROVIDER_ERROR,502,"none"],INTERNAL:[F.INTERNAL,500,"none"]};function ae(t){return typeof t=="object"&&t!==null?t:void 0}function $(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function ce(){return{type:F.CANCELLED,code:"CANCELLED",title:"Cancelled",status:499,detail:"The operation was cancelled.",recovery:"none"}}function Z(t,e){if(e>4)return;if(t==="cancelled")return ce();if(typeof t=="string"){const r=t.trim();if(!r.startsWith("{"))return;try{return Z(JSON.parse(r),e+1)}catch{return}}const n=ae(t);if(n){if(n.name==="AbortError"||n.name==="CancelError")return ce();if($(n.type,256)&&$(n.title,256)&&typeof n.status=="number"&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599&&typeof n.detail=="string"&&n.detail.length<=4096){const r={type:n.type,title:n.title,status:n.status,detail:n.detail};$(n.code,64)&&(r.code=n.code),$(n.requestId,256)&&(r.requestId=n.requestId),$(n.instance,512)&&(r.instance=n.instance),Array.isArray(n.suggestions)&&(r.suggestions=n.suggestions.filter(i=>$(i,512)).slice(0,8)),Array.isArray(n.actions)&&(r.actions=n.actions.filter(i=>{const o=ae(i);return!!o&&["navigate","retry","open-url","copy"].includes(String(o.type))&&$(o.label,256)&&(o.target===void 0||$(o.target,4096))}).slice(0,8)),["correctRequest","refreshContract","restartQuery","reconnect","none"].includes(String(n.recovery))&&(r.recovery=n.recovery);const s=ae(n.location);return(s==null?void 0:s.unit)==="utf8-byte"&&typeof s.start=="number"&&typeof s.end=="number"&&Number.isSafeInteger(s.start)&&Number.isSafeInteger(s.end)&&s.start>=0&&s.end>=s.start&&(r.location={start:s.start,end:s.end,unit:"utf8-byte"}),r}if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){let r=n.code;if(r==="PERMISSION_DENIED"&&(r="FORBIDDEN"),["INVALID_INPUT","FILTER_UNKNOWN_FIELD","FILTER_INVALID_OPERATOR"].includes(r)&&(r="INVALID_REQUEST"),Object.prototype.hasOwnProperty.call(Re,r)||(r="INTERNAL"),r==="CANCELLED")return ce();const[s,i,o]=Re[r],a=r==="FORBIDDEN"||r==="UNAUTHORIZED"||r==="INTERNAL"||r==="PROVIDER_ERROR";return{type:s,status:i,code:r,recovery:o,title:a?r==="FORBIDDEN"?"Access denied":r==="UNAUTHORIZED"?"Authentication required":"Operation failed":$(n.title,256)?n.title:"Operation failed",detail:a?"The operation could not be completed.":$(n.message,4096)?n.message:"The operation could not be completed.",...!a&&Array.isArray(n.suggestions)?{suggestions:n.suggestions.filter(c=>$(c,512)).slice(0,8)}:{}}}return Z(n.message,e+1)??Z(n.cause,e+1)}}function Q(t){return Z(t,0)??{type:F.INTERNAL,title:t==null?"Unknown error":"Error",status:500,detail:t==null?"An unknown error occurred.":"The operation could not be completed."}}function z(t){return Q(t).type===F.CANCELLED}function Ae(t){switch(t.type){case"navigate":return{label:t.label,onClick:()=>{window.location.hash=t.target??""}};case"open-url":return{label:t.label,onClick:()=>{window.open(t.target,"_blank")}};case"copy":return{label:t.label,onClick:()=>{navigator.clipboard.writeText(t.target??"")}};case"retry":return{label:t.label,onClick:()=>{}};default:return{label:t.label,onClick:()=>{}}}}function Te(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
- `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(Ae)}}function j(t,e,n){if(z(e))return;const r=Q(e);t(Te(r,n))}function M(t,e){return n=>{if(z(n))return;const r=Q(n);t(Te(r,r.title!=="Error"?r.title:e))}}function ut(t){const{children:e,pluginId:n}=t,[r,s]=l.useState({}),[i,o]=l.useState(new N.PluginMeta),[a,c]=l.useState(!1),[d,u]=l.useState(null),f=l.useRef(0),p=l.useRef(0);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!d});const y=l.useCallback(()=>{if(n===void 0||n==="")return;const _=++f.current;console.debug(`[PluginContextProvider] fetching settings for "${n}"`),E.PluginValues(n).then(g=>{_===f.current&&(console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(g)),s(g))}).catch(g=>{if(_!==f.current)return;const h=Q(g);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,h.detail)})},[n]),m=l.useCallback(()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}const _=++p.current;console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),E.GetPluginMeta(n).then(g=>{_===p.current&&(console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:g==null?void 0:g.name,version:g==null?void 0:g.version}),o(g),c(!0))}).catch(g=>{if(_!==p.current)return;const h=Q(g);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,h.detail),u(h.detail),c(!1)})},[n]);return l.useEffect(()=>{if(a)return;const _=()=>{y(),m()},g=[D.On("plugin/init_complete",_),D.On("plugin/dev_install_complete",h=>{var b;((b=h.data)==null?void 0:b.id)===n&&_()}),D.On("plugin/inventory_changed",_)];return()=>{for(const h of g)h()}},[n,a,y,m]),l.useEffect(()=>(console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),c(!1),u(null),s({}),y(),m(),()=>{++f.current,++p.current}),[n,y,m]),d?x.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:x.jsxs("div",{style:{maxWidth:480,width:"100%",border:"1px solid #7F1D1D",borderRadius:8,backgroundColor:"#1C1917",padding:20,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[x.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[x.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[x.jsx("circle",{cx:"12",cy:"12",r:"10"}),x.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),x.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),x.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),x.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),x.jsx("button",{onClick:()=>m(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?x.jsx(te.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):x.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[x.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),x.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function ne(){const t=l.useContext(te);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function lt(){return ne().settings}const ge=l.createContext(void 0),dt=({children:t})=>{const[e,n]=l.useState({}),r=l.useRef(0),s=l.useCallback(()=>{const o=r.current+1;r.current=o,E.Values().then(a=>{o===r.current&&n(a)}).catch(a=>{o===r.current&&console.error("Error fetching settings:",a)})},[]);l.useEffect(()=>{const o=D.On("settings/changed",()=>s());return s(),()=>{r.current+=1,o()}},[s]);const i=l.useCallback(()=>{s()},[s]);return x.jsx(ge.Provider,{value:{settings:e,reload:i},children:t})},De={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Fe=l.createContext(De),xe=l.createContext(void 0),Ne=l.createContext(void 0),he=l.createContext(void 0),ft=3e4,pt=({children:t})=>{const[e,n]=l.useState([]),r=l.useCallback(a=>{n(c=>[a,...c])},[]),s=l.useCallback((a,c)=>{n(d=>d.map(u=>u.id===a?{...u,...c}:u))},[]),i=l.useCallback(a=>{n(c=>c.filter(d=>d.id!==a))},[]);l.useEffect(()=>{const a=[];for(const c of e)if(c.status!=="running"){const d=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,ft-d);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[e,i]);const o=l.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return x.jsx(he.Provider,{value:o,children:t})};var fe=function(t,e){return fe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},fe(t,e)};function yt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");fe(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ue="Invariant Violation",be=Object.setPrototypeOf,gt=be===void 0?function(t,e){return t.__proto__=e,t}:be,ht=function(t){yt(e,t);function e(n){n===void 0&&(n=ue);var r=t.call(this,typeof n=="number"?ue+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=ue,gt(r,e.prototype),r}return e}(Error);function pe(t,e){if(!t)throw new ht(e)}var Le=["debug","log","warn","error","silent"],mt=Le.indexOf("log");function Y(t){return function(){if(Le.indexOf(t)>=mt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=Y("debug"),t.log=Y("log"),t.warn=Y("warn"),t.error=Y("error")})(pe||(pe={}));const Me=l.createContext(void 0),ke=()=>l.useContext(Me);function Et(t){const e=ke(),n=l.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=l.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=l.useCallback(()=>{const o=e==null?void 0:e.getExtensionPoint(t);if(!o){if(n.current&&n.current.store===void 0)return n.current.sentinel;const d={};return n.current={store:void 0,version:-1,sentinel:d},d}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return l.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const St=({registry:t,children:e})=>{const n=l.useRef(t);return pe(n.current===t,"You can't change the extension registry after it has been rendered"),x.jsx(Me.Provider,{value:n.current,children:e})},le=t=>{if(!t||typeof t!="string")throw new TypeError(`extensionName is required to be a string and can't be: "${t}" (${typeof t})`);return t.trim()};class qe{constructor(e){L(this,"id");L(this,"mode");L(this,"_pluginId");L(this,"_version",0);L(this,"_contributions",new Map);L(this,"_lookupCache",new Map);L(this,"_matcher");L(this,"_select");L(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class Ct{constructor(e){L(this,"_stores",new Map);L(this,"_storeUnsubs",new Map);L(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=le(e.id);if(this._stores.has(n)){const s=this._stores.get(n);throw new Error(`Extension point "${n}" already exists (owned by "${s.pluginId??"unknown"}")`)}const r=new qe({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=le(e);return this._stores.get(n)}hasExtensionPoint(e){const n=le(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const Ue=l.createContext(void 0),_t={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},wt=({children:t})=>{const{toast:e}=at.useToast(),[n,r]=l.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const d=typeof o=="object";let u="",f="info",p,y=5e3,m;if(d){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}f=o.status,p=o.details,y=o.autoHideDuration??5e3,m=o.actions}else u=o,f=a,p=c;e(p??u,{severity:_t[f]??"info",title:p?u:void 0,duration:y,action:m==null?void 0:m[0]})};return x.jsx(Ue.Provider,{value:{showSnackbar:i},children:t})},U=()=>{const t=l.useContext(Ue);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function T(t){const e=l.useContext(te),n=(e==null?void 0:e.pluginId)??t;if(!n)throw new Error("pluginID must be provided either via PluginContext or as an explicit parameter");return n}const Rt=({pluginID:t,connectionID:e})=>{const n=T(t),r=S.useQueryClient(),{showSnackbar:s}=U(),i=[n,"connection","detail",e],{mutateAsync:o}=S.useMutation({mutationFn:async()=>E.StartConnection(n,e),onSuccess(f){r.setQueryData(i,f),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:M(s,"Failed to start connection")}),{mutateAsync:a}=S.useMutation({mutationFn:async()=>E.StopConnection(n,e),onSuccess(f){r.setQueryData(i,f)},onError:M(s,"Failed to stop connection")}),{mutateAsync:c}=S.useMutation({mutationFn:async f=>E.UpdateConnection(n,f),onSuccess(f,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,f),r.setQueriesData({queryKey:[n,"connection","list"]},y=>y==null?void 0:y.map(m=>m.id===e?f:m))},onError:M(s,"Failed to update connection")}),{mutateAsync:d}=S.useMutation({mutationFn:async()=>E.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.filter(p=>p.id!==e))},onError:M(s,"Failed to remove connection")});return{connection:S.useQuery({queryKey:i,queryFn:async()=>E.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:d}},$e=t=>[t,"connection","list"],bt=({plugin:t})=>{const e=T(t),n=S.useQueryClient(),{showSnackbar:r}=U(),s=$e(e),{mutateAsync:i}=S.useMutation({mutationFn:async d=>E.StartConnectionWatch(e,d.id),onError:M(r,"Failed to start connection watch")}),{mutateAsync:o}=S.useMutation({mutationFn:async d=>E.StopConnectionWatch(e,d.id),onError:M(r,"Failed to stop connection watch")}),a=l.useCallback(d=>{const u=d.data;console.log("got update to connections",u),n.setQueryData(s,u)},[n,s]);return l.useEffect(()=>{const d=D.On(`${e}/connection/sync`,a);return()=>{d()}},[e,a]),{connections:S.useQuery({queryKey:s,queryFn:async()=>{try{return await E.ListConnections(e)}catch(d){console.log(d),M(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:S.keepPreviousData}),startWatch:i,stopWatch:o}},vt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"connection","namespaces",e];return{namespaces:S.useQuery({queryKey:r,queryFn:async()=>E.GetConnectionNamespaces(n,e)})}},P=ct.withLegacyNames(N.WatchState,"WatchState");function ye(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const u of e)u===P.WatchStateSynced&&r++,(u===P.WatchStateError||u===P.WatchStateFailed)&&s++,u===P.WatchStateForbidden&&i++,u===P.WatchStateSkipped&&o++;const a=n-o,c=e.filter(u=>u===P.WatchStateSynced||u===P.WatchStateError||u===P.WatchStateStopped||u===P.WatchStateFailed||u===P.WatchStateForbidden).length,d=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:d}}function ee(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Qe(t){return t.some(e=>!ee(e))}function je(t){const e=t.reduce((r,s)=>r+s.watchedTotal,0);return e===0?0:t.reduce((r,s)=>r+s.doneCount,0)/e}function me(t){return`${t.pluginId}/${t.connection}`}function We(t,e){const n=me(e);t.has(n)||t.set(n,{states:{},pluginID:e.pluginId,connectionID:e.connection});const r=t.get(n);return r.states[e.resourceKey]=e.state,r}function It(){const[t,e]=l.useState(new Set),[n,r]=l.useState({}),[s,i]=l.useState(new Map),o=l.useRef(new Map),[a,c]=l.useState(new Map);l.useEffect(()=>{const C=D.On("plugin/crash_recovery_failed",O=>{const w=O.data,R=w==null?void 0:w.pluginID;R&&c(I=>{const A=new Map(I);return A.set(R,w.error??"Crash recovery failed"),A})}),v=D.On("plugin/recovered",O=>{const w=O.data,R=w==null?void 0:w.pluginID;R&&c(I=>{if(!I.has(R))return I;const A=new Map(I);return A.delete(R),A})});return()=>{C(),v()}},[]),l.useEffect(()=>{E.GetAllConnectionStates().then(C=>{if(!C)return;const v={},O=new Set,w=new Map;for(const[R,I]of Object.entries(C))if(I){v[R]=I.map(A=>A.connection);for(const A of I){if(!A.started)continue;const q=`${R}/${A.connection.id}`;O.add(q);const k={pluginID:R,connectionID:A.connection.id,states:{}};if(A.resources)for(const[ie,st]of Object.entries(A.resources))k.states[ie]=st;o.current.set(q,k),w.set(q,ye(k))}}r(v),e(O),i(w)}).catch(()=>{})},[]),l.useEffect(()=>D.On("connection/status",v=>{const O=v.data,w=`${O.pluginID}/${O.connectionID}`;O.status==="DISCONNECTED"?(e(R=>{const I=new Set(R);return I.delete(w),I}),i(R=>{const I=new Map(R);return I.delete(w),I}),o.current.delete(w)):e(R=>{const I=new Set(R);return I.add(w),I}),E.ListAllConnections().then(R=>{if(!R)return;const I={};for(const[A,q]of Object.entries(R))q!=null&&(I[A]=q);r(I)}).catch(()=>{})}),[]);const d=l.useCallback(C=>{const v=C.data,O=me(v);e(I=>{if(I.has(O))return I;const A=new Set(I);return A.add(O),A});const w=We(o.current,v),R=ye(w);i(I=>{const A=new Map(I);return A.set(O,R),A})},[]);l.useEffect(()=>D.On("watch/STATE",d),[d]);const u=l.useCallback(async(C,v)=>{await E.StopConnection(C,v)},[]),f=l.useCallback(async(C,v)=>{await E.StartConnectionWatch(C,v)},[]),p=l.useCallback(async C=>{const v=a.get(C);c(O=>{if(!O.has(C))return O;const w=new Map(O);return w.delete(C),w});try{await E.RetryFailedPlugin(C)}catch(O){throw c(w=>{const R=new Map(w);return R.set(C,v??"Reload failed"),R}),O}},[a]),y=[];for(const C of t){const[v,O]=C.split("/",2),R=(n[v]??[]).find(ie=>ie.id===O),I=s.get(C),A=I!=null&&!ee(I),q=I!=null&&I.errorCount>0,k=a.get(v);y.push({pluginID:v,connectionID:O,name:(R==null?void 0:R.name)??O,avatar:(R==null?void 0:R.avatar)??"",isStarted:!0,sync:I,isSyncing:A,hasErrors:q||k!=null,pluginFailed:k!=null,pluginError:k})}const m=new Map;for(const C of y){const v=m.get(C.pluginID)??[];v.push(C),m.set(C.pluginID,v)}const _=Array.from(s.values()),g=y.filter(C=>C.isSyncing),h=y.filter(C=>C.hasErrors),b=y.filter(C=>C.pluginFailed);return{entries:y,grouped:m,connectedCount:y.length,syncingCount:g.length,errorCount:h.length,failedCount:b.length,hasSyncing:Qe(_),aggregateProgress:je(_),disconnect:u,retryWatch:f,retryPlugin:p}}function Ot(t,e){return e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?typeof t=="object"&&t!==null&&!Array.isArray(t):typeof t==typeof e}function Pt(t,e,n){const r=T(t),s=S.useQueryClient(),i=[r,"data",e],o=S.useQuery({queryKey:i,queryFn:async()=>{const c=await E.Get(r,e);return c==null?n:Ot(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=S.useMutation({mutationFn:async c=>{await E.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const d=s.getQueryData(i);return s.setQueryData(i,c),{previous:d}},onError:(c,d,u)=>{(u==null?void 0:u.previous)!==void 0&&s.setQueryData(i,u.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const At=()=>{const t=l.useContext(xe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},Ee=()=>{const t=l.useContext(Fe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},Tt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r,updateTab:s}=Ee();return{createSession:S.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:d})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...d}}});const f=N.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const p=await E.CreateSession(e,o,f);if(!p)throw new Error("Failed to create session: null response");s({id:u},{id:p.id,title:c??`Session ${p.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...d}}})}catch(p){const y=Q(p);s({id:u},{properties:{status:"error",error:y.detail,pluginID:e,connectionID:o,opts:{...d}}}),j(n,p,"Failed to start session")}}}).mutateAsync}},Dt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r}=Ee(),s=S.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:d,icon:u,label:f,target:p,follow:y=!0,tailLines:m=1e3,params:_})=>{const g=N.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:d,options:N.LogSessionOptions.createFrom({target:p??"",follow:y,include_previous:!1,include_timestamps:!0,tail_lines:m,since_seconds:0,limit_bytes:0,include_source_events:!0,params:_??{}})}),h=await E.CreateSession$1(e,o,g);if(!h)throw new Error("Failed to create log session: null response");return r({id:h.id,title:f??`Logs ${h.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),h},onError:M(n,"Failed to start log session")}),i=S.useMutation({mutationFn:async o=>{await E.CloseSession(o)},onError:M(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Ft=()=>S.useQuery({queryKey:["metric","providers"],queryFn:E.GetProviders,staleTime:3e4}),Ge=t=>S.useQuery({queryKey:["metric","providers",t],queryFn:()=>E.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),xt=t=>{var g,h;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:d=0,enabled:u=!0}=t,{data:f,isLoading:p}=Ge(n),y=f??[],m=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,_=S.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(g=c==null?void 0:c.start)==null?void 0:g.getTime(),(h=c==null?void 0:c.end)==null?void 0:h.getTime()],queryFn:async()=>{const b=await E.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),m),C={};for(const[v,O]of Object.entries(b))O!=null&&(C[v]=O);return C},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&y.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:S.keepPreviousData});return{data:_.data??void 0,providers:y,isLoading:p||_.isLoading,error:_.error,refetch:_.refetch}},Nt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:d=!0}=t,u=T(e),[f,p]=l.useState(null),[y,m]=l.useState(null),[_,g]=l.useState(!1),[h,b]=l.useState(null),C=l.useRef(null),v=l.useCallback(async()=>{if(!(!d||!u||!n||!r||!s))try{const w=await E.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});m(w),g(!0),b(null);const R=D.On(`core/metrics/data/${w}`,A=>{const q=A.data;try{const k=JSON.parse(q);k.results&&p(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),I=D.On(`core/metrics/error/${w}`,A=>{const q=A.data;try{const k=JSON.parse(q);b(k.error||"Unknown error")}catch{b("Failed to parse metric stream error")}});C.current=()=>{R(),I()}}catch(w){b(w instanceof Error?w.message:String(w))}},[u,n,r,s,i,a,c,d]),O=l.useCallback(async()=>{if(y)try{await E.Unsubscribe(y)}catch(w){console.error("Failed to unsubscribe:",w)}C.current&&(C.current(),C.current=null),m(null),g(!1)},[y]);return l.useEffect(()=>()=>{y&&E.Unsubscribe(y).catch(console.error),C.current&&C.current()},[y]),{data:f,subscriptionID:y,isStreaming:_,error:h,start:v,stop:O}},W=["networker","portforward","all-sessions"];function Lt(){const{showSnackbar:t}=U(),e=S.useQueryClient(),n=S.useQuery({queryKey:[...W],queryFn:async()=>E.ListAllPortForwardSessions().catch(i=>{if(Q(i).detail.includes("not found"))return[];throw i}),retry:!1});l.useEffect(()=>{const i=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...W]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...W]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=S.useMutation({mutationFn:async i=>E.ClosePortForwardSession(i),onError:M(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...W]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>D.OpenURL(`http://localhost:${i}`)}}function Mt({pluginID:t,connectionID:e,resourceID:n}){const r=T(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=U(),o=S.useQueryClient(),a=S.useQuery({queryKey:s,queryFn:async()=>E.FindPortForwardSessions(r,e,N.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const f=Q(u);return f.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:f.detail}),[])}),retry:!1}),c=S.useMutation({mutationFn:async({opts:u})=>{const f=N.PortForwardSessionOptions.createFrom({local_port:u.localPort||0,remote_port:u.remotePort,protocol:u.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:u.resource,connection_id:e,plugin_id:r,resource_id:u.resourceId,resource_key:u.resourceKey},labels:u.labels??{},params:u.parameters??{}}),p=await E.StartResourcePortForwardingSession(r,e,f);if(!p)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&D.OpenURL(`http://localhost:${p.local_port}`),p},onError:M(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...W]})])}}),d=S.useMutation({mutationFn:async({opts:u})=>E.ClosePortForwardSession(u.sessionID),onError:M(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...W]})])}});return{sessions:a,forward:c.mutateAsync,close:d.mutateAsync}}const kt=()=>{const t=l.useContext(Ne);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},qt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=U(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:d}=S.useMutation({mutationFn:async p=>E.Update(i,e,n,N.UpdateInput.createFrom({input:p.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to update resource ${r}`)}),{mutateAsync:u}=S.useMutation({mutationFn:async(p={})=>E.Delete(i,e,n,N.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:p.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to delete resource ${r}`)});return{resource:S.useQuery({queryKey:c,queryFn:async()=>E.Get$1(i,e,n,N.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:u}},Ut=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:S.useQuery({queryKey:e,queryFn:async()=>E.GetResourceAreaComponent(t)})}},$t=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resource_groups","list"];return{groups:S.useQuery({queryKey:r,queryFn:async()=>E.GetResourceGroups(n,e),retry:!1})}},Qt=({pluginID:t,connectionID:e,searches:n})=>{const r=T(t),s=o=>[r,e,o.key,o.namespaces,"list"];return S.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>E.List(r,e,o.key,N.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},jt=({pluginID:t,resourceKey:e})=>{const n=T(t),r=[n,"resources",e];return{resourceType:S.useQuery({queryKey:r,queryFn:async()=>E.GetResourceType(n,e),retry:!1})}},Wt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resources","list",e];return{types:S.useQuery({queryKey:r,queryFn:async()=>E.GetResourceTypes(n,e),retry:!1})}};var J=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Kt="Expected a function",Ke="__lodash_hash_undefined__",Bt="[object Function]",Ht="[object GeneratorFunction]",zt="[object Symbol]",Vt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yt=/^\w*$/,Jt=/^\./,Xt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Zt=/[\\^$.*+?()[\]{}|]/g,en=/\\(\\)?/g,tn=/^\[object .+?Constructor\]$/,nn=typeof J=="object"&&J&&J.Object===Object&&J,rn=typeof self=="object"&&self&&self.Object===Object&&self,Se=nn||rn||Function("return this")();function sn(t,e){return t==null?void 0:t[e]}function on(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var an=Array.prototype,cn=Function.prototype,Be=Object.prototype,de=Se["__core-js_shared__"],ve=function(){var t=/[^.]+$/.exec(de&&de.keys&&de.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),He=cn.toString,Ce=Be.hasOwnProperty,ze=Be.toString,un=RegExp("^"+He.call(Ce).replace(Zt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ie=Se.Symbol,ln=an.splice,dn=Ve(Se,"Map"),V=Ve(Object,"create"),Oe=Ie?Ie.prototype:void 0,Pe=Oe?Oe.toString:void 0;function G(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function fn(){this.__data__=V?V(null):{}}function pn(t){return this.has(t)&&delete this.__data__[t]}function yn(t){var e=this.__data__;if(V){var n=e[t];return n===Ke?void 0:n}return Ce.call(e,t)?e[t]:void 0}function gn(t){var e=this.__data__;return V?e[t]!==void 0:Ce.call(e,t)}function hn(t,e){var n=this.__data__;return n[t]=V&&e===void 0?Ke:e,this}G.prototype.clear=fn;G.prototype.delete=pn;G.prototype.get=yn;G.prototype.has=gn;G.prototype.set=hn;function B(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function mn(){this.__data__=[]}function En(t){var e=this.__data__,n=re(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():ln.call(e,n,1),!0}function Sn(t){var e=this.__data__,n=re(e,t);return n<0?void 0:e[n][1]}function Cn(t){return re(this.__data__,t)>-1}function _n(t,e){var n=this.__data__,r=re(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}B.prototype.clear=mn;B.prototype.delete=En;B.prototype.get=Sn;B.prototype.has=Cn;B.prototype.set=_n;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function wn(){this.__data__={hash:new G,map:new(dn||B),string:new G}}function Rn(t){return se(this,t).delete(t)}function bn(t){return se(this,t).get(t)}function vn(t){return se(this,t).has(t)}function In(t,e){return se(this,t).set(t,e),this}K.prototype.clear=wn;K.prototype.delete=Rn;K.prototype.get=bn;K.prototype.has=vn;K.prototype.set=In;function re(t,e){for(var n=t.length;n--;)if(kn(t[n][0],e))return n;return-1}function On(t,e){e=Dn(e,t)?[e]:Tn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Ln(e[n++])];return n&&n==r?t:void 0}function Pn(t){if(!Je(t)||xn(t))return!1;var e=qn(t)||on(t)?un:tn;return e.test(Mn(t))}function An(t){if(typeof t=="string")return t;if(we(t))return Pe?Pe.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Tn(t){return Ye(t)?t:Nn(t)}function se(t,e){var n=t.__data__;return Fn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ve(t,e){var n=sn(t,e);return Pn(n)?n:void 0}function Dn(t,e){if(Ye(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||we(t)?!0:Yt.test(t)||!Vt.test(t)||e!=null&&t in Object(e)}function Fn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function xn(t){return!!ve&&ve in t}var Nn=_e(function(t){t=$n(t);var e=[];return Jt.test(t)&&e.push(""),t.replace(Xt,function(n,r,s,i){e.push(s?i.replace(en,"$1"):r||n)}),e});function Ln(t){if(typeof t=="string"||we(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Mn(t){if(t!=null){try{return He.call(t)}catch{}try{return t+""}catch{}}return""}function _e(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Kt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(_e.Cache||K),n}_e.Cache=K;function kn(t,e){return t===e||t!==t&&e!==e}var Ye=Array.isArray;function qn(t){var e=Je(t)?ze.call(t):"";return e==Bt||e==Ht}function Je(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Un(t){return!!t&&typeof t=="object"}function we(t){return typeof t=="symbol"||Un(t)&&ze.call(t)==zt}function $n(t){return t==null?"":An(t)}function Qn(t,e,n){var r=t==null?void 0:On(t,e);return r===void 0?n:r}var jn=Qn;const X=Gt(jn);function Xe(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=X(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>X(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>X(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>X(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function Ze(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=l.useRef([]),c=l.useRef(null),d=l.useRef(null),u=l.useRef(s);u.current=s;const f=l.useCallback(()=>{const y=a.current;if(a.current=[],c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),!(y.length===0||!r)){t.setQueryData(e,m=>Xe(m,y,r));for(const m of y)(m.type==="ADD"||m.type==="UPDATE")&&t.setQueryData(n(m.payload.id,m.payload.namespace),{result:m.payload.data})}},[t,e,n,r]),p=l.useCallback(y=>{a.current.push(y),!(c.current!==null||d.current!==null)&&(c.current=setTimeout(f,o),u.current!==1&&(d.current=requestAnimationFrame(f)))},[f,o]);return l.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),p}const Wn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=U(),c=l.useMemo(()=>s??[],[s]),d=l.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=l.useCallback((g,h)=>[i,e,n,h,g],[i,e,n]),{mutateAsync:f}=S.useMutation({mutationFn:async g=>E.Create(i,e,n,N.CreateInput.createFrom({input:g.input,namespace:g.namespace??(c.length===1?c[0]:"")})),onSuccess:async g=>{var v;const h=g==null?void 0:g.result;let b="";(v=h==null?void 0:h.metadata)!=null&&v.name?b=h.metadata.name:h!=null&&h.id?b=h.id:h!=null&&h.name?b=h.name:h!=null&&h.ID?b=h.ID:h!=null&&h.Name&&(b=h.Name);const C=b?`Resource ${b} created`:"Resource created";a(C,"success"),await o.invalidateQueries({queryKey:d})},onError:M(a,"Failed to create resource")}),p=S.useQuery({queryKey:d,queryFn:async()=>E.List(i,e,n,N.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(g,h)=>g,retry:!1}),[y,m]=l.useState(P.WatchStateIdle);l.useEffect(()=>D.On(`${i}/${e}/watch/STATE`,h=>{const b=h.data;b.resourceKey===n&&m(b.state)}),[i,e,n]);const _=Ze(o,d,u,r,y);return l.useEffect(()=>{if(!r)return;E.SubscribeResource(i,e,n);const g=D.On(`${i}/${e}/${n}/ADD`,C=>_({type:"ADD",payload:C.data})),h=D.On(`${i}/${e}/${n}/UPDATE`,C=>_({type:"UPDATE",payload:C.data})),b=D.On(`${i}/${e}/${n}/DELETE`,C=>_({type:"DELETE",payload:C.data}));return()=>{g(),h(),b(),E.UnsubscribeResource(i,e,n)}},[i,e,n,_]),{resources:p,create:f,watchState:y,isSyncing:y===P.WatchStateSyncing,isSynced:y===P.WatchStateSynced,watchError:y===P.WatchStateError}},Gn=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),r=S.useMutation({mutationFn:async({opts:o,input:a})=>E.Create(e,o.connectionID,o.resourceKey,N.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){j(n,o,`Failed to create resource ${a.resourceID}`)}}),s=S.useMutation({mutationFn:async({opts:o,input:a})=>E.Update(e,o.connectionID,o.resourceKey,N.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){j(n,o,`Failed to update resource ${a.resourceID}`)}}),i=S.useMutation({mutationFn:async({opts:o,input:a})=>E.Delete(e,o.connectionID,o.resourceKey,N.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){j(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Kn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=T(t),i=S.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>E.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},Bn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),s=S.useQueryClient(),{showSnackbar:i}=U(),o=S.useMutation({mutationFn:async({actionID:a,id:c="",namespace:d="",params:u={}})=>E.ExecuteAction(r,e,n,a,N.ActionInput.createFrom({id:c,namespace:d,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{j(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Hn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=S.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>E.GetEditorSchemas(r,e),enabled:n&&!!r&&!!e,staleTime:10*60*1e3,retry:1});return{schemas:s.data??[],isLoading:s.isLoading,error:s.error,refetch:s.refetch}},zn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=S.useQueryClient(),i=[r,e,"watch-state"],o=l.useRef([]),a=l.useRef(!1),c=l.useCallback(p=>{s.setQueryData(i,y=>{if(!y)return y;const m={...y.resources,[p.resourceKey]:p.state},_={...y.resourceCounts,[p.resourceKey]:p.resourceCount};let g=0,h=0;for(const b of Object.values(m))b===P.WatchStateSynced&&g++,(b===P.WatchStateError||b===P.WatchStateFailed)&&h++;return{...y,resources:m,resourceCounts:_,totalResources:Object.keys(m).length,syncedCount:g,errorCount:h}})},[s,r,e]),d=S.useQuery({queryKey:i,queryFn:async()=>{const p=await E.GetWatchState(r,e);if(!p)throw new Error("Failed to get watch state: null response");const y={};let m=0,_=0;for(const[h,b]of Object.entries(p.resources??{}))b!=null&&(y[h]=b,b===P.WatchStateSynced&&m++,b===P.WatchStateError&&_++);const g={};for(const[h,b]of Object.entries(p.resourceCounts??{}))b!=null&&(g[h]=b);return{connection:p.connectionId,resources:y,resourceCounts:g,totalResources:Object.keys(y).length,syncedCount:m,errorCount:_}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const y=p.state.data;if(!y||y.totalResources===0)return 3e3;let m=0;for(const _ of Object.values(y.resources))(_===P.WatchStateSynced||_===P.WatchStateError||_===P.WatchStateStopped||_===P.WatchStateFailed||_===P.WatchStateForbidden||_===P.WatchStateSkipped)&&m++;return m>=y.totalResources?!1:3e3}});l.useEffect(()=>{if(!d.data||a.current)return;a.current=!0;const p=o.current;o.current=[];for(const y of p)c(y)},[d.data,c]),l.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const p=D.On(`${r}/${e}/watch/STATE`,y=>{const m=y.data;a.current?c(m):o.current.push(m)});return()=>{p(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=d.data;let f=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===P.WatchStateSynced||p===P.WatchStateError||p===P.WatchStateStopped||p===P.WatchStateFailed||p===P.WatchStateForbidden||p===P.WatchStateSkipped)&&f++;return{summary:d,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&f===u.totalResources:!1,syncProgress:u&&u.totalResources>0?f/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Vn=()=>{const[t,e]=l.useState(new Map),n=l.useRef(new Map),r=l.useRef(new Map),s=l.useCallback(d=>{const u=d.data,f=me(u),p=We(n.current,u),y=ye(p);if(e(m=>{const _=new Map(m);return _.set(f,y),_}),r.current.has(f)&&(clearTimeout(r.current.get(f)),r.current.delete(f)),ee(y)){const m=setTimeout(()=>{e(_=>{const g=new Map(_);return g.delete(f),g}),n.current.delete(f),r.current.delete(f)},5e3);r.current.set(f,m)}},[]);l.useEffect(()=>{const d=D.On("watch/STATE",s);return()=>{d();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(t.values()),o=Qe(i),a=i.find(d=>!ee(d))??i[0]??null,c=je(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},et=()=>{const t=l.useContext(he);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Yn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),{showSnackbar:s}=U(),{addOperation:i,updateOperation:o}=et(),a=l.useRef(new Set),c=l.useCallback((f,p=!1)=>{var y,m,_;f.disposed||(f.disposed=!0,(y=f.unsubscribe)==null||y.call(f),(m=f.open)==null||m.cancel(),(_=f.attach)==null||_.cancel(),f.handle&&(E.CancelStreamAction(f.handle).catch(()=>{}),p&&o(f.handle,{status:"cancelled",message:"Cancelled",completedAt:Date.now()})),a.current.delete(f))},[o]);l.useEffect(()=>()=>{for(const f of a.current)c(f,!0)},[r,e,n,c]);const d=l.useCallback(async({actionID:f,id:p,namespace:y,label:m,params:_={}})=>{const g={disposed:!1,terminal:!1,sequence:0};a.current.add(g);try{g.open=E.StreamAction(r,e,n,f,N.ActionInput.createFrom({id:p,namespace:y,params:_}));const h=await g.open;if(g.open=void 0,g.disposed)return E.CancelStreamAction(h).catch(()=>{}),h;g.handle=h,i({id:h,label:m,resourceKey:n,resourceName:p,namespace:y,connectionID:e,status:"running",startedAt:Date.now()});const b=v=>{if(g.disposed||!Number.isSafeInteger(v.sequence)||v.sequence<=g.sequence)return;g.sequence=v.sequence;const O=v.event,w=O.data??{};if(O.type==="error"){g.terminal=!0;const R=Q(O.error);o(h,{status:z(R)?"cancelled":"error",message:R.title,completedAt:Date.now()}),j(s,R,m),c(g)}else if(O.type==="complete"){g.terminal=!0;const R=typeof w.message=="string"?w.message:`${m} completed`;o(h,{status:"completed",message:R,completedAt:Date.now()}),s(R,"success"),c(g)}else o(h,{message:typeof w.message=="string"?w.message:void 0,progress:typeof w.ready=="number"&&typeof w.desired=="number"?{ready:w.ready,desired:w.desired}:void 0})};g.unsubscribe=D.On(`action/stream/${h}`,v=>b(v.data)),g.attach=E.AttachStreamAction(h);const C=await g.attach;return g.attach=void 0,b(C),h}catch(h){if(g.terminal&&g.handle)return g.handle;throw g.disposed||(g.handle&&o(g.handle,{status:z(h)?"cancelled":"error",message:Q(h).title,completedAt:Date.now()}),j(s,h,`Failed to start "${f}"`)),c(g),h}},[r,e,n,i,o,s,c]),u=l.useCallback(f=>{for(const p of a.current)if(p.handle===f){c(p,!0);return}},[c]);return{startStreamAction:d,cancelStreamAction:u}};function tt(t,e){return`${t}/${e}/graph/CHANGED`}function oe(t,e,n,r){const s=S.useQueryClient(),i=l.useRef(n);i.current=n;const o=JSON.stringify(n);l.useEffect(()=>{if(!r||!t||!e)return;const a=D.On(tt(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const Jn={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function Xn(t,e){const n=Jn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function Zn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function nt(t,e){return e.map(n=>{const r=Zn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const er=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const d=T(t),u=["RESOURCE_RELATED",d,e,n,s,r,i,o??null],f=a&&!!d&&!!e&&!!n&&!!r;oe(d,e,u,f);const p=S.useQuery({queryKey:u,queryFn:async()=>E.GetRelated(d,e,n,s,r,i,o??null),enabled:f,refetchInterval:c}),y={pluginId:d,connectionId:e,resourceKey:n,id:r,namespace:s},m=p.data??[];return{related:nt(y,m),edges:m,isLoading:p.isLoading,isFetching:p.isFetching,error:p.error,refetch:p.refetch}},tr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=T(t),d=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],u=o&&!!c&&!!e&&!!n&&!!r;oe(c,e,d,u);const f=S.useQuery({queryKey:d,queryFn:async()=>E.GetDependencyTree(c,e,n,s,r,i),enabled:u,refetchInterval:a});return{tree:f.data??null,isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}},nr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=T(t),d=["RESOURCE_GRAPH",c,e,n,s,r,i,o],u=a&&!!c&&!!e&&!!n&&!!r;oe(c,e,d,u);const f=S.useQuery({queryKey:d,queryFn:async()=>E.GetSubgraph(c,e,n,s,r,i,o),enabled:u});return{graph:f.data??null,isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}},rr=()=>{const t=l.useContext(ge);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},sr=({to:t,withinContext:e,...n})=>{const{pluginId:r}=ne();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return l.useMemo(()=>x.jsx(H.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function or(){const t=H.useNavigate(),e=H.useLocation(),{pluginId:n}=ne();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=l.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return l.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class ir{}class ar{constructor(){L(this,"_extensions");L(this,"root");L(this,"pages");L(this,"_routes")}get extensions(){return this._extensions||[]}get Routes(){var e;if(!this._routes&&this.root)return[{path:"",index:!0,Component:this.root}];if(!((e=this._routes)!=null&&e.length))throw new Error("cannot use plugin without a root page or router");return this._routes}get Window(){if(!this._routes&&this.root)return x.jsx(this.root,{});const e=H.createMemoryRouter(this._routes||[]);return x.jsx(H.RouterProvider,{router:e})}registerExtensionPoints(e){return this._extensions=e||[],this}setRootPage(e){return this.root=e,this}withPage(e,n){return this.pages||(this.pages={}),this.pages[e]?(console.warn("Cannot register page with the same name. Please use a different name."),this):(this.pages[e]=n,this)}withRoutes(e){return this._routes=e,this}}var rt=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(rt||{});const cr=t=>{const e=t.split("::");return e.length===1?{group:"core",version:"",kind:e[0]}:{group:e[0]||"core",version:e[1]||"",kind:e[2]||e[0]}},ur=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=W;exports.BottomDrawerContext=Fe;exports.ConfirmationModalContext=Ne;exports.ErrorTypes=F;exports.ExtensionPointRegistry=Ct;exports.ExtensionPointStore=qe;exports.ExtensionProvider=St;exports.Link=sr;exports.OperationsContext=he;exports.OperationsProvider=pt;exports.PluginContext=te;exports.PluginContextProvider=ut;exports.PluginErrorCode=rt;exports.PluginWindow=ar;exports.PluginWindowRootProps=ir;exports.RightDrawerContext=xe;exports.SettingsContext=ge;exports.SettingsProvider=dt;exports.SnackbarProvider=wt;exports.WatchState=P;exports.actionToSnackbar=Ae;exports.applyBatch=Xe;exports.connectionListQueryKey=$e;exports.createErrorHandler=M;exports.defaultState=De;exports.formatGroup=ur;exports.graphChangedEvent=tt;exports.isCancelledError=z;exports.parseAppError=Q;exports.parseResourceKey=cr;exports.relationshipLabel=Xn;exports.showAppError=j;exports.toRelatedResources=nt;exports.useActiveSyncs=Vn;exports.useBottomDrawer=Ee;exports.useConfirmationModal=kt;exports.useConnection=Rt;exports.useConnectionNamespaces=vt;exports.useConnectionStatus=It;exports.useConnections=bt;exports.useDependencyTree=tr;exports.useEditorSchemas=Hn;exports.useEventBatcher=Ze;exports.useExec=Tt;exports.useExecuteAction=Bn;exports.useExtensionPoint=Et;exports.useExtensionRegistry=ke;exports.useLogs=Dt;exports.useMetricProviders=Ft;exports.useMetricProvidersForResource=Ge;exports.useMetricStream=Nt;exports.useOperations=et;exports.usePluginContext=ne;exports.usePluginData=Pt;exports.usePluginRouter=or;exports.usePluginSettings=lt;exports.usePortForwardSessions=Lt;exports.useRefetchOnGraphChange=oe;exports.useRelatedResources=er;exports.useResolvedPluginId=T;exports.useResource=qt;exports.useResourceActions=Kn;exports.useResourceAreaComponent=Ut;exports.useResourceGraph=nr;exports.useResourceGroups=$t;exports.useResourceMetrics=xt;exports.useResourceMutations=Gn;exports.useResourcePortForwarder=Mt;exports.useResourceSearch=Qt;exports.useResourceType=jt;exports.useResourceTypes=Wt;exports.useResources=Wn;exports.useRightDrawer=At;exports.useSettings=rr;exports.useSnackbar=U;exports.useStreamAction=Yn;exports.useWatchState=zn;
1
+ "use strict";var it=Object.defineProperty;var at=(t,e,n)=>e in t?it(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var L=(t,e,n)=>at(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("react/jsx-runtime"),u=require("react"),z=require("react-router-dom");require("./index-D_aIcqH0.cjs");const S=require("./graphservice-1J8q3eeL.cjs"),N=require("./models-BQsuB2Lj.cjs"),D=require("./events-CtgYnKmS.cjs"),_=require("@tanstack/react-query"),H=require("@omniviewdev/base-ui"),ct=require("./legacyEnum-DkV5yRdA.cjs"),ne=u.createContext(void 0),F={PLUGIN_NOT_FOUND:"omniview:plugin/not-found",PLUGIN_NOT_LOADED:"omniview:plugin/not-loaded",PLUGIN_ALREADY_LOADED:"omniview:plugin/already-loaded",PLUGIN_INSTALL_FAILED:"omniview:plugin/install-failed",PLUGIN_LOAD_FAILED:"omniview:plugin/load-failed",PLUGIN_BUILD_FAILED:"omniview:plugin/build-failed",PLUGIN_COMMITTED_CLEANUP_PENDING:"omniview:plugin/committed-cleanup-pending",PLUGIN_COMMIT_UNCERTAIN:"omniview:plugin/commit-uncertain",SETTINGS_MISSING_CONFIG:"omniview:settings/missing-config",SETTINGS_INVALID_CONFIG:"omniview:settings/invalid-config",RESOURCE_NOT_FOUND:"omniview:resource/not-found",RESOURCE_FORBIDDEN:"omniview:resource/forbidden",RESOURCE_UNAUTHORIZED:"omniview:resource/unauthorized",RESOURCE_CONFLICT:"omniview:resource/conflict",RESOURCE_TIMEOUT:"omniview:resource/timeout",RESOURCE_LIMIT:"omniview:resource/limit",RESOURCE_CONTINUATION_EXPIRED:"omniview:resource/continuation-expired",RESOURCE_RESET_REQUIRED:"omniview:resource/reset-required",RESOURCE_PARTIAL:"omniview:resource/partial",RESOURCE_PROVIDER_ERROR:"omniview:resource/provider-error",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",SESSION_NOT_FOUND:"omniview:session/not-found",SESSION_FAILED:"omniview:session/failed",CANCELLED:"omniview:cancelled",INTERNAL:"omniview:internal",VALIDATION:"omniview:validation",NOT_IMPLEMENTED:"omniview:not-implemented"},Re={INVALID_REQUEST:[F.VALIDATION,400,"correctRequest"],UNSUPPORTED:[F.NOT_IMPLEMENTED,501,"refreshContract"],FORBIDDEN:[F.RESOURCE_FORBIDDEN,403,"none"],UNAUTHORIZED:[F.RESOURCE_UNAUTHORIZED,401,"none"],NOT_FOUND:[F.RESOURCE_NOT_FOUND,404,"none"],CONFLICT:[F.RESOURCE_CONFLICT,409,"refreshContract"],ALREADY_EXISTS:[F.RESOURCE_CONFLICT,409,"refreshContract"],CANCELLED:[F.CANCELLED,499,"none"],TIMEOUT:[F.RESOURCE_TIMEOUT,408,"none"],UNAVAILABLE:[F.CONNECTION_FAILED,503,"reconnect"],CONNECTION_ERROR:[F.CONNECTION_FAILED,503,"reconnect"],CERTIFICATE_ERROR:[F.CONNECTION_FAILED,502,"reconnect"],RESOURCE_LIMIT:[F.RESOURCE_LIMIT,429,"correctRequest"],CONTINUATION_EXPIRED:[F.RESOURCE_CONTINUATION_EXPIRED,410,"restartQuery"],RESET_REQUIRED:[F.RESOURCE_RESET_REQUIRED,409,"restartQuery"],PARTIAL_RESULT:[F.RESOURCE_PARTIAL,422,"none"],PROVIDER_ERROR:[F.RESOURCE_PROVIDER_ERROR,502,"none"],INTERNAL:[F.INTERNAL,500,"none"]};function ce(t){return typeof t=="object"&&t!==null?t:void 0}function $(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function ue(){return{type:F.CANCELLED,code:"CANCELLED",title:"Cancelled",status:499,detail:"The operation was cancelled.",recovery:"none"}}function ee(t,e){if(e>4)return;if(t==="cancelled")return ue();if(typeof t=="string"){const r=t.trim();if(!r.startsWith("{"))return;try{return ee(JSON.parse(r),e+1)}catch{return}}const n=ce(t);if(n){if(n.name==="AbortError"||n.name==="CancelError")return ue();if($(n.type,256)&&$(n.title,256)&&typeof n.status=="number"&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599&&typeof n.detail=="string"&&n.detail.length<=4096){const r={type:n.type,title:n.title,status:n.status,detail:n.detail};$(n.code,64)&&(r.code=n.code),$(n.requestId,256)&&(r.requestId=n.requestId),$(n.instance,512)&&(r.instance=n.instance),Array.isArray(n.suggestions)&&(r.suggestions=n.suggestions.filter(i=>$(i,512)).slice(0,8)),Array.isArray(n.actions)&&(r.actions=n.actions.filter(i=>{const o=ce(i);return!!o&&["navigate","retry","open-url","copy"].includes(String(o.type))&&$(o.label,256)&&(o.target===void 0||$(o.target,4096))}).slice(0,8)),["correctRequest","refreshContract","restartQuery","reconnect","none"].includes(String(n.recovery))&&(r.recovery=n.recovery);const s=ce(n.location);return(s==null?void 0:s.unit)==="utf8-byte"&&typeof s.start=="number"&&typeof s.end=="number"&&Number.isSafeInteger(s.start)&&Number.isSafeInteger(s.end)&&s.start>=0&&s.end>=s.start&&(r.location={start:s.start,end:s.end,unit:"utf8-byte"}),r}if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){let r=n.code;if(r==="PERMISSION_DENIED"&&(r="FORBIDDEN"),["INVALID_INPUT","FILTER_UNKNOWN_FIELD","FILTER_INVALID_OPERATOR"].includes(r)&&(r="INVALID_REQUEST"),Object.prototype.hasOwnProperty.call(Re,r)||(r="INTERNAL"),r==="CANCELLED")return ue();const[s,i,o]=Re[r],a=r==="FORBIDDEN"||r==="UNAUTHORIZED"||r==="INTERNAL"||r==="PROVIDER_ERROR";return{type:s,status:i,code:r,recovery:o,title:a?r==="FORBIDDEN"?"Access denied":r==="UNAUTHORIZED"?"Authentication required":"Operation failed":$(n.title,256)?n.title:"Operation failed",detail:a?"The operation could not be completed.":$(n.message,4096)?n.message:"The operation could not be completed.",...!a&&Array.isArray(n.suggestions)?{suggestions:n.suggestions.filter(c=>$(c,512)).slice(0,8)}:{}}}return ee(n.message,e+1)??ee(n.cause,e+1)}}function j(t){return ee(t,0)??{type:F.INTERNAL,title:t==null?"Unknown error":"Error",status:500,detail:t==null?"An unknown error occurred.":"The operation could not be completed."}}function V(t){return j(t).type===F.CANCELLED}function Ae(t){switch(t.type){case"navigate":return{label:t.label,onClick:()=>{window.location.hash=t.target??""}};case"open-url":return{label:t.label,onClick:()=>{window.open(t.target,"_blank")}};case"copy":return{label:t.label,onClick:()=>{navigator.clipboard.writeText(t.target??"")}};case"retry":return{label:t.label,onClick:()=>{}};default:return{label:t.label,onClick:()=>{}}}}function Te(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
+ `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(Ae)}}function Q(t,e,n){if(V(e))return;const r=j(e);t(Te(r,n))}function M(t,e){return n=>{if(V(n))return;const r=j(n);t(Te(r,r.title!=="Error"?r.title:e))}}function ut(t){const{children:e,pluginId:n}=t,[r,s]=u.useState({}),[i,o]=u.useState(new N.PluginMeta),[a,c]=u.useState(!1),[d,l]=u.useState(null),f=u.useRef(0),y=u.useRef(0);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!d});const h=u.useCallback(()=>{if(n===void 0||n==="")return;const m=++f.current;console.debug(`[PluginContextProvider] fetching settings for "${n}"`),S.PluginValues(n).then(p=>{m===f.current&&(console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(p)),s(p))}).catch(p=>{if(m!==f.current)return;const g=j(p);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,g.detail)})},[n]),C=u.useCallback(()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}const m=++y.current;console.debug(`[PluginContextProvider] fetching meta for "${n}"`),l(null),S.GetPluginMeta(n).then(p=>{m===y.current&&(console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:p==null?void 0:p.name,version:p==null?void 0:p.version}),o(p),c(!0))}).catch(p=>{if(m!==y.current)return;const g=j(p);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,g.detail),l(g.detail),c(!1)})},[n]);return u.useEffect(()=>{if(a)return;const m=()=>{h(),C()},p=[D.On("plugin/init_complete",m),D.On("plugin/dev_install_complete",g=>{var R;((R=g.data)==null?void 0:R.id)===n&&m()}),D.On("plugin/inventory_changed",m)];return()=>{for(const g of p)g()}},[n,a,h,C]),u.useEffect(()=>(console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),c(!1),l(null),s({}),h(),C(),()=>{++f.current,++y.current}),[n,h,C]),d?x.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:x.jsxs("div",{style:{maxWidth:480,width:"100%",border:"1px solid #7F1D1D",borderRadius:8,backgroundColor:"#1C1917",padding:20,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[x.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[x.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[x.jsx("circle",{cx:"12",cy:"12",r:"10"}),x.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),x.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),x.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),x.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),x.jsx("button",{onClick:()=>C(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?x.jsx(ne.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):x.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[x.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),x.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function re(){const t=u.useContext(ne);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function lt(){return re().settings}const he=u.createContext(void 0),dt=({children:t})=>{const[e,n]=u.useState({}),r=u.useRef(0),s=u.useCallback(()=>{const o=r.current+1;r.current=o,S.Values().then(a=>{o===r.current&&n(a)}).catch(a=>{o===r.current&&console.error("Error fetching settings:",a)})},[]);u.useEffect(()=>{const o=D.On("settings/changed",()=>s());return s(),()=>{r.current+=1,o()}},[s]);const i=u.useCallback(()=>{s()},[s]);return x.jsx(he.Provider,{value:{settings:e,reload:i},children:t})},De={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Fe=u.createContext(De),Ne=u.createContext(void 0),Le=u.createContext(void 0),me=u.createContext(void 0),ft=3e4,pt=({children:t})=>{const[e,n]=u.useState([]),r=u.useCallback(a=>{n(c=>[a,...c])},[]),s=u.useCallback((a,c)=>{n(d=>d.map(l=>l.id===a?{...l,...c}:l))},[]),i=u.useCallback(a=>{n(c=>c.filter(d=>d.id!==a))},[]);u.useEffect(()=>{const a=[];for(const c of e)if(c.status!=="running"){const d=Date.now()-(c.completedAt??c.startedAt),l=Math.max(0,ft-d);a.push(setTimeout(()=>i(c.id),l))}return()=>a.forEach(clearTimeout)},[e,i]);const o=u.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return x.jsx(me.Provider,{value:o,children:t})};var pe=function(t,e){return pe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},pe(t,e)};function gt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");pe(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var le="Invariant Violation",ve=Object.setPrototypeOf,yt=ve===void 0?function(t,e){return t.__proto__=e,t}:ve,ht=function(t){gt(e,t);function e(n){n===void 0&&(n=le);var r=t.call(this,typeof n=="number"?le+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=le,yt(r,e.prototype),r}return e}(Error);function ge(t,e){if(!t)throw new ht(e)}var Me=["debug","log","warn","error","silent"],mt=Me.indexOf("log");function J(t){return function(){if(Me.indexOf(t)>=mt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=J("debug"),t.log=J("log"),t.warn=J("warn"),t.error=J("error")})(ge||(ge={}));const ke=u.createContext(void 0),qe=()=>u.useContext(ke);function Et(t){const e=qe(),n=u.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=u.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=u.useCallback(()=>{const o=e==null?void 0:e.getExtensionPoint(t);if(!o){if(n.current&&n.current.store===void 0)return n.current.sentinel;const d={};return n.current={store:void 0,version:-1,sentinel:d},d}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return u.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const St=({registry:t,children:e})=>{const n=u.useRef(t);return ge(n.current===t,"You can't change the extension registry after it has been rendered"),x.jsx(ke.Provider,{value:n.current,children:e})},de=t=>{if(!t||typeof t!="string")throw new TypeError(`extensionName is required to be a string and can't be: "${t}" (${typeof t})`);return t.trim()};class Ue{constructor(e){L(this,"id");L(this,"mode");L(this,"_pluginId");L(this,"_version",0);L(this,"_contributions",new Map);L(this,"_lookupCache",new Map);L(this,"_matcher");L(this,"_select");L(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class Ct{constructor(e){L(this,"_stores",new Map);L(this,"_storeUnsubs",new Map);L(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=de(e.id);if(this._stores.has(n)){const s=this._stores.get(n);throw new Error(`Extension point "${n}" already exists (owned by "${s.pluginId??"unknown"}")`)}const r=new Ue({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=de(e);return this._stores.get(n)}hasExtensionPoint(e){const n=de(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const $e=u.createContext(void 0),_t={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},wt=({children:t})=>{const{toast:e}=H.useToast(),[n,r]=u.useState([]),[s,i]=u.useState([]),[o,a]=u.useState(!1),[c,d]=u.useState(),[l,f]=u.useState(""),y=u.useRef(Date.now()),h=m=>{r(p=>[...p,m])},C=(m,p,g)=>{const R=typeof m=="object";let E="",v="info",I,w=5e3,b;if(R){if(E=m.message,m.showOnce){if(n.includes(E))return;h(E)}v=m.status,I=m.details,w=m.autoHideDuration??5e3,b=m.actions}else E=m,v=p,I=g;let O;if(v==="error"){const A={id:++y.current,message:E,details:I,created:new Date().toISOString(),actions:b};i(q=>[...q,A].slice(-20)),O={label:"Details",onClick:()=>{d(A.id),a(!0)}}}e(v==="error"?E:I??E,{severity:_t[v]??"info",title:v!=="error"&&I?E:void 0,duration:w,action:O??(b==null?void 0:b[0])})};return x.jsxs($e.Provider,{value:{showSnackbar:C,openNotifications:()=>a(!0),notificationCount:s.length},children:[t,o&&x.jsxs("aside",{"aria-label":"Notifications",style:{position:"fixed",right:16,bottom:64,zIndex:1400,width:"min(600px, calc(100vw - 32px))",maxHeight:"70vh",overflow:"auto",padding:16,background:"var(--ov-color-bg-surface, #202020)",color:"var(--ov-color-fg-default, #eee)",border:"1px solid currentColor",borderRadius:8},children:[x.jsx("h2",{children:"Notifications"}),x.jsx(H.Button,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Close"}),x.jsx(H.Button,{size:"sm",variant:"ghost",onClick:()=>{i([]),d(void 0),f("")},children:"Clear history"}),s.length===0&&x.jsx("p",{children:"No recent errors."}),s.slice().reverse().map(m=>{var p;return x.jsxs("details",{open:c===m.id,onToggle:g=>{g.currentTarget.open&&d(m.id)},children:[x.jsxs("summary",{children:[m.message," — ",x.jsx("time",{dateTime:m.created,children:new Date(m.created).toLocaleString()})]}),x.jsx("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere",userSelect:"text"},children:m.details||m.message}),x.jsx(H.Button,{size:"sm",variant:"ghost",onClick:async()=>{f("");try{await navigator.clipboard.writeText(`${m.message}
3
+ ${m.created}
4
+ ${m.details??""}`)}catch{f("Copy failed. Select the diagnostic text and copy it manually.")}},children:"Copy details"}),(p=m.actions)==null?void 0:p.map((g,R)=>x.jsx(H.Button,{size:"sm",variant:"ghost",onClick:g.onClick,children:g.label},`${g.label}-${R}`))]},m.id)}),l&&x.jsx("p",{role:"status",children:l})]})]})},U=()=>{const t=u.useContext($e);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function T(t){const e=u.useContext(ne),n=(e==null?void 0:e.pluginId)??t;if(!n)throw new Error("pluginID must be provided either via PluginContext or as an explicit parameter");return n}const bt=({pluginID:t,connectionID:e})=>{const n=T(t),r=_.useQueryClient(),{showSnackbar:s}=U(),i=[n,"connection","detail",e],{mutateAsync:o}=_.useMutation({mutationFn:async()=>S.StartConnection(n,e),onSuccess(f){r.setQueryData(i,f),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:M(s,"Failed to start connection")}),{mutateAsync:a}=_.useMutation({mutationFn:async()=>S.StopConnection(n,e),onSuccess(f){r.setQueryData(i,f)},onError:M(s,"Failed to stop connection")}),{mutateAsync:c}=_.useMutation({mutationFn:async f=>S.UpdateConnection(n,f),onSuccess(f,{name:y}){s({message:`Connection ${y} successfully updated`,status:"success"}),r.setQueryData(i,f),r.setQueriesData({queryKey:[n,"connection","list"]},h=>h==null?void 0:h.map(C=>C.id===e?f:C))},onError:M(s,"Failed to update connection")}),{mutateAsync:d}=_.useMutation({mutationFn:async()=>S.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.filter(y=>y.id!==e))},onError:M(s,"Failed to remove connection")});return{connection:_.useQuery({queryKey:i,queryFn:async()=>S.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:d}},je=t=>[t,"connection","list"],Rt=({plugin:t})=>{const e=T(t),n=_.useQueryClient(),{showSnackbar:r}=U(),s=je(e),{mutateAsync:i}=_.useMutation({mutationFn:async d=>S.StartConnectionWatch(e,d.id),onError:M(r,"Failed to start connection watch")}),{mutateAsync:o}=_.useMutation({mutationFn:async d=>S.StopConnectionWatch(e,d.id),onError:M(r,"Failed to stop connection watch")}),a=u.useCallback(d=>{const l=d.data;console.log("got update to connections",l),n.setQueryData(s,l)},[n,s]);return u.useEffect(()=>{const d=D.On(`${e}/connection/sync`,a);return()=>{d()}},[e,a]),{connections:_.useQuery({queryKey:s,queryFn:async()=>{try{return await S.ListConnections(e)}catch(d){console.log(d),M(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:_.keepPreviousData}),startWatch:i,stopWatch:o}},vt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"connection","namespaces",e];return{namespaces:_.useQuery({queryKey:r,queryFn:async()=>S.GetConnectionNamespaces(n,e)})}},P=ct.withLegacyNames(N.WatchState,"WatchState");function ye(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const l of e)l===P.WatchStateSynced&&r++,(l===P.WatchStateError||l===P.WatchStateFailed)&&s++,l===P.WatchStateForbidden&&i++,l===P.WatchStateSkipped&&o++;const a=n-o,c=e.filter(l=>l===P.WatchStateSynced||l===P.WatchStateError||l===P.WatchStateStopped||l===P.WatchStateFailed||l===P.WatchStateForbidden).length,d=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:d}}function te(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Qe(t){return t.some(e=>!te(e))}function We(t){const e=t.reduce((r,s)=>r+s.watchedTotal,0);return e===0?0:t.reduce((r,s)=>r+s.doneCount,0)/e}function Ee(t){return`${t.pluginId}/${t.connection}`}function Ge(t,e){const n=Ee(e);t.has(n)||t.set(n,{states:{},pluginID:e.pluginId,connectionID:e.connection});const r=t.get(n);return r.states[e.resourceKey]=e.state,r}function It(){const[t,e]=u.useState(new Set),[n,r]=u.useState({}),[s,i]=u.useState(new Map),o=u.useRef(new Map),[a,c]=u.useState(new Map);u.useEffect(()=>{const E=D.On("plugin/crash_recovery_failed",I=>{const w=I.data,b=w==null?void 0:w.pluginID;b&&c(O=>{const A=new Map(O);return A.set(b,w.error??"Crash recovery failed"),A})}),v=D.On("plugin/recovered",I=>{const w=I.data,b=w==null?void 0:w.pluginID;b&&c(O=>{if(!O.has(b))return O;const A=new Map(O);return A.delete(b),A})});return()=>{E(),v()}},[]),u.useEffect(()=>{S.GetAllConnectionStates().then(E=>{if(!E)return;const v={},I=new Set,w=new Map;for(const[b,O]of Object.entries(E))if(O){v[b]=O.map(A=>A.connection);for(const A of O){if(!A.started)continue;const q=`${b}/${A.connection.id}`;I.add(q);const k={pluginID:b,connectionID:A.connection.id,states:{}};if(A.resources)for(const[ae,ot]of Object.entries(A.resources))k.states[ae]=ot;o.current.set(q,k),w.set(q,ye(k))}}r(v),e(I),i(w)}).catch(()=>{})},[]),u.useEffect(()=>D.On("connection/status",v=>{const I=v.data,w=`${I.pluginID}/${I.connectionID}`;I.status==="DISCONNECTED"?(e(b=>{const O=new Set(b);return O.delete(w),O}),i(b=>{const O=new Map(b);return O.delete(w),O}),o.current.delete(w)):e(b=>{const O=new Set(b);return O.add(w),O}),S.ListAllConnections().then(b=>{if(!b)return;const O={};for(const[A,q]of Object.entries(b))q!=null&&(O[A]=q);r(O)}).catch(()=>{})}),[]);const d=u.useCallback(E=>{const v=E.data,I=Ee(v);e(O=>{if(O.has(I))return O;const A=new Set(O);return A.add(I),A});const w=Ge(o.current,v),b=ye(w);i(O=>{const A=new Map(O);return A.set(I,b),A})},[]);u.useEffect(()=>D.On("watch/STATE",d),[d]);const l=u.useCallback(async(E,v)=>{await S.StopConnection(E,v)},[]),f=u.useCallback(async(E,v)=>{await S.StartConnectionWatch(E,v)},[]),y=u.useCallback(async E=>{const v=a.get(E);c(I=>{if(!I.has(E))return I;const w=new Map(I);return w.delete(E),w});try{await S.RetryFailedPlugin(E)}catch(I){throw c(w=>{const b=new Map(w);return b.set(E,v??"Reload failed"),b}),I}},[a]),h=[];for(const E of t){const[v,I]=E.split("/",2),b=(n[v]??[]).find(ae=>ae.id===I),O=s.get(E),A=O!=null&&!te(O),q=O!=null&&O.errorCount>0,k=a.get(v);h.push({pluginID:v,connectionID:I,name:(b==null?void 0:b.name)??I,avatar:(b==null?void 0:b.avatar)??"",isStarted:!0,sync:O,isSyncing:A,hasErrors:q||k!=null,pluginFailed:k!=null,pluginError:k})}const C=new Map;for(const E of h){const v=C.get(E.pluginID)??[];v.push(E),C.set(E.pluginID,v)}const m=Array.from(s.values()),p=h.filter(E=>E.isSyncing),g=h.filter(E=>E.hasErrors),R=h.filter(E=>E.pluginFailed);return{entries:h,grouped:C,connectedCount:h.length,syncingCount:p.length,errorCount:g.length,failedCount:R.length,hasSyncing:Qe(m),aggregateProgress:We(m),disconnect:l,retryWatch:f,retryPlugin:y}}function Ot(t,e){return e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?typeof t=="object"&&t!==null&&!Array.isArray(t):typeof t==typeof e}function xt(t,e,n){const r=T(t),s=_.useQueryClient(),i=[r,"data",e],o=_.useQuery({queryKey:i,queryFn:async()=>{const c=await S.Get(r,e);return c==null?n:Ot(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=_.useMutation({mutationFn:async c=>{await S.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const d=s.getQueryData(i);return s.setQueryData(i,c),{previous:d}},onError:(c,d,l)=>{(l==null?void 0:l.previous)!==void 0&&s.setQueryData(i,l.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const Pt=()=>{const t=u.useContext(Ne);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},Se=()=>{const t=u.useContext(Fe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},At=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r,updateTab:s}=Se();return{createSession:_.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:d})=>{const l=`pending-${crypto.randomUUID()}`;r({id:l,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...d}}});const f=N.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const y=await S.CreateSession(e,o,f);if(!y)throw new Error("Failed to create session: null response");s({id:l},{id:y.id,title:c??`Session ${y.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...d}}})}catch(y){const h=j(y);s({id:l},{properties:{status:"error",error:h.detail,pluginID:e,connectionID:o,opts:{...d}}}),Q(n,y,"Failed to start session")}}}).mutateAsync}},Tt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r}=Se(),s=_.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:d,icon:l,label:f,target:y,follow:h=!0,tailLines:C=1e3,params:m})=>{const p=N.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:d,options:N.LogSessionOptions.createFrom({target:y??"",follow:h,include_previous:!1,include_timestamps:!0,tail_lines:C,since_seconds:0,limit_bytes:0,include_source_events:!0,params:m??{}})}),g=await S.CreateSession$1(e,o,p);if(!g)throw new Error("Failed to create log session: null response");return r({id:g.id,title:f??`Logs ${g.id.substring(0,8)}`,variant:"logs",icon:l??"LuLogs"}),g},onError:M(n,"Failed to start log session")}),i=_.useMutation({mutationFn:async o=>{await S.CloseSession(o)},onError:M(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Dt=()=>_.useQuery({queryKey:["metric","providers"],queryFn:S.GetProviders,staleTime:3e4}),Ke=t=>_.useQuery({queryKey:["metric","providers",t],queryFn:()=>S.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Ft=t=>{var p,g;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:d=0,enabled:l=!0}=t,{data:f,isLoading:y}=Ke(n),h=f??[],C=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,m=_.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(p=c==null?void 0:c.start)==null?void 0:p.getTime(),(g=c==null?void 0:c.end)==null?void 0:g.getTime()],queryFn:async()=>{const R=await S.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),C),E={};for(const[v,I]of Object.entries(R))I!=null&&(E[v]=I);return E},enabled:l&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&h.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:_.keepPreviousData});return{data:m.data??void 0,providers:h,isLoading:y||m.isLoading,error:m.error,refetch:m.refetch}},Nt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:d=!0}=t,l=T(e),[f,y]=u.useState(null),[h,C]=u.useState(null),[m,p]=u.useState(!1),[g,R]=u.useState(null),E=u.useRef(null),v=u.useCallback(async()=>{if(!(!d||!l||!n||!r||!s))try{const w=await S.Subscribe(l,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});C(w),p(!0),R(null);const b=D.On(`core/metrics/data/${w}`,A=>{const q=A.data;try{const k=JSON.parse(q);k.results&&y(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),O=D.On(`core/metrics/error/${w}`,A=>{const q=A.data;try{const k=JSON.parse(q);R(k.error||"Unknown error")}catch{R("Failed to parse metric stream error")}});E.current=()=>{b(),O()}}catch(w){R(w instanceof Error?w.message:String(w))}},[l,n,r,s,i,a,c,d]),I=u.useCallback(async()=>{if(h)try{await S.Unsubscribe(h)}catch(w){console.error("Failed to unsubscribe:",w)}E.current&&(E.current(),E.current=null),C(null),p(!1)},[h]);return u.useEffect(()=>()=>{h&&S.Unsubscribe(h).catch(console.error),E.current&&E.current()},[h]),{data:f,subscriptionID:h,isStreaming:m,error:g,start:v,stop:I}},W=["networker","portforward","all-sessions"];function Lt(){const{showSnackbar:t}=U(),e=_.useQueryClient(),n=_.useQuery({queryKey:[...W],queryFn:async()=>S.ListAllPortForwardSessions().catch(i=>{if(j(i).detail.includes("not found"))return[];throw i}),retry:!1});u.useEffect(()=>{const i=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...W]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...W]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=_.useMutation({mutationFn:async i=>S.ClosePortForwardSession(i),onError:M(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...W]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>D.OpenURL(`http://localhost:${i}`)}}function Mt({pluginID:t,connectionID:e,resourceID:n}){const r=T(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=U(),o=_.useQueryClient(),a=_.useQuery({queryKey:s,queryFn:async()=>S.FindPortForwardSessions(r,e,N.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(l=>{const f=j(l);return f.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:f.detail}),[])}),retry:!1}),c=_.useMutation({mutationFn:async({opts:l})=>{const f=N.PortForwardSessionOptions.createFrom({local_port:l.localPort||0,remote_port:l.remotePort,protocol:l.protocol||"TCP",connection_type:"RESOURCE",connection:{resource_data:l.resource,connection_id:e,plugin_id:r,resource_id:l.resourceId,resource_key:l.resourceKey},labels:l.labels??{},params:l.parameters??{}}),y=await S.StartResourcePortForwardingSession(r,e,f);if(!y)throw new Error("Failed to start port forwarding: null response");return l.openInBrowser&&D.OpenURL(`http://localhost:${y.local_port}`),y},onError:M(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...W]})])}}),d=_.useMutation({mutationFn:async({opts:l})=>S.ClosePortForwardSession(l.sessionID),onError:M(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...W]})])}});return{sessions:a,forward:c.mutateAsync,close:d.mutateAsync}}const kt=()=>{const t=u.useContext(Le);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},qt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=T(t),o=_.useQueryClient(),{showSnackbar:a}=U(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:d}=_.useMutation({mutationFn:async y=>S.Update(i,e,n,N.UpdateInput.createFrom({input:y.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to update resource ${r}`)}),{mutateAsync:l}=_.useMutation({mutationFn:async(y={})=>S.Delete(i,e,n,N.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:y.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to delete resource ${r}`)});return{resource:_.useQuery({queryKey:c,queryFn:async()=>S.Get$1(i,e,n,N.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:l}},Ut=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:_.useQuery({queryKey:e,queryFn:async()=>S.GetResourceAreaComponent(t)})}},$t=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resource_groups","list"];return{groups:_.useQuery({queryKey:r,queryFn:async()=>S.GetResourceGroups(n,e),retry:!1})}},jt=({pluginID:t,connectionID:e,searches:n})=>{const r=T(t),s=o=>[r,e,o.key,o.namespaces,"list"];return _.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>S.List(r,e,o.key,N.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},Qt=({pluginID:t,resourceKey:e})=>{const n=T(t),r=[n,"resources",e];return{resourceType:_.useQuery({queryKey:r,queryFn:async()=>S.GetResourceType(n,e),retry:!1})}},Wt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resources","list",e];return{types:_.useQuery({queryKey:r,queryFn:async()=>S.GetResourceTypes(n,e),retry:!1})}};var X=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Kt="Expected a function",Be="__lodash_hash_undefined__",Bt="[object Function]",Ht="[object GeneratorFunction]",zt="[object Symbol]",Vt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yt=/^\w*$/,Jt=/^\./,Xt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Zt=/[\\^$.*+?()[\]{}|]/g,en=/\\(\\)?/g,tn=/^\[object .+?Constructor\]$/,nn=typeof X=="object"&&X&&X.Object===Object&&X,rn=typeof self=="object"&&self&&self.Object===Object&&self,Ce=nn||rn||Function("return this")();function sn(t,e){return t==null?void 0:t[e]}function on(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var an=Array.prototype,cn=Function.prototype,He=Object.prototype,fe=Ce["__core-js_shared__"],Ie=function(){var t=/[^.]+$/.exec(fe&&fe.keys&&fe.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),ze=cn.toString,_e=He.hasOwnProperty,Ve=He.toString,un=RegExp("^"+ze.call(_e).replace(Zt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Oe=Ce.Symbol,ln=an.splice,dn=Ye(Ce,"Map"),Y=Ye(Object,"create"),xe=Oe?Oe.prototype:void 0,Pe=xe?xe.toString:void 0;function G(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function fn(){this.__data__=Y?Y(null):{}}function pn(t){return this.has(t)&&delete this.__data__[t]}function gn(t){var e=this.__data__;if(Y){var n=e[t];return n===Be?void 0:n}return _e.call(e,t)?e[t]:void 0}function yn(t){var e=this.__data__;return Y?e[t]!==void 0:_e.call(e,t)}function hn(t,e){var n=this.__data__;return n[t]=Y&&e===void 0?Be:e,this}G.prototype.clear=fn;G.prototype.delete=pn;G.prototype.get=gn;G.prototype.has=yn;G.prototype.set=hn;function B(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function mn(){this.__data__=[]}function En(t){var e=this.__data__,n=se(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():ln.call(e,n,1),!0}function Sn(t){var e=this.__data__,n=se(e,t);return n<0?void 0:e[n][1]}function Cn(t){return se(this.__data__,t)>-1}function _n(t,e){var n=this.__data__,r=se(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}B.prototype.clear=mn;B.prototype.delete=En;B.prototype.get=Sn;B.prototype.has=Cn;B.prototype.set=_n;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function wn(){this.__data__={hash:new G,map:new(dn||B),string:new G}}function bn(t){return oe(this,t).delete(t)}function Rn(t){return oe(this,t).get(t)}function vn(t){return oe(this,t).has(t)}function In(t,e){return oe(this,t).set(t,e),this}K.prototype.clear=wn;K.prototype.delete=bn;K.prototype.get=Rn;K.prototype.has=vn;K.prototype.set=In;function se(t,e){for(var n=t.length;n--;)if(kn(t[n][0],e))return n;return-1}function On(t,e){e=Tn(e,t)?[e]:An(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Ln(e[n++])];return n&&n==r?t:void 0}function xn(t){if(!Xe(t)||Fn(t))return!1;var e=qn(t)||on(t)?un:tn;return e.test(Mn(t))}function Pn(t){if(typeof t=="string")return t;if(be(t))return Pe?Pe.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function An(t){return Je(t)?t:Nn(t)}function oe(t,e){var n=t.__data__;return Dn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ye(t,e){var n=sn(t,e);return xn(n)?n:void 0}function Tn(t,e){if(Je(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||be(t)?!0:Yt.test(t)||!Vt.test(t)||e!=null&&t in Object(e)}function Dn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Fn(t){return!!Ie&&Ie in t}var Nn=we(function(t){t=$n(t);var e=[];return Jt.test(t)&&e.push(""),t.replace(Xt,function(n,r,s,i){e.push(s?i.replace(en,"$1"):r||n)}),e});function Ln(t){if(typeof t=="string"||be(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Mn(t){if(t!=null){try{return ze.call(t)}catch{}try{return t+""}catch{}}return""}function we(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Kt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(we.Cache||K),n}we.Cache=K;function kn(t,e){return t===e||t!==t&&e!==e}var Je=Array.isArray;function qn(t){var e=Xe(t)?Ve.call(t):"";return e==Bt||e==Ht}function Xe(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Un(t){return!!t&&typeof t=="object"}function be(t){return typeof t=="symbol"||Un(t)&&Ve.call(t)==zt}function $n(t){return t==null?"":Pn(t)}function jn(t,e,n){var r=t==null?void 0:On(t,e);return r===void 0?n:r}var Qn=jn;const Z=Gt(Qn);function Ze(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=Z(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>Z(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>Z(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>Z(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function et(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=u.useRef([]),c=u.useRef(null),d=u.useRef(null),l=u.useRef(s);l.current=s;const f=u.useCallback(()=>{const h=a.current;if(a.current=[],c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),!(h.length===0||!r)){t.setQueryData(e,C=>Ze(C,h,r));for(const C of h)(C.type==="ADD"||C.type==="UPDATE")&&t.setQueryData(n(C.payload.id,C.payload.namespace),{result:C.payload.data})}},[t,e,n,r]),y=u.useCallback(h=>{a.current.push(h),!(c.current!==null||d.current!==null)&&(c.current=setTimeout(f,o),l.current!==1&&(d.current=requestAnimationFrame(f)))},[f,o]);return u.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),y}const Wn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=T(t),o=_.useQueryClient(),{showSnackbar:a}=U(),c=u.useMemo(()=>s??[],[s]),d=u.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),l=u.useCallback((p,g)=>[i,e,n,g,p],[i,e,n]),{mutateAsync:f}=_.useMutation({mutationFn:async p=>S.Create(i,e,n,N.CreateInput.createFrom({input:p.input,namespace:p.namespace??(c.length===1?c[0]:"")})),onSuccess:async p=>{var v;const g=p==null?void 0:p.result;let R="";(v=g==null?void 0:g.metadata)!=null&&v.name?R=g.metadata.name:g!=null&&g.id?R=g.id:g!=null&&g.name?R=g.name:g!=null&&g.ID?R=g.ID:g!=null&&g.Name&&(R=g.Name);const E=R?`Resource ${R} created`:"Resource created";a(E,"success"),await o.invalidateQueries({queryKey:d})},onError:M(a,"Failed to create resource")}),y=_.useQuery({queryKey:d,queryFn:async()=>S.List(i,e,n,N.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(p,g)=>p,retry:!1}),[h,C]=u.useState(P.WatchStateIdle);u.useEffect(()=>D.On(`${i}/${e}/watch/STATE`,g=>{const R=g.data;R.resourceKey===n&&C(R.state)}),[i,e,n]);const m=et(o,d,l,r,h);return u.useEffect(()=>{if(!r)return;S.SubscribeResource(i,e,n);const p=D.On(`${i}/${e}/${n}/ADD`,E=>m({type:"ADD",payload:E.data})),g=D.On(`${i}/${e}/${n}/UPDATE`,E=>m({type:"UPDATE",payload:E.data})),R=D.On(`${i}/${e}/${n}/DELETE`,E=>m({type:"DELETE",payload:E.data}));return()=>{p(),g(),R(),S.UnsubscribeResource(i,e,n)}},[i,e,n,m]),{resources:y,create:f,watchState:h,isSyncing:h===P.WatchStateSyncing,isSynced:h===P.WatchStateSynced,watchError:h===P.WatchStateError}},Gn=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),r=_.useMutation({mutationFn:async({opts:o,input:a})=>S.Create(e,o.connectionID,o.resourceKey,N.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){Q(n,o,`Failed to create resource ${a.resourceID}`)}}),s=_.useMutation({mutationFn:async({opts:o,input:a})=>S.Update(e,o.connectionID,o.resourceKey,N.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){Q(n,o,`Failed to update resource ${a.resourceID}`)}}),i=_.useMutation({mutationFn:async({opts:o,input:a})=>S.Delete(e,o.connectionID,o.resourceKey,N.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){Q(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Kn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=T(t),i=_.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>S.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},Bn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),s=_.useQueryClient(),{showSnackbar:i}=U(),o=_.useMutation({mutationFn:async({actionID:a,id:c="",namespace:d="",params:l={}})=>S.ExecuteAction(r,e,n,a,N.ActionInput.createFrom({id:c,namespace:d,params:l})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{Q(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Hn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=_.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>S.GetEditorSchemas(r,e),enabled:n&&!!r&&!!e,staleTime:10*60*1e3,retry:1});return{schemas:s.data??[],isLoading:s.isLoading,error:s.error,refetch:s.refetch}},zn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=_.useQueryClient(),i=[r,e,"watch-state"],o=u.useRef([]),a=u.useRef(!1),c=u.useCallback(y=>{s.setQueryData(i,h=>{if(!h)return h;const C={...h.resources,[y.resourceKey]:y.state},m={...h.resourceCounts,[y.resourceKey]:y.resourceCount};let p=0,g=0;for(const R of Object.values(C))R===P.WatchStateSynced&&p++,(R===P.WatchStateError||R===P.WatchStateFailed)&&g++;return{...h,resources:C,resourceCounts:m,totalResources:Object.keys(C).length,syncedCount:p,errorCount:g}})},[s,r,e]),d=_.useQuery({queryKey:i,queryFn:async()=>{const y=await S.GetWatchState(r,e);if(!y)throw new Error("Failed to get watch state: null response");const h={};let C=0,m=0;for(const[g,R]of Object.entries(y.resources??{}))R!=null&&(h[g]=R,R===P.WatchStateSynced&&C++,R===P.WatchStateError&&m++);const p={};for(const[g,R]of Object.entries(y.resourceCounts??{}))R!=null&&(p[g]=R);return{connection:y.connectionId,resources:h,resourceCounts:p,totalResources:Object.keys(h).length,syncedCount:C,errorCount:m}},enabled:n&&!!r&&!!e,refetchInterval:y=>{const h=y.state.data;if(!h||h.totalResources===0)return 3e3;let C=0;for(const m of Object.values(h.resources))(m===P.WatchStateSynced||m===P.WatchStateError||m===P.WatchStateStopped||m===P.WatchStateFailed||m===P.WatchStateForbidden||m===P.WatchStateSkipped)&&C++;return C>=h.totalResources?!1:3e3}});u.useEffect(()=>{if(!d.data||a.current)return;a.current=!0;const y=o.current;o.current=[];for(const h of y)c(h)},[d.data,c]),u.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const y=D.On(`${r}/${e}/watch/STATE`,h=>{const C=h.data;a.current?c(C):o.current.push(C)});return()=>{y(),a.current=!1,o.current=[]}},[r,e,n,c]);const l=d.data;let f=0;if(l!=null&&l.resources)for(const y of Object.values(l.resources))(y===P.WatchStateSynced||y===P.WatchStateError||y===P.WatchStateStopped||y===P.WatchStateFailed||y===P.WatchStateForbidden||y===P.WatchStateSkipped)&&f++;return{summary:d,getResourceState:y=>l==null?void 0:l.resources[y],isFullySynced:l?l.totalResources>0&&f===l.totalResources:!1,syncProgress:l&&l.totalResources>0?f/l.totalResources:0,errorCount:(l==null?void 0:l.errorCount)??0}},Vn=()=>{const[t,e]=u.useState(new Map),n=u.useRef(new Map),r=u.useRef(new Map),s=u.useCallback(d=>{const l=d.data,f=Ee(l),y=Ge(n.current,l),h=ye(y);if(e(C=>{const m=new Map(C);return m.set(f,h),m}),r.current.has(f)&&(clearTimeout(r.current.get(f)),r.current.delete(f)),te(h)){const C=setTimeout(()=>{e(m=>{const p=new Map(m);return p.delete(f),p}),n.current.delete(f),r.current.delete(f)},5e3);r.current.set(f,C)}},[]);u.useEffect(()=>{const d=D.On("watch/STATE",s);return()=>{d();for(const l of r.current.values())clearTimeout(l)}},[s]);const i=Array.from(t.values()),o=Qe(i),a=i.find(d=>!te(d))??i[0]??null,c=We(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},tt=()=>{const t=u.useContext(me);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Yn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),{showSnackbar:s}=U(),{addOperation:i,updateOperation:o}=tt(),a=u.useRef(new Set),c=u.useCallback((f,y=!1)=>{var h,C,m;f.disposed||(f.disposed=!0,(h=f.unsubscribe)==null||h.call(f),(C=f.open)==null||C.cancel(),(m=f.attach)==null||m.cancel(),f.handle&&(S.CancelStreamAction(f.handle).catch(()=>{}),y&&o(f.handle,{status:"cancelled",message:"Cancelled",completedAt:Date.now()})),a.current.delete(f))},[o]);u.useEffect(()=>()=>{for(const f of a.current)c(f,!0)},[r,e,n,c]);const d=u.useCallback(async({actionID:f,id:y,namespace:h,label:C,params:m={}})=>{const p={disposed:!1,terminal:!1,sequence:0};a.current.add(p);try{p.open=S.StreamAction(r,e,n,f,N.ActionInput.createFrom({id:y,namespace:h,params:m}));const g=await p.open;if(p.open=void 0,p.disposed)return S.CancelStreamAction(g).catch(()=>{}),g;p.handle=g,i({id:g,label:C,resourceKey:n,resourceName:y,namespace:h,connectionID:e,status:"running",startedAt:Date.now()});const R=v=>{if(p.disposed||!Number.isSafeInteger(v.sequence)||v.sequence<=p.sequence)return;p.sequence=v.sequence;const I=v.event,w=I.data??{};if(I.type==="error"){p.terminal=!0;const b=j(I.error);o(g,{status:V(b)?"cancelled":"error",message:b.title,completedAt:Date.now()}),Q(s,b,C),c(p)}else if(I.type==="complete"){p.terminal=!0;const b=typeof w.message=="string"?w.message:`${C} completed`;o(g,{status:"completed",message:b,completedAt:Date.now()}),s(b,"success"),c(p)}else o(g,{message:typeof w.message=="string"?w.message:void 0,progress:typeof w.ready=="number"&&typeof w.desired=="number"?{ready:w.ready,desired:w.desired}:void 0})};p.unsubscribe=D.On(`action/stream/${g}`,v=>R(v.data)),p.attach=S.AttachStreamAction(g);const E=await p.attach;return p.attach=void 0,R(E),g}catch(g){if(p.terminal&&p.handle)return p.handle;throw p.disposed||(p.handle&&o(p.handle,{status:V(g)?"cancelled":"error",message:j(g).title,completedAt:Date.now()}),Q(s,g,`Failed to start "${f}"`)),c(p),g}},[r,e,n,i,o,s,c]),l=u.useCallback(f=>{for(const y of a.current)if(y.handle===f){c(y,!0);return}},[c]);return{startStreamAction:d,cancelStreamAction:l}};function nt(t,e){return`${t}/${e}/graph/CHANGED`}function ie(t,e,n,r){const s=_.useQueryClient(),i=u.useRef(n);i.current=n;const o=JSON.stringify(n);u.useEffect(()=>{if(!r||!t||!e)return;const a=D.On(nt(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const Jn={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function Xn(t,e){const n=Jn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function Zn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function rt(t,e){return e.map(n=>{const r=Zn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const er=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const d=T(t),l=["RESOURCE_RELATED",d,e,n,s,r,i,o??null],f=a&&!!d&&!!e&&!!n&&!!r;ie(d,e,l,f);const y=_.useQuery({queryKey:l,queryFn:async()=>S.GetRelated(d,e,n,s,r,i,o??null),enabled:f,refetchInterval:c}),h={pluginId:d,connectionId:e,resourceKey:n,id:r,namespace:s},C=y.data??[];return{related:rt(h,C),edges:C,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},tr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=T(t),d=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],l=o&&!!c&&!!e&&!!n&&!!r;ie(c,e,d,l);const f=_.useQuery({queryKey:d,queryFn:async()=>S.GetDependencyTree(c,e,n,s,r,i),enabled:l,refetchInterval:a});return{tree:f.data??null,isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}},nr=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=T(t),d=["RESOURCE_GRAPH",c,e,n,s,r,i,o],l=a&&!!c&&!!e&&!!n&&!!r;ie(c,e,d,l);const f=_.useQuery({queryKey:d,queryFn:async()=>S.GetSubgraph(c,e,n,s,r,i,o),enabled:l});return{graph:f.data??null,isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}},rr=()=>{const t=u.useContext(he);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},sr=({to:t,withinContext:e,...n})=>{const{pluginId:r}=re();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return u.useMemo(()=>x.jsx(z.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function or(){const t=z.useNavigate(),e=z.useLocation(),{pluginId:n}=re();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=u.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return u.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class ir{}class ar{constructor(){L(this,"_extensions");L(this,"root");L(this,"pages");L(this,"_routes")}get extensions(){return this._extensions||[]}get Routes(){var e;if(!this._routes&&this.root)return[{path:"",index:!0,Component:this.root}];if(!((e=this._routes)!=null&&e.length))throw new Error("cannot use plugin without a root page or router");return this._routes}get Window(){if(!this._routes&&this.root)return x.jsx(this.root,{});const e=z.createMemoryRouter(this._routes||[]);return x.jsx(z.RouterProvider,{router:e})}registerExtensionPoints(e){return this._extensions=e||[],this}setRootPage(e){return this.root=e,this}withPage(e,n){return this.pages||(this.pages={}),this.pages[e]?(console.warn("Cannot register page with the same name. Please use a different name."),this):(this.pages[e]=n,this)}withRoutes(e){return this._routes=e,this}}var st=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(st||{});const cr=t=>{const e=t.split("::");return e.length===1?{group:"core",version:"",kind:e[0]}:{group:e[0]||"core",version:e[1]||"",kind:e[2]||e[0]}},ur=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=W;exports.BottomDrawerContext=Fe;exports.ConfirmationModalContext=Le;exports.ErrorTypes=F;exports.ExtensionPointRegistry=Ct;exports.ExtensionPointStore=Ue;exports.ExtensionProvider=St;exports.Link=sr;exports.OperationsContext=me;exports.OperationsProvider=pt;exports.PluginContext=ne;exports.PluginContextProvider=ut;exports.PluginErrorCode=st;exports.PluginWindow=ar;exports.PluginWindowRootProps=ir;exports.RightDrawerContext=Ne;exports.SettingsContext=he;exports.SettingsProvider=dt;exports.SnackbarProvider=wt;exports.WatchState=P;exports.actionToSnackbar=Ae;exports.applyBatch=Ze;exports.connectionListQueryKey=je;exports.createErrorHandler=M;exports.defaultState=De;exports.formatGroup=ur;exports.graphChangedEvent=nt;exports.isCancelledError=V;exports.parseAppError=j;exports.parseResourceKey=cr;exports.relationshipLabel=Xn;exports.showAppError=Q;exports.toRelatedResources=rt;exports.useActiveSyncs=Vn;exports.useBottomDrawer=Se;exports.useConfirmationModal=kt;exports.useConnection=bt;exports.useConnectionNamespaces=vt;exports.useConnectionStatus=It;exports.useConnections=Rt;exports.useDependencyTree=tr;exports.useEditorSchemas=Hn;exports.useEventBatcher=et;exports.useExec=At;exports.useExecuteAction=Bn;exports.useExtensionPoint=Et;exports.useExtensionRegistry=qe;exports.useLogs=Tt;exports.useMetricProviders=Dt;exports.useMetricProvidersForResource=Ke;exports.useMetricStream=Nt;exports.useOperations=tt;exports.usePluginContext=re;exports.usePluginData=xt;exports.usePluginRouter=or;exports.usePluginSettings=lt;exports.usePortForwardSessions=Lt;exports.useRefetchOnGraphChange=ie;exports.useRelatedResources=er;exports.useResolvedPluginId=T;exports.useResource=qt;exports.useResourceActions=Kn;exports.useResourceAreaComponent=Ut;exports.useResourceGraph=nr;exports.useResourceGroups=$t;exports.useResourceMetrics=Ft;exports.useResourceMutations=Gn;exports.useResourcePortForwarder=Mt;exports.useResourceSearch=jt;exports.useResourceType=Qt;exports.useResourceTypes=Wt;exports.useResources=Wn;exports.useRightDrawer=Pt;exports.useSettings=rr;exports.useSnackbar=U;exports.useStreamAction=Yn;exports.useWatchState=zn;