@omniviewdev/runtime 0.0.0-nightly.20260322 → 0.0.0-nightly.20260328

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.
@@ -0,0 +1,2 @@
1
+ export { DependencyNode, DependencyTree, GraphEdge, GraphNode } from './models.js';
2
+ export type { RelationshipType } from './models.js';
@@ -0,0 +1,53 @@
1
+ import * as resource$0 from "../../../../../../plugin-sdk/pkg/v1/resource/models.js";
2
+ export declare class DependencyNode {
3
+ "edge": GraphEdge;
4
+ "children": DependencyNode[];
5
+ /** Creates a new DependencyNode instance. */
6
+ constructor($$source?: Partial<DependencyNode>);
7
+ /**
8
+ * Creates a new DependencyNode instance from a string or object.
9
+ */
10
+ static createFrom($$source?: any): DependencyNode;
11
+ }
12
+ export declare class DependencyTree {
13
+ "root": GraphNode;
14
+ "children": DependencyNode[];
15
+ /** Creates a new DependencyTree instance. */
16
+ constructor($$source?: Partial<DependencyTree>);
17
+ /**
18
+ * Creates a new DependencyTree instance from a string or object.
19
+ */
20
+ static createFrom($$source?: any): DependencyTree;
21
+ }
22
+ export declare class GraphEdge {
23
+ "source": GraphNode;
24
+ "target": GraphNode;
25
+ "type": RelationshipType;
26
+ "label": string;
27
+ /** Creates a new GraphEdge instance. */
28
+ constructor($$source?: Partial<GraphEdge>);
29
+ /**
30
+ * Creates a new GraphEdge instance from a string or object.
31
+ */
32
+ static createFrom($$source?: any): GraphEdge;
33
+ }
34
+ /**
35
+ * GraphNode identifies a specific resource instance in the graph.
36
+ */
37
+ export declare class GraphNode {
38
+ "pluginId": string;
39
+ "connectionId": string;
40
+ "resourceKey": string;
41
+ "id": string;
42
+ "namespace"?: string;
43
+ /** Creates a new GraphNode instance. */
44
+ constructor($$source?: Partial<GraphNode>);
45
+ /**
46
+ * Creates a new GraphNode instance from a string or object.
47
+ */
48
+ static createFrom($$source?: any): GraphNode;
49
+ }
50
+ /**
51
+ * RelationshipType re-exports from SDK for convenience.
52
+ */
53
+ export type RelationshipType = resource$0.RelationshipType;
@@ -0,0 +1,14 @@
1
+ import { CancellablePromise as $CancellablePromise } from '@wailsio/runtime';
2
+ import * as graph$0 from "./graph/models.js";
3
+ /**
4
+ * GetDependencyTree follows all outgoing edges recursively.
5
+ */
6
+ export declare function GetDependencyTree(pluginID: string, connectionID: string, resourceKey: string, $namespace: string, id: string, maxDepth: number): $CancellablePromise<graph$0.DependencyTree | null>;
7
+ /**
8
+ * GetRelated returns edges connected to the given node.
9
+ */
10
+ export declare function GetRelated(pluginID: string, connectionID: string, resourceKey: string, $namespace: string, id: string, direction: string, relType: string | null): $CancellablePromise<graph$0.GraphEdge[]>;
11
+ /**
12
+ * GetRelationshipChain follows edges of a specific type up to maxDepth hops.
13
+ */
14
+ export declare function GetRelationshipChain(pluginID: string, connectionID: string, resourceKey: string, $namespace: string, id: string, relType: string, maxDepth: number): $CancellablePromise<graph$0.GraphEdge[][]>;
@@ -1,3 +1,4 @@
1
+ import * as GraphService from "./graphservice.js";
1
2
  import * as ServiceWrapper from "./servicewrapper.js";
2
- export { ServiceWrapper };
3
+ export { GraphService, ServiceWrapper };
3
4
  export { ConnectionState, ConnectionStatusPayload } from './models.js';
@@ -34,6 +34,9 @@ export type ResourceEvent = {
34
34
  /**
35
35
  * Apply a batch of resource events to a list query cache entry.
36
36
  * Extracted for testability — this is the core batching logic.
37
+ *
38
+ * Returns a new plain object (immutable-style) without relying on Immer,
39
+ * avoiding issues with Wails binding class instances that Immer cannot draft.
37
40
  */
38
41
  export declare function applyBatch(oldData: any, events: ResourceEvent[], idAccessor: string): any;
39
42
  /**
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Mt=Object.defineProperty;var kt=(e,t,n)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>kt(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("react/jsx-runtime"),l=require("react"),ee=require("react-router-dom"),g=require("./servicewrapper-BtYdL57C.cjs"),w=require("./models-2dDjO0f0.cjs"),_=require("@tanstack/react-query"),Wt=require("@omniviewdev/ui/feedback");require("./index-DCsB3HOd.cjs");const x=require("./events-D6Z9I2K4.cjs"),le=l.createContext(void 0),U={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",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",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",RESOURCE_CONNECTION_ERROR:"omniview:resource/connection-error",RESOURCE_CERTIFICATE_ERROR:"omniview:resource/certificate-error",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"};function Lt(e){switch(e){case"NOT_FOUND":return{typeUri:U.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:U.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:U.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:U.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:U.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:U.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:U.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:U.INTERNAL,status:500}}}function j(e){if(e==null)return{type:U.INTERNAL,title:"Unknown error",status:500,detail:"An unknown error occurred."};let t;if(typeof e=="string"?t=e:e instanceof Error?t=e.message:t=String(e),t.startsWith("{"))try{const n=JSON.parse(t);if(typeof n.type=="string"&&typeof n.title=="string"&&typeof n.status=="number"&&typeof n.detail=="string")return n;if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){const{typeUri:r,status:s}=Lt(n.code);return{type:r,title:n.title,status:s,detail:n.message,suggestions:Array.isArray(n.suggestions)?n.suggestions:void 0}}}catch{}return{type:U.INTERNAL,title:"Error",status:500,detail:t}}function Ae(e){return e==null?!1:(typeof e=="string"?e:e instanceof Error?e.message:String(e))==="cancelled"?!0:j(e).type===U.CANCELLED}function et(e){switch(e.type){case"navigate":return{label:e.label,onClick:()=>{window.location.hash=e.target??""}};case"open-url":return{label:e.label,onClick:()=>{window.open(e.target,"_blank")}};case"copy":return{label:e.label,onClick:()=>{navigator.clipboard.writeText(e.target??"")}};case"retry":return{label:e.label,onClick:()=>{}};default:return{label:e.label,onClick:()=>{}}}}function tt(e,t){var s,i;const n=[e.detail,...((s=e.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
- `);return{message:t||(e.title!=="Error"?e.title:"Operation failed"),status:"error",details:n,actions:(i=e.actions)==null?void 0:i.map(et)}}function z(e,t,n){if(Ae(t))return;const r=j(t);e(tt(r,n))}function N(e,t){return n=>{if(Ae(n))return;const r=j(n);e(tt(r,r.title!=="Error"?r.title:t))}}function $t(e){const{children:t,pluginId:n}=e,[r,s]=l.useState({}),[i,o]=l.useState(new w.PluginMeta),[a,c]=l.useState(!1),[d,u]=l.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!d});const h=()=>{n===void 0||n===""||(console.debug(`[PluginContextProvider] fetching settings for "${n}"`),g.PluginValues(n).then(f=>{console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),s(f)}).catch(f=>{const y=j(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,y.detail)}))},p=()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),g.GetPluginMeta(n).then(f=>{console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),o(f),c(!0)}).catch(f=>{const y=j(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,y.detail),u(y.detail),c(!1)})};return l.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),h(),p()},[n]),d?I.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:I.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:[I.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[I.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[I.jsx("circle",{cx:"12",cy:"12",r:"10"}),I.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),I.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),I.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),I.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),I.jsx("button",{onClick:()=>p(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?I.jsx(le.Provider,{value:{pluginId:n,settings:r,meta:i},children:t}):I.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[I.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),I.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function de(){const e=l.useContext(le);if(!e)throw new Error("usePluginContext must be used within a PluginContextProvider");return e}function Ut(){return de().settings}const Ne=l.createContext(void 0),qt=({children:e})=>{const[t,n]=l.useState({}),r=()=>{g.Values().then(i=>{console.log("Fetched settings:",i),n(i)}).catch(i=>{console.error("Error fetching settings:",i)})};l.useEffect(()=>{r()},[]);const s=()=>{r()};return I.jsx(Ne.Provider,{value:{settings:t,reload:s},children:e})},nt={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},rt=l.createContext(nt),st=l.createContext(void 0),ot=l.createContext(void 0),Me=l.createContext(void 0),jt=3e4,Qt=({children:e})=>{const[t,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 t)if(c.status==="completed"||c.status==="error"){const d=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,jt-d);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[t,i]);const o=l.useMemo(()=>({operations:t,addOperation:r,updateOperation:s,removeOperation:i}),[t,r,s,i]);return I.jsx(Me.Provider,{value:o,children:e})};var ve=function(e,t){return ve=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])},ve(e,t)};function Gt(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");ve(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Se="Invariant Violation",Ge=Object.setPrototypeOf,zt=Ge===void 0?function(e,t){return e.__proto__=t,e}:Ge,Kt=function(e){Gt(t,e);function t(n){n===void 0&&(n=Se);var r=e.call(this,typeof n=="number"?Se+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=Se,zt(r,t.prototype),r}return t}(Error);function Pe(e,t){if(!e)throw new Kt(t)}var it=["debug","log","warn","error","silent"],Bt=it.indexOf("log");function se(e){return function(){if(it.indexOf(e)>=Bt){var t=console[e]||console.log;return t.apply(console,arguments)}}}(function(e){e.debug=se("debug"),e.log=se("log"),e.warn=se("warn"),e.error=se("error")})(Pe||(Pe={}));const at=l.createContext(void 0),ct=()=>l.useContext(at);function Ht(e){const t=ct(),n=l.useRef(null),r=t==null?void 0:t.getExtensionPoint(e),s=l.useCallback(o=>{const a=[];return t&&a.push(t.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[t,e,r]),i=l.useCallback(()=>{const o=t==null?void 0:t.getExtensionPoint(e);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},[t,e]);return l.useSyncExternalStore(s,i),t==null?void 0:t.getExtensionPoint(e)}const Yt=({registry:e,children:t})=>{const n=l.useRef(e);return Pe(n.current===e,"You can't change the extension registry after it has been rendered"),I.jsx(at.Provider,{value:n.current,children:t})},we=e=>{if(!e||typeof e!="string")throw new TypeError(`extensionName is required to be a string and can't be: "${e}" (${typeof e})`);return e.trim()};class ut{constructor(t){A(this,"id");A(this,"mode");A(this,"_pluginId");A(this,"_version",0);A(this,"_contributions",new Map);A(this,"_lookupCache",new Map);A(this,"_matcher");A(this,"_select");A(this,"_listeners",new Set);this.id=t.id,this.mode=t.mode??"multiple",this._pluginId=t.pluginId,this._matcher=t.matcher,this._select=t.select}get pluginId(){return this._pluginId}get version(){return this._version}register(t){if(this._contributions.has(t.id))throw new Error(`Contribution with id "${t.id}" already exists in extension point "${this.id}"`);this._contributions.set(t.id,t),this._invalidateCache(),this._notify()}unregister(t){this._contributions.delete(t)&&(this._invalidateCache(),this._notify())}provide(t){return this._getMatched(t).map(r=>r.value)}list(t){return this._getMatched(t)}listAll(){return Array.from(this._contributions.values())}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}removeContributionsByPlugin(t){let n=!1;for(const[r,s]of this._contributions)s.plugin===t&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(t){const n=this._getCacheKey(t);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,t)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&t!==void 0&&(r=r.filter(s=>this._matcher(s,t))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,t)}_applyMode(t,n){if(this.mode==="single"){if(this._select){const r=this._select(t,n);return r?[r]:[]}return t.length>0?[t[0]]:[]}return t}_sortDeterministic(t){return[...t].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(t){if(t!=null&&typeof t=="object"&&"getCacheKey"in t){const n=t.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const t of this._listeners)t()}}class Jt{constructor(t){A(this,"_stores",new Map);A(this,"_storeUnsubs",new Map);A(this,"_listeners",new Set);if(t!=null&&t.initialStores)for(const n of t.initialStores)this.addExtensionPoint(n)}addExtensionPoint(t){const n=we(t.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 ut({...t,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(t){const n=we(t);return this._stores.get(n)}hasExtensionPoint(t){const n=we(t);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(t){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===t&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(t){for(const n of this._stores.values())n.removeContributionsByPlugin(t);this._notify()}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}_notify(){for(const t of this._listeners)t()}}const lt=l.createContext(void 0),Vt={default:"info",info:"info",success:"success",warning:"warning",error:"error"},Xt=({children:e})=>{const{push:t}=Wt.useNotificationStack(),[n,r]=l.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const d=typeof o=="object";let u="",h="info",p,f=5e3,y;if(d){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}h=o.status,p=o.details,f=o.autoHideDuration??5e3,y=o.actions}else u=o,h=a,p=c;t({severity:Vt[h]??"info",title:u,message:p,timeout:f,actions:y})};return I.jsx(lt.Provider,{value:{showSnackbar:i},children:e})},q=()=>{const e=l.useContext(lt);if(e===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return e};function T(e){const t=l.useContext(le),n=(t==null?void 0:t.pluginId)??e;if(!n)throw new Error("pluginID must be provided either via PluginContext or as an explicit parameter");return n}const Zt=({pluginID:e,connectionID:t})=>{const n=T(e),r=_.useQueryClient(),{showSnackbar:s}=q(),i=[n,"connection","detail",t],{mutateAsync:o}=_.useMutation({mutationFn:async()=>g.StartConnection(n,t),onSuccess(h){r.setQueryData(i,h),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,t]})},onError:N(s,"Failed to start connection")}),{mutateAsync:a}=_.useMutation({mutationFn:async()=>g.StopConnection(n,t),onSuccess(h){r.setQueryData(i,h)},onError:N(s,"Failed to stop connection")}),{mutateAsync:c}=_.useMutation({mutationFn:async h=>g.UpdateConnection(n,h),onSuccess(h,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,h),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(y=>y.id===t?h:y))},onError:N(s,"Failed to update connection")}),{mutateAsync:d}=_.useMutation({mutationFn:async()=>g.RemoveConnection(n,t),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},h=>h==null?void 0:h.filter(p=>p.id!==t))},onError:N(s,"Failed to remove connection")});return{connection:_.useQuery({queryKey:i,queryFn:async()=>g.GetConnection(n,t)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:d}},dt=e=>[e,"connection","list"],en=({plugin:e})=>{const t=T(e),n=_.useQueryClient(),{showSnackbar:r}=q(),s=dt(t),{mutateAsync:i}=_.useMutation({mutationFn:async d=>g.StartConnectionWatch(t,d.id),onError:N(r,"Failed to start connection watch")}),{mutateAsync:o}=_.useMutation({mutationFn:async d=>g.StopConnectionWatch(t,d.id),onError:N(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=x.On(`${t}/connection/sync`,a);return()=>{d()}},[t,a]),{connections:_.useQuery({queryKey:s,queryFn:async()=>{try{return await g.ListConnections(t)}catch(d){console.log(d),N(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:_.keepPreviousData}),startWatch:i,stopWatch:o}},tn=({pluginID:e,connectionID:t})=>{const n=T(e),r=[n,"connection","namespaces",t];return{namespaces:_.useQuery({queryKey:r,queryFn:async()=>g.GetConnectionNamespaces(n,t)})}};function Re(e){const t=Object.values(e.states),n=t.length;let r=0,s=0,i=0,o=0;for(const u of t)u===w.WatchState.WatchStateSynced&&r++,(u===w.WatchState.WatchStateError||u===w.WatchState.WatchStateFailed)&&s++,u===w.WatchState.WatchStateForbidden&&i++,u===w.WatchState.WatchStateSkipped&&o++;const a=n-o,c=t.filter(u=>u===w.WatchState.WatchStateSynced||u===w.WatchState.WatchStateError||u===w.WatchState.WatchStateStopped||u===w.WatchState.WatchStateFailed||u===w.WatchState.WatchStateForbidden).length,d=a>0?c/a:0;return{pluginID:e.pluginID,connectionID:e.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:d}}function ie(e){return e.watchedTotal>0&&e.doneCount>=e.watchedTotal}function ft(e){return e.some(t=>!ie(t))}function pt(e){const t=e.reduce((r,s)=>r+s.watchedTotal,0);return t===0?0:e.reduce((r,s)=>r+s.doneCount,0)/t}function ke(e){return`${e.pluginId}/${e.connection}`}function yt(e,t){const n=ke(t);e.has(n)||e.set(n,{states:{},pluginID:t.pluginId,connectionID:t.connection});const r=e.get(n);return r.states[t.resourceKey]=t.state,r}function nn(){const[e,t]=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 m=x.On("plugin/crash_recovery_failed",O=>{const b=O.data,E=b==null?void 0:b.pluginID;E&&c(P=>{const D=new Map(P);return D.set(E,b.error??"Crash recovery failed"),D})}),F=x.On("plugin/recovered",O=>{const b=O.data,E=b==null?void 0:b.pluginID;E&&c(P=>{if(!P.has(E))return P;const D=new Map(P);return D.delete(E),D})});return()=>{m(),F()}},[]),l.useEffect(()=>{g.GetAllConnectionStates().then(m=>{if(!m)return;const F={},O=new Set,b=new Map;for(const[E,P]of Object.entries(m))if(P){F[E]=P.map(D=>D.connection);for(const D of P){if(!D.started)continue;const $=`${E}/${D.connection.id}`;O.add($);const M={pluginID:E,connectionID:D.connection.id,states:{}};if(D.resources)for(const[_e,Nt]of Object.entries(D.resources))M.states[_e]=Nt;o.current.set($,M),b.set($,Re(M))}}r(F),t(O),i(b)}).catch(()=>{})},[]),l.useEffect(()=>x.On("connection/status",F=>{const O=F.data,b=`${O.pluginID}/${O.connectionID}`;O.status==="DISCONNECTED"?(t(E=>{const P=new Set(E);return P.delete(b),P}),i(E=>{const P=new Map(E);return P.delete(b),P}),o.current.delete(b)):t(E=>{const P=new Set(E);return P.add(b),P}),g.ListAllConnections().then(E=>{if(!E)return;const P={};for(const[D,$]of Object.entries(E))$!=null&&(P[D]=$);r(P)}).catch(()=>{})}),[]);const d=l.useCallback(m=>{const F=m.data,O=ke(F);t(P=>{if(P.has(O))return P;const D=new Set(P);return D.add(O),D});const b=yt(o.current,F),E=Re(b);i(P=>{const D=new Map(P);return D.set(O,E),D})},[]);l.useEffect(()=>x.On("watch/STATE",d),[d]);const u=l.useCallback(async(m,F)=>{await g.StopConnection(m,F)},[]),h=l.useCallback(async(m,F)=>{await g.StartConnectionWatch(m,F)},[]),p=l.useCallback(async m=>{const F=a.get(m);c(O=>{if(!O.has(m))return O;const b=new Map(O);return b.delete(m),b});try{await g.RetryFailedPlugin(m)}catch(O){throw c(b=>{const E=new Map(b);return E.set(m,F??"Reload failed"),E}),O}},[a]),f=[];for(const m of e){const[F,O]=m.split("/",2),E=(n[F]??[]).find(_e=>_e.id===O),P=s.get(m),D=P!=null&&!ie(P),$=P!=null&&P.errorCount>0,M=a.get(F);f.push({pluginID:F,connectionID:O,name:(E==null?void 0:E.name)??O,avatar:(E==null?void 0:E.avatar)??"",isStarted:!0,sync:P,isSyncing:D,hasErrors:$||M!=null,pluginFailed:M!=null,pluginError:M})}const y=new Map;for(const m of f){const F=y.get(m.pluginID)??[];F.push(m),y.set(m.pluginID,F)}const C=Array.from(s.values()),R=f.filter(m=>m.isSyncing),S=f.filter(m=>m.hasErrors),v=f.filter(m=>m.pluginFailed);return{entries:f,grouped:y,connectedCount:f.length,syncingCount:R.length,errorCount:S.length,failedCount:v.length,hasSyncing:ft(C),aggregateProgress:pt(C),disconnect:u,retryWatch:h,retryPlugin:p}}function rn(e,t,n){const r=T(e),s=_.useQueryClient(),i=[r,"data",t],o=_.useQuery({queryKey:i,queryFn:async()=>{const c=await g.Get(r,t);return c??n}}),a=_.useMutation({mutationFn:async c=>{await g.Set(r,t,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 sn=()=>{const e=l.useContext(st);if(!e)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return e},We=()=>{const e=l.useContext(rt);if(e===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return e},on=({pluginID:e})=>{const t=T(e),{showSnackbar:n}=q(),{createTab:r,updateTab:s}=We();return{createSession:_.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:t,connectionID:o,opts:{...d}}});const h=w.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const p=await g.CreateSession(t,o,h);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:t,connectionID:o,opts:{...d}}})}catch(p){const f=j(p);s({id:u},{properties:{status:"error",error:f.detail,pluginID:t,connectionID:o,opts:{...d}}}),z(n,p,"Failed to start session")}}}).mutateAsync}},an=({pluginID:e})=>{const t=T(e),{showSnackbar:n}=q(),{createTab:r}=We(),s=_.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:d,icon:u,label:h,target:p,follow:f=!0,tailLines:y=1e3,params:C})=>{const R=w.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:d,options:w.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:y,since_seconds:0,limit_bytes:0,include_source_events:!0,params:C??{}})}),S=await g.CreateSession$1(t,o,R);if(!S)throw new Error("Failed to create log session: null response");return r({id:S.id,title:h??`Logs ${S.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),S},onError:N(n,"Failed to start log session")}),i=_.useMutation({mutationFn:async o=>{await g.CloseSession(o)},onError:N(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},cn=()=>_.useQuery({queryKey:["metric","providers"],queryFn:g.GetProviders,staleTime:3e4}),ht=e=>_.useQuery({queryKey:["metric","providers",e],queryFn:()=>g.GetProvidersForResource(e),enabled:!!e,staleTime:3e4}),un=e=>{var R,S;const{connectionID:t,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:d=0,enabled:u=!0}=e,{data:h,isLoading:p}=ht(n),f=h??[],y=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,C=_.useQuery({queryKey:["metric","query",t,n,r,s,o,a,(R=c==null?void 0:c.start)==null?void 0:R.getTime(),(S=c==null?void 0:c.end)==null?void 0:S.getTime()],queryFn:async()=>{const v=await g.QueryAll(t,n,r,s,i,o,a,(c==null?void 0:c.start)??new Date(0),(c==null?void 0:c.end)??new Date(0),y),m={};for(const[F,O]of Object.entries(v))O!=null&&(m[F]=O);return m},enabled:u&&!!t&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:_.keepPreviousData});return{data:C.data??void 0,providers:f,isLoading:p||C.isLoading,error:C.error,refetch:C.refetch}},ln=e=>{const{pluginID:t,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:d=!0}=e,u=T(t),[h,p]=l.useState(null),[f,y]=l.useState(null),[C,R]=l.useState(!1),[S,v]=l.useState(null),m=l.useRef(null),F=l.useCallback(async()=>{if(!(!d||!u||!n||!r||!s))try{const b=await g.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});y(b),R(!0),v(null);const E=x.On(`core/metrics/data/${b}`,D=>{const $=D.data;try{const M=JSON.parse($);M.results&&p(M.results)}catch(M){console.error("Failed to parse metric stream data:",M)}}),P=x.On(`core/metrics/error/${b}`,D=>{const $=D.data;try{const M=JSON.parse($);v(M.error||"Unknown error")}catch{v("Failed to parse metric stream error")}});m.current=()=>{E(),P()}}catch(b){v(b instanceof Error?b.message:String(b))}},[u,n,r,s,i,a,c,d]),O=l.useCallback(async()=>{if(f)try{await g.Unsubscribe(f)}catch(b){console.error("Failed to unsubscribe:",b)}m.current&&(m.current(),m.current=null),y(null),R(!1)},[f]);return l.useEffect(()=>()=>{f&&g.Unsubscribe(f).catch(console.error),m.current&&m.current()},[f]),{data:h,subscriptionID:f,isStreaming:C,error:S,start:F,stop:O}},G=["networker","portforward","all-sessions"];function dn(){const{showSnackbar:e}=q(),t=_.useQueryClient(),n=_.useQuery({queryKey:[...G],queryFn:async()=>g.ListAllPortForwardSessions().catch(i=>{if(j(i).detail.includes("not found"))return[];throw i}),retry:!1});l.useEffect(()=>{const i=x.On("core/networker/portforward/created",()=>{t.invalidateQueries({queryKey:[...G]})}),o=x.On("core/networker/portforward/closed",()=>{t.invalidateQueries({queryKey:[...G]})});return()=>{i(),o()}},[t]);const r=n.data??[],s=_.useMutation({mutationFn:async i=>g.ClosePortForwardSession(i),onError:N(e,"Failed to close port forwarding session"),onSuccess:async()=>{await t.invalidateQueries({queryKey:[...G]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>x.OpenURL(`http://localhost:${i}`)}}function fn({pluginID:e,connectionID:t,resourceID:n}){const r=T(e),s=["networker","portforward","sessions",r,t,n],{showSnackbar:i}=q(),o=_.useQueryClient(),a=_.useQuery({queryKey:s,queryFn:async()=>g.FindPortForwardSessions(r,t,w.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:t})).catch(u=>{const h=j(u);return h.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:h.detail}),[])}),retry:!1}),c=_.useMutation({mutationFn:async({opts:u})=>{const h=w.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:t,plugin_id:r,resource_id:u.resourceId,resource_key:u.resourceKey},labels:u.labels??{},params:u.parameters??{}}),p=await g.StartResourcePortForwardingSession(r,t,h);if(!p)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&x.OpenURL(`http://localhost:${p.local_port}`),p},onError:N(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...G]})])}}),d=_.useMutation({mutationFn:async({opts:u})=>g.ClosePortForwardSession(u.sessionID),onError:N(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...G]})])}});return{sessions:a,forward:c.mutateAsync,close:d.mutateAsync}}const pn=()=>{const e=l.useContext(ot);if(!e)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return e},yn=({pluginID:e,connectionID:t,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=T(e),o=_.useQueryClient(),{showSnackbar:a}=q(),c=["RESOURCE",i,t,n,r,s],{mutateAsync:d}=_.useMutation({mutationFn:async p=>g.Update(i,t,n,w.UpdateInput.createFrom({input:p.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to update resource ${r}`)}),{mutateAsync:u}=_.useMutation({mutationFn:async(p={})=>g.Delete(i,t,n,w.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:p.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:N(a,`Failed to delete resource ${r}`)});return{resource:_.useQuery({queryKey:c,queryFn:async()=>g.Get$1(i,t,n,w.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:u}},hn=e=>{const t=["component",e.plugin,e.resource,e.area];return{component:_.useQuery({queryKey:t,queryFn:async()=>g.GetResourceAreaComponent(e)})}},gn=({pluginID:e,connectionID:t})=>{const n=T(e),r=[n,"resource_groups","list"];return{groups:_.useQuery({queryKey:r,queryFn:async()=>g.GetResourceGroups(n,t),retry:!1})}},mn=({pluginID:e,connectionID:t,searches:n})=>{const r=T(e),s=o=>[r,t,o.key,o.namespaces,"list"];return _.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>g.List(r,t,o.key,w.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}))})},_n=({pluginID:e,resourceKey:t})=>{const n=T(e),r=[n,"resources",t];return{resourceType:_.useQuery({queryKey:r,queryFn:async()=>g.GetResourceType(n,t),retry:!1})}},Sn=({pluginID:e,connectionID:t})=>{const n=T(e),r=[n,"resources","list",t];return{types:_.useQuery({queryKey:r,queryFn:async()=>g.GetResourceTypes(n,t),retry:!1})}};var gt=Symbol.for("immer-nothing"),ze=Symbol.for("immer-draftable"),W=Symbol.for("immer-state"),wn=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function k(e,...t){if(process.env.NODE_ENV!=="production"){const n=wn[e],r=typeof n=="function"?n.apply(null,t):n;throw new Error(`[Immer] ${r}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var V=Object.getPrototypeOf;function X(e){return!!e&&!!e[W]}function K(e){var t;return e?mt(e)||Array.isArray(e)||!!e[ze]||!!((t=e.constructor)!=null&&t[ze])||pe(e)||ye(e):!1}var Cn=Object.prototype.constructor.toString();function mt(e){if(!e||typeof e!="object")return!1;const t=V(e);if(t===null)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Cn}function ae(e,t){fe(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function fe(e){const t=e[W];return t?t.type_:Array.isArray(e)?1:pe(e)?2:ye(e)?3:0}function Fe(e,t){return fe(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function _t(e,t,n){const r=fe(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function En(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function pe(e){return e instanceof Map}function ye(e){return e instanceof Set}function Q(e){return e.copy_||e.base_}function Oe(e,t){if(pe(e))return new Map(e);if(ye(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=mt(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[W];let s=Reflect.ownKeys(r);for(let i=0;i<s.length;i++){const o=s[i],a=r[o];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[o]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[o]})}return Object.create(V(e),r)}else{const r=V(e);if(r!==null&&n)return{...e};const s=Object.create(r);return Object.assign(s,e)}}function Le(e,t=!1){return he(e)||X(e)||!K(e)||(fe(e)>1&&(e.set=e.add=e.clear=e.delete=bn),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>Le(r,!0))),e}function bn(){k(2)}function he(e){return Object.isFrozen(e)}var vn={};function B(e){const t=vn[e];return t||k(0,e),t}var te;function St(){return te}function Pn(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ke(e,t){t&&(B("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function De(e){Ie(e),e.drafts_.forEach(Rn),e.drafts_=null}function Ie(e){e===te&&(te=e.parent_)}function Be(e){return te=Pn(te,e)}function Rn(e){const t=e[W];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function He(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[W].modified_&&(De(t),k(4)),K(e)&&(e=ce(t,e),t.parent_||ue(t,e)),t.patches_&&B("Patches").generateReplacementPatches_(n[W].base_,e,t.patches_,t.inversePatches_)):e=ce(t,n,[]),De(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==gt?e:void 0}function ce(e,t,n){if(he(t))return t;const r=t[W];if(!r)return ae(t,(s,i)=>Ye(e,r,t,s,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return ue(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const s=r.copy_;let i=s,o=!1;r.type_===3&&(i=new Set(s),s.clear(),o=!0),ae(i,(a,c)=>Ye(e,r,s,a,c,n,o)),ue(e,s,!1),n&&e.patches_&&B("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Ye(e,t,n,r,s,i,o){if(process.env.NODE_ENV!=="production"&&s===n&&k(5),X(s)){const a=i&&t&&t.type_!==3&&!Fe(t.assigned_,r)?i.concat(r):void 0,c=ce(e,s,a);if(_t(n,r,c),X(c))e.canAutoFreeze_=!1;else return}else o&&n.add(s);if(K(s)&&!he(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ce(e,s),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&ue(e,s)}}function ue(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Le(t,n)}function Fn(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:St(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=r,i=$e;n&&(s=[r],i=ne);const{revoke:o,proxy:a}=Proxy.revocable(s,i);return r.draft_=a,r.revoke_=o,a}var $e={get(e,t){if(t===W)return e;const n=Q(e);if(!Fe(n,t))return On(e,n,t);const r=n[t];return e.finalized_||!K(r)?r:r===Ce(e.base_,t)?(Ee(e),e.copy_[t]=Te(r,e)):r},has(e,t){return t in Q(e)},ownKeys(e){return Reflect.ownKeys(Q(e))},set(e,t,n){const r=wt(Q(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const s=Ce(Q(e),t),i=s==null?void 0:s[W];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(En(n,s)&&(n!==void 0||Fe(e.base_,t)))return!0;Ee(e),xe(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Ce(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Ee(e),xe(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Q(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){k(11)},getPrototypeOf(e){return V(e.base_)},setPrototypeOf(){k(12)}},ne={};ae($e,(e,t)=>{ne[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ne.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&k(13),ne.set.call(this,e,t,void 0)};ne.set=function(e,t,n){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&k(14),$e.set.call(this,e[0],t,n,e[0])};function Ce(e,t){const n=e[W];return(n?Q(n):e)[t]}function On(e,t,n){var s;const r=wt(t,n);return r?"value"in r?r.value:(s=r.get)==null?void 0:s.call(e.draft_):void 0}function wt(e,t){if(!(t in e))return;let n=V(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=V(n)}}function xe(e){e.modified_||(e.modified_=!0,e.parent_&&xe(e.parent_))}function Ee(e){e.copy_||(e.copy_=Oe(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Dn=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const o=this;return function(c=i,...d){return o.produce(c,u=>n.call(this,u,...d))}}typeof n!="function"&&k(6),r!==void 0&&typeof r!="function"&&k(7);let s;if(K(t)){const i=Be(this),o=Te(t,void 0);let a=!0;try{s=n(o),a=!1}finally{a?De(i):Ie(i)}return Ke(i,r),He(s,i)}else if(!t||typeof t!="object"){if(s=n(t),s===void 0&&(s=t),s===gt&&(s=void 0),this.autoFreeze_&&Le(s,!0),r){const i=[],o=[];B("Patches").generateReplacementPatches_(t,s,i,o),r(i,o)}return s}else k(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(o,...a)=>this.produceWithPatches(o,c=>t(c,...a));let r,s;return[this.produce(t,n,(o,a)=>{r=o,s=a}),r,s]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||k(8),X(e)&&(e=In(e));const t=Be(this),n=Te(e,void 0);return n[W].isManual_=!0,Ie(t),n}finishDraft(e,t){const n=e&&e[W];(!n||!n.isManual_)&&k(9);const{scope_:r}=n;return Ke(r,t),He(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const s=t[n];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}n>-1&&(t=t.slice(n+1));const r=B("Patches").applyPatches_;return X(e)?r(e,t):this.produce(e,s=>r(s,t))}};function Te(e,t){const n=pe(e)?B("MapSet").proxyMap_(e,t):ye(e)?B("MapSet").proxySet_(e,t):Fn(e,t);return(t?t.scope_:St()).drafts_.push(n),n}function In(e){return X(e)||k(10,e),Ct(e)}function Ct(e){if(!K(e)||he(e))return e;const t=e[W];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Oe(e,t.scope_.immer_.useStrictShallowCopy_)}else n=Oe(e,!0);return ae(n,(r,s)=>{_t(n,r,Ct(s))}),t&&(t.finalized_=!1),n}var L=new Dn,Et=L.produce;L.produceWithPatches.bind(L);L.setAutoFreeze.bind(L);L.setUseStrictShallowCopy.bind(L);L.applyPatches.bind(L);L.createDraft.bind(L);L.finishDraft.bind(L);var oe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tn="Expected a function",bt="__lodash_hash_undefined__",An="[object Function]",Nn="[object GeneratorFunction]",Mn="[object Symbol]",kn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wn=/^\w*$/,Ln=/^\./,$n=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Un=/[\\^$.*+?()[\]{}|]/g,qn=/\\(\\)?/g,jn=/^\[object .+?Constructor\]$/,Qn=typeof oe=="object"&&oe&&oe.Object===Object&&oe,Gn=typeof self=="object"&&self&&self.Object===Object&&self,Ue=Qn||Gn||Function("return this")();function zn(e,t){return e==null?void 0:e[t]}function Kn(e){var t=!1;if(e!=null&&typeof e.toString!="function")try{t=!!(e+"")}catch{}return t}var Bn=Array.prototype,Hn=Function.prototype,vt=Object.prototype,be=Ue["__core-js_shared__"],Je=function(){var e=/[^.]+$/.exec(be&&be.keys&&be.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Pt=Hn.toString,qe=vt.hasOwnProperty,Rt=vt.toString,Yn=RegExp("^"+Pt.call(qe).replace(Un,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ve=Ue.Symbol,Jn=Bn.splice,Vn=Ft(Ue,"Map"),re=Ft(Object,"create"),Xe=Ve?Ve.prototype:void 0,Ze=Xe?Xe.toString:void 0;function H(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Xn(){this.__data__=re?re(null):{}}function Zn(e){return this.has(e)&&delete this.__data__[e]}function er(e){var t=this.__data__;if(re){var n=t[e];return n===bt?void 0:n}return qe.call(t,e)?t[e]:void 0}function tr(e){var t=this.__data__;return re?t[e]!==void 0:qe.call(t,e)}function nr(e,t){var n=this.__data__;return n[e]=re&&t===void 0?bt:t,this}H.prototype.clear=Xn;H.prototype.delete=Zn;H.prototype.get=er;H.prototype.has=tr;H.prototype.set=nr;function Z(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function rr(){this.__data__=[]}function sr(e){var t=this.__data__,n=ge(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Jn.call(t,n,1),!0}function or(e){var t=this.__data__,n=ge(t,e);return n<0?void 0:t[n][1]}function ir(e){return ge(this.__data__,e)>-1}function ar(e,t){var n=this.__data__,r=ge(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}Z.prototype.clear=rr;Z.prototype.delete=sr;Z.prototype.get=or;Z.prototype.has=ir;Z.prototype.set=ar;function Y(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function cr(){this.__data__={hash:new H,map:new(Vn||Z),string:new H}}function ur(e){return me(this,e).delete(e)}function lr(e){return me(this,e).get(e)}function dr(e){return me(this,e).has(e)}function fr(e,t){return me(this,e).set(e,t),this}Y.prototype.clear=cr;Y.prototype.delete=ur;Y.prototype.get=lr;Y.prototype.has=dr;Y.prototype.set=fr;function ge(e,t){for(var n=e.length;n--;)if(br(e[n][0],t))return n;return-1}function pr(e,t){t=mr(t,e)?[t]:gr(t);for(var n=0,r=t.length;e!=null&&n<r;)e=e[Cr(t[n++])];return n&&n==r?e:void 0}function yr(e){if(!Dt(e)||Sr(e))return!1;var t=vr(e)||Kn(e)?Yn:jn;return t.test(Er(e))}function hr(e){if(typeof e=="string")return e;if(Qe(e))return Ze?Ze.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}function gr(e){return Ot(e)?e:wr(e)}function me(e,t){var n=e.__data__;return _r(t)?n[typeof t=="string"?"string":"hash"]:n.map}function Ft(e,t){var n=zn(e,t);return yr(n)?n:void 0}function mr(e,t){if(Ot(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||Qe(e)?!0:Wn.test(e)||!kn.test(e)||t!=null&&e in Object(t)}function _r(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Sr(e){return!!Je&&Je in e}var wr=je(function(e){e=Rr(e);var t=[];return Ln.test(e)&&t.push(""),e.replace($n,function(n,r,s,i){t.push(s?i.replace(qn,"$1"):r||n)}),t});function Cr(e){if(typeof e=="string"||Qe(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}function Er(e){if(e!=null){try{return Pt.call(e)}catch{}try{return e+""}catch{}}return""}function je(e,t){if(typeof e!="function"||t&&typeof t!="function")throw new TypeError(Tn);var n=function(){var r=arguments,s=t?t.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=e.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(je.Cache||Y),n}je.Cache=Y;function br(e,t){return e===t||e!==e&&t!==t}var Ot=Array.isArray;function vr(e){var t=Dt(e)?Rt.call(e):"";return t==An||t==Nn}function Dt(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Pr(e){return!!e&&typeof e=="object"}function Qe(e){return typeof e=="symbol"||Pr(e)&&Rt.call(e)==Mn}function Rr(e){return e==null?"":hr(e)}function Fr(e,t,n){var r=e==null?void 0:pr(e,t);return r===void 0?n:r}var Or=Fr;const J=xn(Or);function It(e,t,n){return Et(e??{result:[],success:!0,totalCount:0},s=>{for(const i of t)switch(i.type){case"ADD":{s.result.findIndex(a=>J(i.payload.data,n)===J(a,n))===-1&&s.result.push(i.payload.data);break}case"UPDATE":{const o=s.result.findIndex(a=>J(i.payload.data,n)===J(a,n));o!==-1&&(s.result[o]=i.payload.data);break}case"DELETE":{const o=s.result.findIndex(a=>J(i.payload.data,n)===J(a,n));o!==-1&&s.result.splice(o,1);break}}})}function xt(e,t,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 h=l.useCallback(()=>{const f=a.current;if(a.current=[],c.current=null,d.current=null,!(f.length===0||!r)){e.setQueryData(t,y=>It(y,f,r));for(const y of f)(y.type==="ADD"||y.type==="UPDATE")&&e.setQueryData(n(y.payload.id,y.payload.namespace),{result:y.payload.data})}},[e,t,n,r]),p=l.useCallback(f=>{a.current.push(f),!(c.current!==null||d.current!==null)&&(u.current===1?c.current=setTimeout(h,o):d.current=requestAnimationFrame(h))},[h,o]);return l.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),p}const Dr=({pluginID:e,connectionID:t,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=T(e),o=_.useQueryClient(),{showSnackbar:a}=q(),c=l.useMemo(()=>s??[],[s]),d=l.useMemo(()=>[i,t,n,c,"list"],[i,t,n,c]),u=l.useCallback((R,S)=>[i,t,n,S,R],[i,t,n]),{mutateAsync:h}=_.useMutation({mutationFn:async R=>g.Create(i,t,n,w.CreateInput.createFrom({input:R.input,namespace:R.namespace??(c.length===1?c[0]:"")})),onSuccess:async R=>{var F;const S=R==null?void 0:R.result;let v="";(F=S==null?void 0:S.metadata)!=null&&F.name?v=S.metadata.name:S!=null&&S.id?v=S.id:S!=null&&S.name?v=S.name:S!=null&&S.ID?v=S.ID:S!=null&&S.Name&&(v=S.Name);const m=v?`Resource ${v} created`:"Resource created";a(m,"success"),await o.invalidateQueries({queryKey:d})},onError:N(a,"Failed to create resource")}),p=_.useQuery({queryKey:d,queryFn:async()=>g.List(i,t,n,w.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(R,S)=>R,retry:!1}),[f,y]=l.useState(w.WatchState.WatchStateIdle);l.useEffect(()=>x.On(`${i}/${t}/watch/STATE`,S=>{const v=S.data;v.resourceKey===n&&y(v.state)}),[i,t,n]);const C=xt(o,d,u,r,f);return l.useEffect(()=>{if(!r)return;g.SubscribeResource(i,t,n);const R=x.On(`${i}/${t}/${n}/ADD`,m=>C({type:"ADD",payload:m.data})),S=x.On(`${i}/${t}/${n}/UPDATE`,m=>C({type:"UPDATE",payload:m.data})),v=x.On(`${i}/${t}/${n}/DELETE`,m=>C({type:"DELETE",payload:m.data}));return()=>{R(),S(),v(),g.UnsubscribeResource(i,t,n)}},[i,t,n,C]),{resources:p,create:h,watchState:f,isSyncing:f===w.WatchState.WatchStateSyncing,isSynced:f===w.WatchState.WatchStateSynced,watchError:f===w.WatchState.WatchStateError}},Ir=({pluginID:e})=>{const t=T(e),{showSnackbar:n}=q(),r=_.useMutation({mutationFn:async({opts:o,input:a})=>g.Create(t,o.connectionID,o.resourceKey,w.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){z(n,o,`Failed to create resource ${a.resourceID}`)}}),s=_.useMutation({mutationFn:async({opts:o,input:a})=>g.Update(t,o.connectionID,o.resourceKey,w.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}){z(n,o,`Failed to update resource ${a.resourceID}`)}}),i=_.useMutation({mutationFn:async({opts:o,input:a})=>g.Delete(t,o.connectionID,o.resourceKey,w.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}){z(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},xr=({pluginID:e,connectionID:t,resourceKey:n,enabled:r=!0})=>{const s=T(e),i=_.useQuery({queryKey:["RESOURCE_ACTIONS",s,t,n],queryFn:()=>g.GetActions(s,t,n),enabled:r&&!!s&&!!t&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},Tr=({pluginID:e,connectionID:t,resourceKey:n})=>{const r=T(e),s=_.useQueryClient(),{showSnackbar:i}=q(),o=_.useMutation({mutationFn:async({actionID:a,id:c="",namespace:d="",params:u={}})=>g.ExecuteAction(r,t,n,a,w.ActionInput.createFrom({id:c,namespace:d,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,t,n]})},onError:(a,c)=>{z(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Ar=({pluginID:e,connectionID:t,enabled:n=!0})=>{const r=T(e),s=_.useQuery({queryKey:["EDITOR_SCHEMAS",r,t],queryFn:()=>g.GetEditorSchemas(r,t),enabled:n&&!!r&&!!t,staleTime:10*60*1e3,retry:1});return{schemas:s.data??[],isLoading:s.isLoading,error:s.error,refetch:s.refetch}},Nr=({pluginID:e,connectionID:t,enabled:n=!0})=>{const r=T(e),s=_.useQueryClient(),i=[r,t,"watch-state"],o=l.useRef([]),a=l.useRef(!1),c=l.useCallback(p=>{s.setQueryData(i,f=>f&&Et(f,y=>{y.resources[p.resourceKey]=p.state,y.resourceCounts[p.resourceKey]=p.resourceCount;let C=0,R=0;for(const S of Object.values(y.resources))S===w.WatchState.WatchStateSynced&&C++,(S===w.WatchState.WatchStateError||S===w.WatchState.WatchStateFailed)&&R++;y.syncedCount=C,y.errorCount=R}))},[s,r,t]),d=_.useQuery({queryKey:i,queryFn:async()=>{const p=await g.GetWatchState(r,t);if(!p)throw new Error("Failed to get watch state: null response");const f={};let y=0,C=0;for(const[S,v]of Object.entries(p.resources??{}))v!=null&&(f[S]=v,v===w.WatchState.WatchStateSynced&&y++,v===w.WatchState.WatchStateError&&C++);const R={};for(const[S,v]of Object.entries(p.resourceCounts??{}))v!=null&&(R[S]=v);return{connection:p.connectionId,resources:f,resourceCounts:R,totalResources:Object.keys(f).length,syncedCount:y,errorCount:C}},enabled:n&&!!r&&!!t,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let y=0;for(const C of Object.values(f.resources))(C===w.WatchState.WatchStateSynced||C===w.WatchState.WatchStateError||C===w.WatchState.WatchStateStopped||C===w.WatchState.WatchStateFailed||C===w.WatchState.WatchStateForbidden||C===w.WatchState.WatchStateSkipped)&&y++;return y>=f.totalResources?!1:3e3}});l.useEffect(()=>{if(!d.data||a.current)return;a.current=!0;const p=o.current;o.current=[];for(const f of p)c(f)},[d.data,c]),l.useEffect(()=>{if(!n||!r||!t)return;a.current=!1,o.current=[];const p=x.On(`${r}/${t}/watch/STATE`,f=>{const y=f.data;a.current?c(y):o.current.push(y)});return()=>{p(),a.current=!1,o.current=[]}},[r,t,n,c]);const u=d.data;let h=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===w.WatchState.WatchStateSynced||p===w.WatchState.WatchStateError||p===w.WatchState.WatchStateStopped||p===w.WatchState.WatchStateFailed||p===w.WatchState.WatchStateForbidden||p===w.WatchState.WatchStateSkipped)&&h++;return{summary:d,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&h===u.totalResources:!1,syncProgress:u&&u.totalResources>0?h/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Mr=()=>{const[e,t]=l.useState(new Map),n=l.useRef(new Map),r=l.useRef(new Map),s=l.useCallback(d=>{const u=d.data,h=ke(u),p=yt(n.current,u),f=Re(p);if(t(y=>{const C=new Map(y);return C.set(h,f),C}),r.current.has(h)&&(clearTimeout(r.current.get(h)),r.current.delete(h)),ie(f)){const y=setTimeout(()=>{t(C=>{const R=new Map(C);return R.delete(h),R}),n.current.delete(h),r.current.delete(h)},5e3);r.current.set(h,y)}},[]);l.useEffect(()=>{const d=x.On("watch/STATE",s);return()=>{d();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(e.values()),o=ft(i),a=i.find(d=>!ie(d))??i[0]??null,c=pt(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},Tt=()=>{const e=l.useContext(Me);if(!e)throw new Error("useOperations must be used within an OperationsProvider");return e},kr=({pluginID:e,connectionID:t,resourceKey:n})=>{const r=T(e),{showSnackbar:s}=q(),{addOperation:i,updateOperation:o}=Tt(),a=l.useRef([]);return l.useEffect(()=>()=>{a.current.forEach(d=>d())},[]),{startStreamAction:l.useCallback(async({actionID:d,id:u,namespace:h,label:p,params:f={}})=>{try{const y=await g.StreamAction(r,t,n,d,w.ActionInput.createFrom({id:u,namespace:h,params:f}));i({id:y,label:p,resourceKey:n,resourceName:u,namespace:h,connectionID:t,status:"running",startedAt:Date.now()});const C=`action/stream/${y}`,R=x.On(C,S=>{var m,F,O,b;const v=S.data;switch(v.type){case"progress":{const E=v.data??{};o(y,{message:E.message,progress:E.ready!==void 0&&E.desired!==void 0?{ready:E.ready,desired:E.desired}:void 0});break}case"complete":o(y,{status:"completed",message:((m=v.data)==null?void 0:m.message)??"Completed",completedAt:Date.now()}),s(((F=v.data)==null?void 0:F.message)??p+" completed","success"),x.Off(C);break;case"error":o(y,{status:"error",message:((O=v.data)==null?void 0:O.message)??"Failed",completedAt:Date.now()}),s(((b=v.data)==null?void 0:b.message)??p+" failed","error"),x.Off(C);break}});return a.current.push(()=>{R(),x.Off(C)}),y}catch(y){throw z(s,y,`Failed to start "${d}"`),y}},[r,t,n,i,o,s])}},Wr=()=>{const e=l.useContext(Ne);if(!e)throw new Error("useSettings must be used within a SettingsProvider");return e},Lr=({to:e,withinContext:t,...n})=>{const{pluginId:r}=de();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${e.startsWith("/")?"":"/"}${e}`;return l.useMemo(()=>I.jsx(ee.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function $r(){const e=ee.useNavigate(),t=ee.useLocation(),{pluginId:n}=de();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=t.pathname.startsWith(r)?t.pathname.slice(r.length)||"/":t.pathname,i=l.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?e(`${r}${o}`,c):e(o,c)},[e,r]);return l.useMemo(()=>({location:t,navigate:i,pluginPath:s}),[t,i,s])}class Ur{}class qr{constructor(){A(this,"_extensions");A(this,"root");A(this,"pages");A(this,"_routes")}get extensions(){return this._extensions||[]}get Routes(){var t;if(!this._routes&&this.root)return[{path:"",index:!0,Component:this.root}];if(!((t=this._routes)!=null&&t.length))throw new Error("cannot use plugin without a root page or router");return this._routes}get Window(){if(!this._routes&&this.root)return I.jsx(this.root,{});const t=ee.createMemoryRouter(this._routes||[]);return I.jsx(ee.RouterProvider,{router:t})}registerExtensionPoints(t){return this._extensions=t||[],this}setRootPage(t){return this.root=t,this}withPage(t,n){return this.pages||(this.pages={}),this.pages[t]?(console.warn("Cannot register page with the same name. Please use a different name."),this):(this.pages[t]=n,this)}withRoutes(t){return this._routes=t,this}}var At=(e=>(e.MISSING_MANIFEST="MISSING_MANIFEST",e.MISSING_PLUGIN="MISSING_PLUGIN",e.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",e))(At||{});const jr=e=>{const t=e.split("::");return t.length===1?{group:"core",version:"",kind:t[0]}:{group:t[0]||"core",version:t[1]||"",kind:t[2]||t[0]}},Qr=e=>!e||e==="core"?"Core":e.charAt(0).toUpperCase()+e.slice(1);exports.WatchState=w.WatchState;exports.ALL_SESSIONS_KEY=G;exports.BottomDrawerContext=rt;exports.ConfirmationModalContext=ot;exports.ErrorTypes=U;exports.ExtensionPointRegistry=Jt;exports.ExtensionPointStore=ut;exports.ExtensionProvider=Yt;exports.Link=Lr;exports.OperationsContext=Me;exports.OperationsProvider=Qt;exports.PluginContext=le;exports.PluginContextProvider=$t;exports.PluginErrorCode=At;exports.PluginWindow=qr;exports.PluginWindowRootProps=Ur;exports.RightDrawerContext=st;exports.SettingsContext=Ne;exports.SettingsProvider=qt;exports.SnackbarProvider=Xt;exports.actionToSnackbar=et;exports.applyBatch=It;exports.connectionListQueryKey=dt;exports.createErrorHandler=N;exports.defaultState=nt;exports.formatGroup=Qr;exports.isCancelledError=Ae;exports.parseAppError=j;exports.parseResourceKey=jr;exports.showAppError=z;exports.useActiveSyncs=Mr;exports.useBottomDrawer=We;exports.useConfirmationModal=pn;exports.useConnection=Zt;exports.useConnectionNamespaces=tn;exports.useConnectionStatus=nn;exports.useConnections=en;exports.useEditorSchemas=Ar;exports.useEventBatcher=xt;exports.useExec=on;exports.useExecuteAction=Tr;exports.useExtensionPoint=Ht;exports.useExtensionRegistry=ct;exports.useLogs=an;exports.useMetricProviders=cn;exports.useMetricProvidersForResource=ht;exports.useMetricStream=ln;exports.useOperations=Tt;exports.usePluginContext=de;exports.usePluginData=rn;exports.usePluginRouter=$r;exports.usePluginSettings=Ut;exports.usePortForwardSessions=dn;exports.useResolvedPluginId=T;exports.useResource=yn;exports.useResourceActions=xr;exports.useResourceAreaComponent=hn;exports.useResourceGroups=gn;exports.useResourceMetrics=un;exports.useResourceMutations=Ir;exports.useResourcePortForwarder=fn;exports.useResourceSearch=mn;exports.useResourceType=_n;exports.useResourceTypes=Sn;exports.useResources=Dr;exports.useRightDrawer=sn;exports.useSettings=Wr;exports.useSnackbar=q;exports.useStreamAction=kr;exports.useWatchState=Nr;
1
+ "use strict";var Je=Object.defineProperty;var Ze=(t,e,n)=>e in t?Je(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var T=(t,e,n)=>Ze(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("react/jsx-runtime"),l=require("react"),K=require("react-router-dom"),g=require("./servicewrapper-BtYdL57C.cjs"),C=require("./models-2dDjO0f0.cjs"),S=require("@tanstack/react-query"),Xe=require("@omniviewdev/ui/feedback");require("./index-DCsB3HOd.cjs");const D=require("./events-D6Z9I2K4.cjs"),Z=l.createContext(void 0),W={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",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",CONNECTION_NOT_FOUND:"omniview:connection/not-found",CONNECTION_FAILED:"omniview:connection/failed",RESOURCE_CONNECTION_ERROR:"omniview:resource/connection-error",RESOURCE_CERTIFICATE_ERROR:"omniview:resource/certificate-error",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"};function Ve(t){switch(t){case"NOT_FOUND":return{typeUri:W.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:W.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:W.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:W.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:W.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:W.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:W.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:W.INTERNAL,status:500}}}function $(t){if(t==null)return{type:W.INTERNAL,title:"Unknown error",status:500,detail:"An unknown error occurred."};let e;if(typeof t=="string"?e=t:t instanceof Error?e=t.message:e=String(t),e.startsWith("{"))try{const n=JSON.parse(e);if(typeof n.type=="string"&&typeof n.title=="string"&&typeof n.status=="number"&&typeof n.detail=="string")return n;if(typeof n.code=="string"&&typeof n.title=="string"&&typeof n.message=="string"){const{typeUri:r,status:s}=Ve(n.code);return{type:r,title:n.title,status:s,detail:n.message,suggestions:Array.isArray(n.suggestions)?n.suggestions:void 0}}}catch{}return{type:W.INTERNAL,title:"Error",status:500,detail:e}}function ce(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:$(t).type===W.CANCELLED}function we(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 ve(t,e){var s,a;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:(a=t.actions)==null?void 0:a.map(we)}}function q(t,e,n){if(ce(e))return;const r=$(e);t(ve(r,n))}function M(t,e){return n=>{if(ce(n))return;const r=$(n);t(ve(r,r.title!=="Error"?r.title:e))}}function et(t){const{children:e,pluginId:n}=t,[r,s]=l.useState({}),[a,o]=l.useState(new C.PluginMeta),[i,c]=l.useState(!1),[d,u]=l.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:i,metaError:!!d});const h=()=>{n===void 0||n===""||(console.debug(`[PluginContextProvider] fetching settings for "${n}"`),g.PluginValues(n).then(f=>{console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),s(f)}).catch(f=>{const y=$(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,y.detail)}))},p=()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),g.GetPluginMeta(n).then(f=>{console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:f==null?void 0:f.name,version:f==null?void 0:f.version}),o(f),c(!0)}).catch(f=>{const y=$(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,y.detail),u(y.detail),c(!1)})};return l.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),h(),p()},[n]),d?O.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:O.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:[O.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[O.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[O.jsx("circle",{cx:"12",cy:"12",r:"10"}),O.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),O.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),O.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),O.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),O.jsx("button",{onClick:()=>p(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):i?O.jsx(Z.Provider,{value:{pluginId:n,settings:r,meta:a},children:e}):O.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[O.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),O.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function X(){const t=l.useContext(Z);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function tt(){return X().settings}const ue=l.createContext(void 0),nt=({children:t})=>{const[e,n]=l.useState({}),r=()=>{g.Values().then(a=>{console.log("Fetched settings:",a),n(a)}).catch(a=>{console.error("Error fetching settings:",a)})};l.useEffect(()=>{r()},[]);const s=()=>{r()};return O.jsx(ue.Provider,{value:{settings:e,reload:s},children:t})},be={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Re=l.createContext(be),xe=l.createContext(void 0),Pe=l.createContext(void 0),le=l.createContext(void 0),rt=3e4,st=({children:t})=>{const[e,n]=l.useState([]),r=l.useCallback(i=>{n(c=>[i,...c])},[]),s=l.useCallback((i,c)=>{n(d=>d.map(u=>u.id===i?{...u,...c}:u))},[]),a=l.useCallback(i=>{n(c=>c.filter(d=>d.id!==i))},[]);l.useEffect(()=>{const i=[];for(const c of e)if(c.status==="completed"||c.status==="error"){const d=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,rt-d);i.push(setTimeout(()=>a(c.id),u))}return()=>i.forEach(clearTimeout)},[e,a]);const o=l.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:a}),[e,r,s,a]);return O.jsx(le.Provider,{value:o,children:t})};var oe=function(t,e){return oe=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])},oe(t,e)};function ot(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");oe(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ne="Invariant Violation",me=Object.setPrototypeOf,at=me===void 0?function(t,e){return t.__proto__=e,t}:me,it=function(t){ot(e,t);function e(n){n===void 0&&(n=ne);var r=t.call(this,typeof n=="number"?ne+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=ne,at(r,e.prototype),r}return e}(Error);function ae(t,e){if(!t)throw new it(e)}var Ie=["debug","log","warn","error","silent"],ct=Ie.indexOf("log");function H(t){return function(){if(Ie.indexOf(t)>=ct){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=H("debug"),t.log=H("log"),t.warn=H("warn"),t.error=H("error")})(ae||(ae={}));const Fe=l.createContext(void 0),Oe=()=>l.useContext(Fe);function ut(t){const e=Oe(),n=l.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=l.useCallback(o=>{const i=[];return e&&i.push(e.subscribe(o)),r&&i.push(r.subscribe(o)),()=>{for(const c of i)c()}},[e,t,r]),a=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 i=n.current;if(i&&i.store===o&&i.version===o.version)return i.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return l.useSyncExternalStore(s,a),e==null?void 0:e.getExtensionPoint(t)}const lt=({registry:t,children:e})=>{const n=l.useRef(t);return ae(n.current===t,"You can't change the extension registry after it has been rendered"),O.jsx(Fe.Provider,{value:n.current,children:e})},re=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 De{constructor(e){T(this,"id");T(this,"mode");T(this,"_pluginId");T(this,"_version",0);T(this,"_contributions",new Map);T(this,"_lookupCache",new Map);T(this,"_matcher");T(this,"_select");T(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 a=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(a,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 dt{constructor(e){T(this,"_stores",new Map);T(this,"_storeUnsubs",new Map);T(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=re(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 De({...e,id:n});this._stores.set(n,r),this._storeUnsubs.set(n,r.subscribe(()=>this._notify())),this._notify()}getExtensionPoint(e){const n=re(e);return this._stores.get(n)}hasExtensionPoint(e){const n=re(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,a]of this._stores)a.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 Ae=l.createContext(void 0),ft={default:"info",info:"info",success:"success",warning:"warning",error:"error"},pt=({children:t})=>{const{push:e}=Xe.useNotificationStack(),[n,r]=l.useState([]),s=o=>{r(i=>[...i,o])},a=(o,i,c)=>{const d=typeof o=="object";let u="",h="info",p,f=5e3,y;if(d){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}h=o.status,p=o.details,f=o.autoHideDuration??5e3,y=o.actions}else u=o,h=i,p=c;e({severity:ft[h]??"info",title:u,message:p,timeout:f,actions:y})};return O.jsx(Ae.Provider,{value:{showSnackbar:a},children:t})},L=()=>{const t=l.useContext(Ae);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function A(t){const e=l.useContext(Z),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 yt=({pluginID:t,connectionID:e})=>{const n=A(t),r=S.useQueryClient(),{showSnackbar:s}=L(),a=[n,"connection","detail",e],{mutateAsync:o}=S.useMutation({mutationFn:async()=>g.StartConnection(n,e),onSuccess(h){r.setQueryData(a,h),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:M(s,"Failed to start connection")}),{mutateAsync:i}=S.useMutation({mutationFn:async()=>g.StopConnection(n,e),onSuccess(h){r.setQueryData(a,h)},onError:M(s,"Failed to stop connection")}),{mutateAsync:c}=S.useMutation({mutationFn:async h=>g.UpdateConnection(n,h),onSuccess(h,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(a,h),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(y=>y.id===e?h:y))},onError:M(s,"Failed to update connection")}),{mutateAsync:d}=S.useMutation({mutationFn:async()=>g.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(a,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},h=>h==null?void 0:h.filter(p=>p.id!==e))},onError:M(s,"Failed to remove connection")});return{connection:S.useQuery({queryKey:a,queryFn:async()=>g.GetConnection(n,e)}),startConnection:o,stopConnection:i,updateConnection:c,deleteConnection:d}},Te=t=>[t,"connection","list"],ht=({plugin:t})=>{const e=A(t),n=S.useQueryClient(),{showSnackbar:r}=L(),s=Te(e),{mutateAsync:a}=S.useMutation({mutationFn:async d=>g.StartConnectionWatch(e,d.id),onError:M(r,"Failed to start connection watch")}),{mutateAsync:o}=S.useMutation({mutationFn:async d=>g.StopConnectionWatch(e,d.id),onError:M(r,"Failed to stop connection watch")}),i=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`,i);return()=>{d()}},[e,i]),{connections:S.useQuery({queryKey:s,queryFn:async()=>{try{return await g.ListConnections(e)}catch(d){console.log(d),M(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:S.keepPreviousData}),startWatch:a,stopWatch:o}},gt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"connection","namespaces",e];return{namespaces:S.useQuery({queryKey:r,queryFn:async()=>g.GetConnectionNamespaces(n,e)})}};function ie(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,a=0,o=0;for(const u of e)u===C.WatchState.WatchStateSynced&&r++,(u===C.WatchState.WatchStateError||u===C.WatchState.WatchStateFailed)&&s++,u===C.WatchState.WatchStateForbidden&&a++,u===C.WatchState.WatchStateSkipped&&o++;const i=n-o,c=e.filter(u=>u===C.WatchState.WatchStateSynced||u===C.WatchState.WatchStateError||u===C.WatchState.WatchStateStopped||u===C.WatchState.WatchStateFailed||u===C.WatchState.WatchStateForbidden).length,d=i>0?c/i:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:i,syncedCount:r,errorCount:s,forbiddenCount:a,skippedCount:o,doneCount:c,progress:d}}function J(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function Me(t){return t.some(e=>!J(e))}function Ne(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 de(t){return`${t.pluginId}/${t.connection}`}function ke(t,e){const n=de(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 mt(){const[t,e]=l.useState(new Set),[n,r]=l.useState({}),[s,a]=l.useState(new Map),o=l.useRef(new Map),[i,c]=l.useState(new Map);l.useEffect(()=>{const m=D.On("plugin/crash_recovery_failed",I=>{const b=I.data,w=b==null?void 0:b.pluginID;w&&c(R=>{const F=new Map(R);return F.set(w,b.error??"Crash recovery failed"),F})}),P=D.On("plugin/recovered",I=>{const b=I.data,w=b==null?void 0:b.pluginID;w&&c(R=>{if(!R.has(w))return R;const F=new Map(R);return F.delete(w),F})});return()=>{m(),P()}},[]),l.useEffect(()=>{g.GetAllConnectionStates().then(m=>{if(!m)return;const P={},I=new Set,b=new Map;for(const[w,R]of Object.entries(m))if(R){P[w]=R.map(F=>F.connection);for(const F of R){if(!F.started)continue;const k=`${w}/${F.connection.id}`;I.add(k);const N={pluginID:w,connectionID:F.connection.id,states:{}};if(F.resources)for(const[te,Ye]of Object.entries(F.resources))N.states[te]=Ye;o.current.set(k,N),b.set(k,ie(N))}}r(P),e(I),a(b)}).catch(()=>{})},[]),l.useEffect(()=>D.On("connection/status",P=>{const I=P.data,b=`${I.pluginID}/${I.connectionID}`;I.status==="DISCONNECTED"?(e(w=>{const R=new Set(w);return R.delete(b),R}),a(w=>{const R=new Map(w);return R.delete(b),R}),o.current.delete(b)):e(w=>{const R=new Set(w);return R.add(b),R}),g.ListAllConnections().then(w=>{if(!w)return;const R={};for(const[F,k]of Object.entries(w))k!=null&&(R[F]=k);r(R)}).catch(()=>{})}),[]);const d=l.useCallback(m=>{const P=m.data,I=de(P);e(R=>{if(R.has(I))return R;const F=new Set(R);return F.add(I),F});const b=ke(o.current,P),w=ie(b);a(R=>{const F=new Map(R);return F.set(I,w),F})},[]);l.useEffect(()=>D.On("watch/STATE",d),[d]);const u=l.useCallback(async(m,P)=>{await g.StopConnection(m,P)},[]),h=l.useCallback(async(m,P)=>{await g.StartConnectionWatch(m,P)},[]),p=l.useCallback(async m=>{const P=i.get(m);c(I=>{if(!I.has(m))return I;const b=new Map(I);return b.delete(m),b});try{await g.RetryFailedPlugin(m)}catch(I){throw c(b=>{const w=new Map(b);return w.set(m,P??"Reload failed"),w}),I}},[i]),f=[];for(const m of t){const[P,I]=m.split("/",2),w=(n[P]??[]).find(te=>te.id===I),R=s.get(m),F=R!=null&&!J(R),k=R!=null&&R.errorCount>0,N=i.get(P);f.push({pluginID:P,connectionID:I,name:(w==null?void 0:w.name)??I,avatar:(w==null?void 0:w.avatar)??"",isStarted:!0,sync:R,isSyncing:F,hasErrors:k||N!=null,pluginFailed:N!=null,pluginError:N})}const y=new Map;for(const m of f){const P=y.get(m.pluginID)??[];P.push(m),y.set(m.pluginID,P)}const v=Array.from(s.values()),x=f.filter(m=>m.isSyncing),E=f.filter(m=>m.hasErrors),_=f.filter(m=>m.pluginFailed);return{entries:f,grouped:y,connectedCount:f.length,syncingCount:x.length,errorCount:E.length,failedCount:_.length,hasSyncing:Me(v),aggregateProgress:Ne(v),disconnect:u,retryWatch:h,retryPlugin:p}}function St(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 Ct(t,e,n){const r=A(t),s=S.useQueryClient(),a=[r,"data",e],o=S.useQuery({queryKey:a,queryFn:async()=>{const c=await g.Get(r,e);return c==null?n:St(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)}}),i=S.useMutation({mutationFn:async c=>{await g.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,c),{previous:d}},onError:(c,d,u)=>{(u==null?void 0:u.previous)!==void 0&&s.setQueryData(a,u.previous)},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{data:o.data??n,update:async c=>{await i.mutateAsync(c)},isLoading:o.isLoading}}const Et=()=>{const t=l.useContext(xe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},fe=()=>{const t=l.useContext(Re);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},_t=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=L(),{createTab:r,updateTab:s}=fe();return{createSession:S.useMutation({mutationFn:async({connectionID:o,icon:i,label:c,opts:d})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:i??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...d}}});const h=C.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const p=await g.CreateSession(e,o,h);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 f=$(p);s({id:u},{properties:{status:"error",error:f.detail,pluginID:e,connectionID:o,opts:{...d}}}),q(n,p,"Failed to start session")}}}).mutateAsync}},wt=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=L(),{createTab:r}=fe(),s=S.useMutation({mutationFn:async({connectionID:o,resourceKey:i,resourceID:c,resourceData:d,icon:u,label:h,target:p,follow:f=!0,tailLines:y=1e3,params:v})=>{const x=C.CreateSessionOptions.createFrom({resource_key:i,resource_id:c,resource_data:d,options:C.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:y,since_seconds:0,limit_bytes:0,include_source_events:!0,params:v??{}})}),E=await g.CreateSession$1(e,o,x);if(!E)throw new Error("Failed to create log session: null response");return r({id:E.id,title:h??`Logs ${E.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),E},onError:M(n,"Failed to start log session")}),a=S.useMutation({mutationFn:async o=>{await g.CloseSession(o)},onError:M(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:a.mutateAsync}},vt=()=>S.useQuery({queryKey:["metric","providers"],queryFn:g.GetProviders,staleTime:3e4}),We=t=>S.useQuery({queryKey:["metric","providers",t],queryFn:()=>g.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),bt=t=>{var x,E;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:a={},metricIDs:o=[],shape:i=0,timeRange:c,refreshInterval:d=0,enabled:u=!0}=t,{data:h,isLoading:p}=We(n),f=h??[],y=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,v=S.useQuery({queryKey:["metric","query",e,n,r,s,o,i,(x=c==null?void 0:c.start)==null?void 0:x.getTime(),(E=c==null?void 0:c.end)==null?void 0:E.getTime()],queryFn:async()=>{const _=await g.QueryAll(e,n,r,s,a,o,i,(c==null?void 0:c.start)??new Date(0),(c==null?void 0:c.end)??new Date(0),y),m={};for(const[P,I]of Object.entries(_))I!=null&&(m[P]=I);return m},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:S.keepPreviousData});return{data:v.data??void 0,providers:f,isLoading:p||v.isLoading,error:v.error,refetch:v.refetch}},Rt=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:a="",resourceData:o={},metricIDs:i=[],interval:c=1e4,enabled:d=!0}=t,u=A(e),[h,p]=l.useState(null),[f,y]=l.useState(null),[v,x]=l.useState(!1),[E,_]=l.useState(null),m=l.useRef(null),P=l.useCallback(async()=>{if(!(!d||!u||!n||!r||!s))try{const b=await g.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:a,resource_data:o,metric_ids:i,interval:c*1e6});y(b),x(!0),_(null);const w=D.On(`core/metrics/data/${b}`,F=>{const k=F.data;try{const N=JSON.parse(k);N.results&&p(N.results)}catch(N){console.error("Failed to parse metric stream data:",N)}}),R=D.On(`core/metrics/error/${b}`,F=>{const k=F.data;try{const N=JSON.parse(k);_(N.error||"Unknown error")}catch{_("Failed to parse metric stream error")}});m.current=()=>{w(),R()}}catch(b){_(b instanceof Error?b.message:String(b))}},[u,n,r,s,a,i,c,d]),I=l.useCallback(async()=>{if(f)try{await g.Unsubscribe(f)}catch(b){console.error("Failed to unsubscribe:",b)}m.current&&(m.current(),m.current=null),y(null),x(!1)},[f]);return l.useEffect(()=>()=>{f&&g.Unsubscribe(f).catch(console.error),m.current&&m.current()},[f]),{data:h,subscriptionID:f,isStreaming:v,error:E,start:P,stop:I}},U=["networker","portforward","all-sessions"];function xt(){const{showSnackbar:t}=L(),e=S.useQueryClient(),n=S.useQuery({queryKey:[...U],queryFn:async()=>g.ListAllPortForwardSessions().catch(a=>{if($(a).detail.includes("not found"))return[];throw a}),retry:!1});l.useEffect(()=>{const a=D.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...U]})}),o=D.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...U]})});return()=>{a(),o()}},[e]);const r=n.data??[],s=S.useMutation({mutationFn:async a=>g.ClosePortForwardSession(a),onError:M(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...U]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:a=>D.OpenURL(`http://localhost:${a}`)}}function Pt({pluginID:t,connectionID:e,resourceID:n}){const r=A(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:a}=L(),o=S.useQueryClient(),i=S.useQuery({queryKey:s,queryFn:async()=>g.FindPortForwardSessions(r,e,C.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const h=$(u);return h.detail.includes("not found")?[]:(a({message:"Failed to fetch port forward sessions",status:"error",details:h.detail}),[])}),retry:!1}),c=S.useMutation({mutationFn:async({opts:u})=>{const h=C.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 g.StartResourcePortForwardingSession(r,e,h);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(a,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...U]})])}}),d=S.useMutation({mutationFn:async({opts:u})=>g.ClosePortForwardSession(u.sessionID),onError:M(a,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...U]})])}});return{sessions:i,forward:c.mutateAsync,close:d.mutateAsync}}const It=()=>{const t=l.useContext(Pe);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Ft=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const a=A(t),o=S.useQueryClient(),{showSnackbar:i}=L(),c=["RESOURCE",a,e,n,r,s],{mutateAsync:d}=S.useMutation({mutationFn:async p=>g.Update(a,e,n,C.UpdateInput.createFrom({input:p.input,id:r,namespace:s})),onSuccess:async()=>{i(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(i,`Failed to update resource ${r}`)}),{mutateAsync:u}=S.useMutation({mutationFn:async(p={})=>g.Delete(a,e,n,C.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:p.gracePeriodSeconds})),onSuccess:async()=>{i(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(i,`Failed to delete resource ${r}`)});return{resource:S.useQuery({queryKey:c,queryFn:async()=>g.Get$1(a,e,n,C.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:u}},Ot=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:S.useQuery({queryKey:e,queryFn:async()=>g.GetResourceAreaComponent(t)})}},Dt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resource_groups","list"];return{groups:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceGroups(n,e),retry:!1})}},At=({pluginID:t,connectionID:e,searches:n})=>{const r=A(t),s=o=>[r,e,o.key,o.namespaces,"list"];return S.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>g.List(r,e,o.key,C.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(i=>i?(console.log(i.result),i.result&&o.postFilter?Object.values(i.result).filter(o.postFilter):Object.values(i.result||{})):[]),retry:!1}))})},Tt=({pluginID:t,resourceKey:e})=>{const n=A(t),r=[n,"resources",e];return{resourceType:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceType(n,e),retry:!1})}},Mt=({pluginID:t,connectionID:e})=>{const n=A(t),r=[n,"resources","list",e];return{types:S.useQuery({queryKey:r,queryFn:async()=>g.GetResourceTypes(n,e),retry:!1})}};var z=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Nt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var kt="Expected a function",Le="__lodash_hash_undefined__",Wt="[object Function]",Lt="[object GeneratorFunction]",$t="[object Symbol]",Ut=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qt=/^\w*$/,jt=/^\./,Qt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Gt=/[\\^$.*+?()[\]{}|]/g,Kt=/\\(\\)?/g,Bt=/^\[object .+?Constructor\]$/,Ht=typeof z=="object"&&z&&z.Object===Object&&z,zt=typeof self=="object"&&self&&self.Object===Object&&self,pe=Ht||zt||Function("return this")();function Yt(t,e){return t==null?void 0:t[e]}function Jt(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var Zt=Array.prototype,Xt=Function.prototype,$e=Object.prototype,se=pe["__core-js_shared__"],Se=function(){var t=/[^.]+$/.exec(se&&se.keys&&se.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Ue=Xt.toString,ye=$e.hasOwnProperty,qe=$e.toString,Vt=RegExp("^"+Ue.call(ye).replace(Gt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ce=pe.Symbol,en=Zt.splice,tn=je(pe,"Map"),B=je(Object,"create"),Ee=Ce?Ce.prototype:void 0,_e=Ee?Ee.toString:void 0;function j(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 nn(){this.__data__=B?B(null):{}}function rn(t){return this.has(t)&&delete this.__data__[t]}function sn(t){var e=this.__data__;if(B){var n=e[t];return n===Le?void 0:n}return ye.call(e,t)?e[t]:void 0}function on(t){var e=this.__data__;return B?e[t]!==void 0:ye.call(e,t)}function an(t,e){var n=this.__data__;return n[t]=B&&e===void 0?Le:e,this}j.prototype.clear=nn;j.prototype.delete=rn;j.prototype.get=sn;j.prototype.has=on;j.prototype.set=an;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 cn(){this.__data__=[]}function un(t){var e=this.__data__,n=V(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():en.call(e,n,1),!0}function ln(t){var e=this.__data__,n=V(e,t);return n<0?void 0:e[n][1]}function dn(t){return V(this.__data__,t)>-1}function fn(t,e){var n=this.__data__,r=V(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}G.prototype.clear=cn;G.prototype.delete=un;G.prototype.get=ln;G.prototype.has=dn;G.prototype.set=fn;function Q(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 pn(){this.__data__={hash:new j,map:new(tn||G),string:new j}}function yn(t){return ee(this,t).delete(t)}function hn(t){return ee(this,t).get(t)}function gn(t){return ee(this,t).has(t)}function mn(t,e){return ee(this,t).set(t,e),this}Q.prototype.clear=pn;Q.prototype.delete=yn;Q.prototype.get=hn;Q.prototype.has=gn;Q.prototype.set=mn;function V(t,e){for(var n=t.length;n--;)if(In(t[n][0],e))return n;return-1}function Sn(t,e){e=wn(e,t)?[e]:_n(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[xn(e[n++])];return n&&n==r?t:void 0}function Cn(t){if(!Ge(t)||bn(t))return!1;var e=Fn(t)||Jt(t)?Vt:Bt;return e.test(Pn(t))}function En(t){if(typeof t=="string")return t;if(ge(t))return _e?_e.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function _n(t){return Qe(t)?t:Rn(t)}function ee(t,e){var n=t.__data__;return vn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function je(t,e){var n=Yt(t,e);return Cn(n)?n:void 0}function wn(t,e){if(Qe(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||ge(t)?!0:qt.test(t)||!Ut.test(t)||e!=null&&t in Object(e)}function vn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function bn(t){return!!Se&&Se in t}var Rn=he(function(t){t=Dn(t);var e=[];return jt.test(t)&&e.push(""),t.replace(Qt,function(n,r,s,a){e.push(s?a.replace(Kt,"$1"):r||n)}),e});function xn(t){if(typeof t=="string"||ge(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Pn(t){if(t!=null){try{return Ue.call(t)}catch{}try{return t+""}catch{}}return""}function he(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],a=n.cache;if(a.has(s))return a.get(s);var o=t.apply(this,r);return n.cache=a.set(s,o),o};return n.cache=new(he.Cache||Q),n}he.Cache=Q;function In(t,e){return t===e||t!==t&&e!==e}var Qe=Array.isArray;function Fn(t){var e=Ge(t)?qe.call(t):"";return e==Wt||e==Lt}function Ge(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function On(t){return!!t&&typeof t=="object"}function ge(t){return typeof t=="symbol"||On(t)&&qe.call(t)==$t}function Dn(t){return t==null?"":En(t)}function An(t,e,n){var r=t==null?void 0:Sn(t,e);return r===void 0?n:r}var Tn=An;const Y=Nt(Tn);function Ke(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const a of e){const o=Y(a.payload.data,n);switch(a.type){case"ADD":{s.findIndex(c=>Y(c,n)===o)===-1&&s.push(a.payload.data);break}case"UPDATE":{const i=s.findIndex(c=>Y(c,n)===o);i!==-1&&(s[i]=a.payload.data);break}case"DELETE":{const i=s.findIndex(c=>Y(c,n)===o);i!==-1&&s.splice(i,1);break}}}return{...r,result:s}}function Be(t,e,n,r,s,a){const o=(a==null?void 0:a.syncWindowMs)??500,i=l.useRef([]),c=l.useRef(null),d=l.useRef(null),u=l.useRef(s);u.current=s;const h=l.useCallback(()=>{const f=i.current;if(i.current=[],c.current=null,d.current=null,!(f.length===0||!r)){t.setQueryData(e,y=>Ke(y,f,r));for(const y of f)(y.type==="ADD"||y.type==="UPDATE")&&t.setQueryData(n(y.payload.id,y.payload.namespace),{result:y.payload.data})}},[t,e,n,r]),p=l.useCallback(f=>{i.current.push(f),!(c.current!==null||d.current!==null)&&(u.current===1?c.current=setTimeout(h,o):d.current=requestAnimationFrame(h))},[h,o]);return l.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),p}const Mn=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const a=A(t),o=S.useQueryClient(),{showSnackbar:i}=L(),c=l.useMemo(()=>s??[],[s]),d=l.useMemo(()=>[a,e,n,c,"list"],[a,e,n,c]),u=l.useCallback((x,E)=>[a,e,n,E,x],[a,e,n]),{mutateAsync:h}=S.useMutation({mutationFn:async x=>g.Create(a,e,n,C.CreateInput.createFrom({input:x.input,namespace:x.namespace??(c.length===1?c[0]:"")})),onSuccess:async x=>{var P;const E=x==null?void 0:x.result;let _="";(P=E==null?void 0:E.metadata)!=null&&P.name?_=E.metadata.name:E!=null&&E.id?_=E.id:E!=null&&E.name?_=E.name:E!=null&&E.ID?_=E.ID:E!=null&&E.Name&&(_=E.Name);const m=_?`Resource ${_} created`:"Resource created";i(m,"success"),await o.invalidateQueries({queryKey:d})},onError:M(i,"Failed to create resource")}),p=S.useQuery({queryKey:d,queryFn:async()=>g.List(a,e,n,C.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(x,E)=>x,retry:!1}),[f,y]=l.useState(C.WatchState.WatchStateIdle);l.useEffect(()=>D.On(`${a}/${e}/watch/STATE`,E=>{const _=E.data;_.resourceKey===n&&y(_.state)}),[a,e,n]);const v=Be(o,d,u,r,f);return l.useEffect(()=>{if(!r)return;g.SubscribeResource(a,e,n);const x=D.On(`${a}/${e}/${n}/ADD`,m=>v({type:"ADD",payload:m.data})),E=D.On(`${a}/${e}/${n}/UPDATE`,m=>v({type:"UPDATE",payload:m.data})),_=D.On(`${a}/${e}/${n}/DELETE`,m=>v({type:"DELETE",payload:m.data}));return()=>{x(),E(),_(),g.UnsubscribeResource(a,e,n)}},[a,e,n,v]),{resources:p,create:h,watchState:f,isSyncing:f===C.WatchState.WatchStateSyncing,isSynced:f===C.WatchState.WatchStateSynced,watchError:f===C.WatchState.WatchStateError}},Nn=({pluginID:t})=>{const e=A(t),{showSnackbar:n}=L(),r=S.useMutation({mutationFn:async({opts:o,input:i})=>g.Create(e,o.connectionID,o.resourceKey,C.CreateInput.createFrom({input:i.input,namespace:i.namespace??o.namespace??""})),onSuccess:(o,{opts:i})=>{n(`Resource ${i.resourceID} created`,"success")},onError(o,{opts:i}){q(n,o,`Failed to create resource ${i.resourceID}`)}}),s=S.useMutation({mutationFn:async({opts:o,input:i})=>g.Update(e,o.connectionID,o.resourceKey,C.UpdateInput.createFrom({input:i.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:i})=>{n(`Resource ${i.resourceID} updated`,"success")},onError(o,{opts:i}){q(n,o,`Failed to update resource ${i.resourceID}`)}}),a=S.useMutation({mutationFn:async({opts:o,input:i})=>g.Delete(e,o.connectionID,o.resourceKey,C.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:i.gracePeriodSeconds})),onSuccess:(o,{opts:i})=>{n(`Resource ${i.resourceID} deleted`,"success")},onError(o,{opts:i}){q(n,o,`Failed to delete resource ${i.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:a.mutateAsync}},kn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=A(t),a=S.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>g.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:a.data??[],isLoading:a.isLoading,error:a.error}},Wn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),s=S.useQueryClient(),{showSnackbar:a}=L(),o=S.useMutation({mutationFn:async({actionID:i,id:c="",namespace:d="",params:u={}})=>g.ExecuteAction(r,e,n,i,C.ActionInput.createFrom({id:c,namespace:d,params:u})),onSuccess:i=>{i!=null&&i.message&&a(i.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(i,c)=>{q(a,i,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Ln=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=S.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>g.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}},$n=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=A(t),s=S.useQueryClient(),a=[r,e,"watch-state"],o=l.useRef([]),i=l.useRef(!1),c=l.useCallback(p=>{s.setQueryData(a,f=>{if(!f)return f;const y={...f.resources,[p.resourceKey]:p.state},v={...f.resourceCounts,[p.resourceKey]:p.resourceCount};let x=0,E=0;for(const _ of Object.values(y))_===C.WatchState.WatchStateSynced&&x++,(_===C.WatchState.WatchStateError||_===C.WatchState.WatchStateFailed)&&E++;return{...f,resources:y,resourceCounts:v,totalResources:Object.keys(y).length,syncedCount:x,errorCount:E}})},[s,r,e]),d=S.useQuery({queryKey:a,queryFn:async()=>{const p=await g.GetWatchState(r,e);if(!p)throw new Error("Failed to get watch state: null response");const f={};let y=0,v=0;for(const[E,_]of Object.entries(p.resources??{}))_!=null&&(f[E]=_,_===C.WatchState.WatchStateSynced&&y++,_===C.WatchState.WatchStateError&&v++);const x={};for(const[E,_]of Object.entries(p.resourceCounts??{}))_!=null&&(x[E]=_);return{connection:p.connectionId,resources:f,resourceCounts:x,totalResources:Object.keys(f).length,syncedCount:y,errorCount:v}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let y=0;for(const v of Object.values(f.resources))(v===C.WatchState.WatchStateSynced||v===C.WatchState.WatchStateError||v===C.WatchState.WatchStateStopped||v===C.WatchState.WatchStateFailed||v===C.WatchState.WatchStateForbidden||v===C.WatchState.WatchStateSkipped)&&y++;return y>=f.totalResources?!1:3e3}});l.useEffect(()=>{if(!d.data||i.current)return;i.current=!0;const p=o.current;o.current=[];for(const f of p)c(f)},[d.data,c]),l.useEffect(()=>{if(!n||!r||!e)return;i.current=!1,o.current=[];const p=D.On(`${r}/${e}/watch/STATE`,f=>{const y=f.data;i.current?c(y):o.current.push(y)});return()=>{p(),i.current=!1,o.current=[]}},[r,e,n,c]);const u=d.data;let h=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===C.WatchState.WatchStateSynced||p===C.WatchState.WatchStateError||p===C.WatchState.WatchStateStopped||p===C.WatchState.WatchStateFailed||p===C.WatchState.WatchStateForbidden||p===C.WatchState.WatchStateSkipped)&&h++;return{summary:d,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&h===u.totalResources:!1,syncProgress:u&&u.totalResources>0?h/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Un=()=>{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,h=de(u),p=ke(n.current,u),f=ie(p);if(e(y=>{const v=new Map(y);return v.set(h,f),v}),r.current.has(h)&&(clearTimeout(r.current.get(h)),r.current.delete(h)),J(f)){const y=setTimeout(()=>{e(v=>{const x=new Map(v);return x.delete(h),x}),n.current.delete(h),r.current.delete(h)},5e3);r.current.set(h,y)}},[]);l.useEffect(()=>{const d=D.On("watch/STATE",s);return()=>{d();for(const u of r.current.values())clearTimeout(u)}},[s]);const a=Array.from(t.values()),o=Me(a),i=a.find(d=>!J(d))??a[0]??null,c=Ne(a);return{syncs:a,hasSyncing:o,primarySync:i,aggregateProgress:c}},He=()=>{const t=l.useContext(le);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},qn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=A(t),{showSnackbar:s}=L(),{addOperation:a,updateOperation:o}=He(),i=l.useRef([]);return l.useEffect(()=>()=>{i.current.forEach(d=>d())},[]),{startStreamAction:l.useCallback(async({actionID:d,id:u,namespace:h,label:p,params:f={}})=>{try{const y=await g.StreamAction(r,e,n,d,C.ActionInput.createFrom({id:u,namespace:h,params:f}));a({id:y,label:p,resourceKey:n,resourceName:u,namespace:h,connectionID:e,status:"running",startedAt:Date.now()});const v=`action/stream/${y}`,x=D.On(v,E=>{var m,P,I,b;const _=E.data;switch(_.type){case"progress":{const w=_.data??{};o(y,{message:w.message,progress:w.ready!==void 0&&w.desired!==void 0?{ready:w.ready,desired:w.desired}:void 0});break}case"complete":o(y,{status:"completed",message:((m=_.data)==null?void 0:m.message)??"Completed",completedAt:Date.now()}),s(((P=_.data)==null?void 0:P.message)??p+" completed","success"),D.Off(v);break;case"error":o(y,{status:"error",message:((I=_.data)==null?void 0:I.message)??"Failed",completedAt:Date.now()}),s(((b=_.data)==null?void 0:b.message)??p+" failed","error"),D.Off(v);break}});return i.current.push(()=>{x(),D.Off(v)}),y}catch(y){throw q(s,y,`Failed to start "${d}"`),y}},[r,e,n,a,o,s])}},jn=()=>{const t=l.useContext(ue);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},Qn=({to:t,withinContext:e,...n})=>{const{pluginId:r}=X();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return l.useMemo(()=>O.jsx(K.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function Gn(){const t=K.useNavigate(),e=K.useLocation(),{pluginId:n}=X();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,a=l.useCallback((o,i)=>{const{...c}=i??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return l.useMemo(()=>({location:e,navigate:a,pluginPath:s}),[e,a,s])}class Kn{}class Bn{constructor(){T(this,"_extensions");T(this,"root");T(this,"pages");T(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 O.jsx(this.root,{});const e=K.createMemoryRouter(this._routes||[]);return O.jsx(K.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 ze=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(ze||{});const Hn=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]}},zn=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.WatchState=C.WatchState;exports.ALL_SESSIONS_KEY=U;exports.BottomDrawerContext=Re;exports.ConfirmationModalContext=Pe;exports.ErrorTypes=W;exports.ExtensionPointRegistry=dt;exports.ExtensionPointStore=De;exports.ExtensionProvider=lt;exports.Link=Qn;exports.OperationsContext=le;exports.OperationsProvider=st;exports.PluginContext=Z;exports.PluginContextProvider=et;exports.PluginErrorCode=ze;exports.PluginWindow=Bn;exports.PluginWindowRootProps=Kn;exports.RightDrawerContext=xe;exports.SettingsContext=ue;exports.SettingsProvider=nt;exports.SnackbarProvider=pt;exports.actionToSnackbar=we;exports.applyBatch=Ke;exports.connectionListQueryKey=Te;exports.createErrorHandler=M;exports.defaultState=be;exports.formatGroup=zn;exports.isCancelledError=ce;exports.parseAppError=$;exports.parseResourceKey=Hn;exports.showAppError=q;exports.useActiveSyncs=Un;exports.useBottomDrawer=fe;exports.useConfirmationModal=It;exports.useConnection=yt;exports.useConnectionNamespaces=gt;exports.useConnectionStatus=mt;exports.useConnections=ht;exports.useEditorSchemas=Ln;exports.useEventBatcher=Be;exports.useExec=_t;exports.useExecuteAction=Wn;exports.useExtensionPoint=ut;exports.useExtensionRegistry=Oe;exports.useLogs=wt;exports.useMetricProviders=vt;exports.useMetricProvidersForResource=We;exports.useMetricStream=Rt;exports.useOperations=He;exports.usePluginContext=X;exports.usePluginData=Ct;exports.usePluginRouter=Gn;exports.usePluginSettings=tt;exports.usePortForwardSessions=xt;exports.useResolvedPluginId=A;exports.useResource=Ft;exports.useResourceActions=kn;exports.useResourceAreaComponent=Ot;exports.useResourceGroups=Dt;exports.useResourceMetrics=bt;exports.useResourceMutations=Nn;exports.useResourcePortForwarder=Pt;exports.useResourceSearch=At;exports.useResourceType=Tt;exports.useResourceTypes=Mt;exports.useResources=Mn;exports.useRightDrawer=Et;exports.useSettings=jn;exports.useSnackbar=L;exports.useStreamAction=qn;exports.useWatchState=$n;