@omniviewdev/runtime 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/api.cjs +1 -1
  2. package/dist/api.js +246 -113
  3. package/dist/bindings/events/index.d.ts +140 -0
  4. package/dist/bindings/github.com/omniviewdev/omniview/appservice.d.ts +5 -0
  5. package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/devserver/index.d.ts +1 -1
  6. package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/devserver/models.d.ts +24 -26
  7. package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/devserver/servicewrapper.d.ts +0 -1
  8. package/dist/bindings/github.com/omniviewdev/omniview/backend/pkg/plugin/servicewrapper.d.ts +2 -0
  9. package/dist/bindings/github.com/omniviewdev/omniview/internal/devcontract/index.d.ts +1 -0
  10. package/dist/bindings/github.com/omniviewdev/omniview/internal/devcontract/models.d.ts +101 -0
  11. package/dist/bindings/github.com/omniviewdev/plugin-sdk/pkg/config/index.d.ts +1 -1
  12. package/dist/bindings/github.com/omniviewdev/plugin-sdk/pkg/config/models.d.ts +31 -0
  13. package/dist/errors/types.d.ts +2 -0
  14. package/dist/graphservice-Cb7rr7SB.cjs +1 -0
  15. package/dist/graphservice-DloOtC_7.js +739 -0
  16. package/dist/index.cjs +2 -2
  17. package/dist/index.js +566 -539
  18. package/dist/models-8-4Ny_ft.cjs +1 -0
  19. package/dist/{models-3V1aa9YT.js → models-BlTzZkmp.js} +46 -60
  20. package/dist/models-CGYstu7u.cjs +1 -0
  21. package/dist/{models-B97zjrHu.js → models-D-vu7j83.js} +442 -411
  22. package/dist/models.cjs +1 -1
  23. package/dist/models.d.ts +1 -1
  24. package/dist/models.js +39 -38
  25. package/package.json +5 -5
  26. package/dist/graphservice-2kgAuCnt.cjs +0 -1
  27. package/dist/graphservice-5kuEPkCT.js +0 -731
  28. package/dist/models-BPmIMpct.cjs +0 -1
  29. package/dist/models-sJV1iQbd.cjs +0 -1
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var et=Object.defineProperty;var tt=(t,e,n)=>e in t?et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>tt(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),d=require("react"),B=require("react-router-dom"),h=require("./graphservice-2kgAuCnt.cjs"),D=require("./models-sJV1iQbd.cjs"),m=require("@tanstack/react-query"),nt=require("@omniviewdev/base-ui");require("./index-D_aIcqH0.cjs");const T=require("./events-BTiuwc-0.cjs"),rt=require("./legacyEnum-DkV5yRdA.cjs"),X=d.createContext(void 0),q={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 st(t){switch(t){case"NOT_FOUND":return{typeUri:q.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:q.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:q.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:q.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:q.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:q.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:q.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:q.INTERNAL,status:500}}}function $(t){if(t==null)return{type:q.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}=st(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:q.INTERNAL,title:"Error",status:500,detail:e}}function le(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:$(t).type===q.CANCELLED}function ve(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 Re(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
- `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(ve)}}function j(t,e,n){if(le(e))return;const r=$(e);t(Re(r,n))}function N(t,e){return n=>{if(le(n))return;const r=$(n);t(Re(r,r.title!=="Error"?r.title:e))}}function ot(t){const{children:e,pluginId:n}=t,[r,s]=d.useState({}),[i,o]=d.useState(new D.PluginMeta),[a,c]=d.useState(!1),[l,u]=d.useState(null);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!l});const y=()=>{n===void 0||n===""||(console.debug(`[PluginContextProvider] fetching settings for "${n}"`),h.PluginValues(n).then(f=>{console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(f)),s(f)}).catch(f=>{const g=$(f);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,g.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),h.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 g=$(f);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,g.detail),u(g.detail),c(!1)})};return d.useEffect(()=>{console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),y(),p()},[n]),l?A.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:A.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:[A.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[A.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("circle",{cx:"12",cy:"12",r:"10"}),A.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),A.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),A.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),A.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:l}),A.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?A.jsx(X.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):A.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[A.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),A.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function V(){const t=d.useContext(X);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function it(){return V().settings}const de=d.createContext(void 0),at=({children:t})=>{const[e,n]=d.useState({}),r=()=>{h.Values().then(i=>{console.log("Fetched settings:",i),n(i)}).catch(i=>{console.error("Error fetching settings:",i)})};d.useEffect(()=>{r()},[]);const s=()=>{r()};return A.jsx(de.Provider,{value:{settings:e,reload:s},children:t})},xe={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Fe=d.createContext(xe),Pe=d.createContext(void 0),Oe=d.createContext(void 0),fe=d.createContext(void 0),ct=3e4,ut=({children:t})=>{const[e,n]=d.useState([]),r=d.useCallback(a=>{n(c=>[a,...c])},[]),s=d.useCallback((a,c)=>{n(l=>l.map(u=>u.id===a?{...u,...c}:u))},[]),i=d.useCallback(a=>{n(c=>c.filter(l=>l.id!==a))},[]);d.useEffect(()=>{const a=[];for(const c of e)if(c.status==="completed"||c.status==="error"){const l=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,ct-l);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[e,i]);const o=d.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return A.jsx(fe.Provider,{value:o,children:t})};var ae=function(t,e){return ae=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])},ae(t,e)};function lt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ae(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var se="Invariant Violation",Ce=Object.setPrototypeOf,dt=Ce===void 0?function(t,e){return t.__proto__=e,t}:Ce,ft=function(t){lt(e,t);function e(n){n===void 0&&(n=se);var r=t.call(this,typeof n=="number"?se+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=se,dt(r,e.prototype),r}return e}(Error);function ce(t,e){if(!t)throw new ft(e)}var Ie=["debug","log","warn","error","silent"],pt=Ie.indexOf("log");function z(t){return function(){if(Ie.indexOf(t)>=pt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=z("debug"),t.log=z("log"),t.warn=z("warn"),t.error=z("error")})(ce||(ce={}));const Te=d.createContext(void 0),Ae=()=>d.useContext(Te);function yt(t){const e=Ae(),n=d.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=d.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=d.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 l={};return n.current={store:void 0,version:-1,sentinel:l},l}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return d.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const gt=({registry:t,children:e})=>{const n=d.useRef(t);return ce(n.current===t,"You can't change the extension registry after it has been rendered"),A.jsx(Te.Provider,{value:n.current,children:e})},oe=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){M(this,"id");M(this,"mode");M(this,"_pluginId");M(this,"_version",0);M(this,"_contributions",new Map);M(this,"_lookupCache",new Map);M(this,"_matcher");M(this,"_select");M(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class ht{constructor(e){M(this,"_stores",new Map);M(this,"_storeUnsubs",new Map);M(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=oe(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=oe(e);return this._stores.get(n)}hasExtensionPoint(e){const n=oe(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const Me=d.createContext(void 0),mt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},St=({children:t})=>{const{toast:e}=nt.useToast(),[n,r]=d.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const l=typeof o=="object";let u="",y="info",p,f=5e3,g;if(l){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}y=o.status,p=o.details,f=o.autoHideDuration??5e3,g=o.actions}else u=o,y=a,p=c;e(p??u,{severity:mt[y]??"info",title:p?u:void 0,duration:f,action:g==null?void 0:g[0]})};return A.jsx(Me.Provider,{value:{showSnackbar:i},children:t})},U=()=>{const t=d.useContext(Me);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function I(t){const e=d.useContext(X),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 Ct=({pluginID:t,connectionID:e})=>{const n=I(t),r=m.useQueryClient(),{showSnackbar:s}=U(),i=[n,"connection","detail",e],{mutateAsync:o}=m.useMutation({mutationFn:async()=>h.StartConnection(n,e),onSuccess(y){r.setQueryData(i,y),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:N(s,"Failed to start connection")}),{mutateAsync:a}=m.useMutation({mutationFn:async()=>h.StopConnection(n,e),onSuccess(y){r.setQueryData(i,y)},onError:N(s,"Failed to stop connection")}),{mutateAsync:c}=m.useMutation({mutationFn:async y=>h.UpdateConnection(n,y),onSuccess(y,{name:p}){s({message:`Connection ${p} successfully updated`,status:"success"}),r.setQueryData(i,y),r.setQueriesData({queryKey:[n,"connection","list"]},f=>f==null?void 0:f.map(g=>g.id===e?y:g))},onError:N(s,"Failed to update connection")}),{mutateAsync:l}=m.useMutation({mutationFn:async()=>h.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},y=>y==null?void 0:y.filter(p=>p.id!==e))},onError:N(s,"Failed to remove connection")});return{connection:m.useQuery({queryKey:i,queryFn:async()=>h.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:l}},Ne=t=>[t,"connection","list"],Et=({plugin:t})=>{const e=I(t),n=m.useQueryClient(),{showSnackbar:r}=U(),s=Ne(e),{mutateAsync:i}=m.useMutation({mutationFn:async l=>h.StartConnectionWatch(e,l.id),onError:N(r,"Failed to start connection watch")}),{mutateAsync:o}=m.useMutation({mutationFn:async l=>h.StopConnectionWatch(e,l.id),onError:N(r,"Failed to stop connection watch")}),a=d.useCallback(l=>{const u=l.data;console.log("got update to connections",u),n.setQueryData(s,u)},[n,s]);return d.useEffect(()=>{const l=T.On(`${e}/connection/sync`,a);return()=>{l()}},[e,a]),{connections:m.useQuery({queryKey:s,queryFn:async()=>{try{return await h.ListConnections(e)}catch(l){console.log(l),N(r,"Failed to load connections")(l)}return[]},staleTime:3e4,placeholderData:m.keepPreviousData}),startWatch:i,stopWatch:o}},_t=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"connection","namespaces",e];return{namespaces:m.useQuery({queryKey:r,queryFn:async()=>h.GetConnectionNamespaces(n,e)})}},P=rt.withLegacyNames(D.WatchState,"WatchState");function ue(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const u of e)u===P.WatchStateSynced&&r++,(u===P.WatchStateError||u===P.WatchStateFailed)&&s++,u===P.WatchStateForbidden&&i++,u===P.WatchStateSkipped&&o++;const a=n-o,c=e.filter(u=>u===P.WatchStateSynced||u===P.WatchStateError||u===P.WatchStateStopped||u===P.WatchStateFailed||u===P.WatchStateForbidden).length,l=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:l}}function Z(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function ke(t){return t.some(e=>!Z(e))}function Le(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 pe(t){return`${t.pluginId}/${t.connection}`}function qe(t,e){const n=pe(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 wt(){const[t,e]=d.useState(new Set),[n,r]=d.useState({}),[s,i]=d.useState(new Map),o=d.useRef(new Map),[a,c]=d.useState(new Map);d.useEffect(()=>{const S=T.On("plugin/crash_recovery_failed",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{const O=new Map(v);return O.set(_,b.error??"Crash recovery failed"),O})}),x=T.On("plugin/recovered",F=>{const b=F.data,_=b==null?void 0:b.pluginID;_&&c(v=>{if(!v.has(_))return v;const O=new Map(v);return O.delete(_),O})});return()=>{S(),x()}},[]),d.useEffect(()=>{h.GetAllConnectionStates().then(S=>{if(!S)return;const x={},F=new Set,b=new Map;for(const[_,v]of Object.entries(S))if(v){x[_]=v.map(O=>O.connection);for(const O of v){if(!O.started)continue;const L=`${_}/${O.connection.id}`;F.add(L);const k={pluginID:_,connectionID:O.connection.id,states:{}};if(O.resources)for(const[re,Ve]of Object.entries(O.resources))k.states[re]=Ve;o.current.set(L,k),b.set(L,ue(k))}}r(x),e(F),i(b)}).catch(()=>{})},[]),d.useEffect(()=>T.On("connection/status",x=>{const F=x.data,b=`${F.pluginID}/${F.connectionID}`;F.status==="DISCONNECTED"?(e(_=>{const v=new Set(_);return v.delete(b),v}),i(_=>{const v=new Map(_);return v.delete(b),v}),o.current.delete(b)):e(_=>{const v=new Set(_);return v.add(b),v}),h.ListAllConnections().then(_=>{if(!_)return;const v={};for(const[O,L]of Object.entries(_))L!=null&&(v[O]=L);r(v)}).catch(()=>{})}),[]);const l=d.useCallback(S=>{const x=S.data,F=pe(x);e(v=>{if(v.has(F))return v;const O=new Set(v);return O.add(F),O});const b=qe(o.current,x),_=ue(b);i(v=>{const O=new Map(v);return O.set(F,_),O})},[]);d.useEffect(()=>T.On("watch/STATE",l),[l]);const u=d.useCallback(async(S,x)=>{await h.StopConnection(S,x)},[]),y=d.useCallback(async(S,x)=>{await h.StartConnectionWatch(S,x)},[]),p=d.useCallback(async S=>{const x=a.get(S);c(F=>{if(!F.has(S))return F;const b=new Map(F);return b.delete(S),b});try{await h.RetryFailedPlugin(S)}catch(F){throw c(b=>{const _=new Map(b);return _.set(S,x??"Reload failed"),_}),F}},[a]),f=[];for(const S of t){const[x,F]=S.split("/",2),_=(n[x]??[]).find(re=>re.id===F),v=s.get(S),O=v!=null&&!Z(v),L=v!=null&&v.errorCount>0,k=a.get(x);f.push({pluginID:x,connectionID:F,name:(_==null?void 0:_.name)??F,avatar:(_==null?void 0:_.avatar)??"",isStarted:!0,sync:v,isSyncing:O,hasErrors:L||k!=null,pluginFailed:k!=null,pluginError:k})}const g=new Map;for(const S of f){const x=g.get(S.pluginID)??[];x.push(S),g.set(S.pluginID,x)}const w=Array.from(s.values()),R=f.filter(S=>S.isSyncing),C=f.filter(S=>S.hasErrors),E=f.filter(S=>S.pluginFailed);return{entries:f,grouped:g,connectedCount:f.length,syncingCount:R.length,errorCount:C.length,failedCount:E.length,hasSyncing:ke(w),aggregateProgress:Le(w),disconnect:u,retryWatch:y,retryPlugin:p}}function bt(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 vt(t,e,n){const r=I(t),s=m.useQueryClient(),i=[r,"data",e],o=m.useQuery({queryKey:i,queryFn:async()=>{const c=await h.Get(r,e);return c==null?n:bt(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=m.useMutation({mutationFn:async c=>{await h.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const l=s.getQueryData(i);return s.setQueryData(i,c),{previous:l}},onError:(c,l,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 Rt=()=>{const t=d.useContext(Pe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},ye=()=>{const t=d.useContext(Fe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},xt=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),{createTab:r,updateTab:s}=ye();return{createSession:m.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:l})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...l}}});const y=D.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...l});try{const p=await h.CreateSession(e,o,y);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:{...l}}})}catch(p){const f=$(p);s({id:u},{properties:{status:"error",error:f.detail,pluginID:e,connectionID:o,opts:{...l}}}),j(n,p,"Failed to start session")}}}).mutateAsync}},Ft=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),{createTab:r}=ye(),s=m.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:l,icon:u,label:y,target:p,follow:f=!0,tailLines:g=1e3,params:w})=>{const R=D.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:l,options:D.LogSessionOptions.createFrom({target:p??"",follow:f,include_previous:!1,include_timestamps:!0,tail_lines:g,since_seconds:0,limit_bytes:0,include_source_events:!0,params:w??{}})}),C=await h.CreateSession$1(e,o,R);if(!C)throw new Error("Failed to create log session: null response");return r({id:C.id,title:y??`Logs ${C.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),C},onError:N(n,"Failed to start log session")}),i=m.useMutation({mutationFn:async o=>{await h.CloseSession(o)},onError:N(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Pt=()=>m.useQuery({queryKey:["metric","providers"],queryFn:h.GetProviders,staleTime:3e4}),Ue=t=>m.useQuery({queryKey:["metric","providers",t],queryFn:()=>h.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Ot=t=>{var R,C;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:l=0,enabled:u=!0}=t,{data:y,isLoading:p}=Ue(n),f=y??[],g=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,w=m.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(R=c==null?void 0:c.start)==null?void 0:R.getTime(),(C=c==null?void 0:c.end)==null?void 0:C.getTime()],queryFn:async()=>{const E=await h.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),g),S={};for(const[x,F]of Object.entries(E))F!=null&&(S[x]=F);return S},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&f.length>0,refetchInterval:l>0?l:void 0,staleTime:5e3,placeholderData:m.keepPreviousData});return{data:w.data??void 0,providers:f,isLoading:p||w.isLoading,error:w.error,refetch:w.refetch}},It=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:l=!0}=t,u=I(e),[y,p]=d.useState(null),[f,g]=d.useState(null),[w,R]=d.useState(!1),[C,E]=d.useState(null),S=d.useRef(null),x=d.useCallback(async()=>{if(!(!l||!u||!n||!r||!s))try{const b=await h.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});g(b),R(!0),E(null);const _=T.On(`core/metrics/data/${b}`,O=>{const L=O.data;try{const k=JSON.parse(L);k.results&&p(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),v=T.On(`core/metrics/error/${b}`,O=>{const L=O.data;try{const k=JSON.parse(L);E(k.error||"Unknown error")}catch{E("Failed to parse metric stream error")}});S.current=()=>{_(),v()}}catch(b){E(b instanceof Error?b.message:String(b))}},[u,n,r,s,i,a,c,l]),F=d.useCallback(async()=>{if(f)try{await h.Unsubscribe(f)}catch(b){console.error("Failed to unsubscribe:",b)}S.current&&(S.current(),S.current=null),g(null),R(!1)},[f]);return d.useEffect(()=>()=>{f&&h.Unsubscribe(f).catch(console.error),S.current&&S.current()},[f]),{data:y,subscriptionID:f,isStreaming:w,error:C,start:x,stop:F}},Q=["networker","portforward","all-sessions"];function Tt(){const{showSnackbar:t}=U(),e=m.useQueryClient(),n=m.useQuery({queryKey:[...Q],queryFn:async()=>h.ListAllPortForwardSessions().catch(i=>{if($(i).detail.includes("not found"))return[];throw i}),retry:!1});d.useEffect(()=>{const i=T.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...Q]})}),o=T.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...Q]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=m.useMutation({mutationFn:async i=>h.ClosePortForwardSession(i),onError:N(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...Q]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>T.OpenURL(`http://localhost:${i}`)}}function At({pluginID:t,connectionID:e,resourceID:n}){const r=I(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=U(),o=m.useQueryClient(),a=m.useQuery({queryKey:s,queryFn:async()=>h.FindPortForwardSessions(r,e,D.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const y=$(u);return y.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:y.detail}),[])}),retry:!1}),c=m.useMutation({mutationFn:async({opts:u})=>{const y=D.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 h.StartResourcePortForwardingSession(r,e,y);if(!p)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&T.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:[...Q]})])}}),l=m.useMutation({mutationFn:async({opts:u})=>h.ClosePortForwardSession(u.sessionID),onError:N(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...Q]})])}});return{sessions:a,forward:c.mutateAsync,close:l.mutateAsync}}const Dt=()=>{const t=d.useContext(Oe);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Mt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=I(t),o=m.useQueryClient(),{showSnackbar:a}=U(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:l}=m.useMutation({mutationFn:async p=>h.Update(i,e,n,D.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}=m.useMutation({mutationFn:async(p={})=>h.Delete(i,e,n,D.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:m.useQuery({queryKey:c,queryFn:async()=>h.Get$1(i,e,n,D.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:l,remove:u}},Nt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:m.useQuery({queryKey:e,queryFn:async()=>h.GetResourceAreaComponent(t)})}},kt=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"resource_groups","list"];return{groups:m.useQuery({queryKey:r,queryFn:async()=>h.GetResourceGroups(n,e),retry:!1})}},Lt=({pluginID:t,connectionID:e,searches:n})=>{const r=I(t),s=o=>[r,e,o.key,o.namespaces,"list"];return m.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>h.List(r,e,o.key,D.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},qt=({pluginID:t,resourceKey:e})=>{const n=I(t),r=[n,"resources",e];return{resourceType:m.useQuery({queryKey:r,queryFn:async()=>h.GetResourceType(n,e),retry:!1})}},Ut=({pluginID:t,connectionID:e})=>{const n=I(t),r=[n,"resources","list",e];return{types:m.useQuery({queryKey:r,queryFn:async()=>h.GetResourceTypes(n,e),retry:!1})}};var Y=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qt="Expected a function",$e="__lodash_hash_undefined__",jt="[object Function]",Wt="[object GeneratorFunction]",Gt="[object Symbol]",Kt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Bt=/^\w*$/,Ht=/^\./,zt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Yt=/[\\^$.*+?()[\]{}|]/g,Jt=/\\(\\)?/g,Zt=/^\[object .+?Constructor\]$/,Xt=typeof Y=="object"&&Y&&Y.Object===Object&&Y,Vt=typeof self=="object"&&self&&self.Object===Object&&self,ge=Xt||Vt||Function("return this")();function en(t,e){return t==null?void 0:t[e]}function tn(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var nn=Array.prototype,rn=Function.prototype,Qe=Object.prototype,ie=ge["__core-js_shared__"],Ee=function(){var t=/[^.]+$/.exec(ie&&ie.keys&&ie.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),je=rn.toString,he=Qe.hasOwnProperty,We=Qe.toString,sn=RegExp("^"+je.call(he).replace(Yt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_e=ge.Symbol,on=nn.splice,an=Ge(ge,"Map"),H=Ge(Object,"create"),we=_e?_e.prototype:void 0,be=we?we.toString:void 0;function W(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__=H?H(null):{}}function un(t){return this.has(t)&&delete this.__data__[t]}function ln(t){var e=this.__data__;if(H){var n=e[t];return n===$e?void 0:n}return he.call(e,t)?e[t]:void 0}function dn(t){var e=this.__data__;return H?e[t]!==void 0:he.call(e,t)}function fn(t,e){var n=this.__data__;return n[t]=H&&e===void 0?$e:e,this}W.prototype.clear=cn;W.prototype.delete=un;W.prototype.get=ln;W.prototype.has=dn;W.prototype.set=fn;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function pn(){this.__data__=[]}function yn(t){var e=this.__data__,n=ee(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():on.call(e,n,1),!0}function gn(t){var e=this.__data__,n=ee(e,t);return n<0?void 0:e[n][1]}function hn(t){return ee(this.__data__,t)>-1}function mn(t,e){var n=this.__data__,r=ee(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}K.prototype.clear=pn;K.prototype.delete=yn;K.prototype.get=gn;K.prototype.has=hn;K.prototype.set=mn;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 Sn(){this.__data__={hash:new W,map:new(an||K),string:new W}}function Cn(t){return te(this,t).delete(t)}function En(t){return te(this,t).get(t)}function _n(t){return te(this,t).has(t)}function wn(t,e){return te(this,t).set(t,e),this}G.prototype.clear=Sn;G.prototype.delete=Cn;G.prototype.get=En;G.prototype.has=_n;G.prototype.set=wn;function ee(t,e){for(var n=t.length;n--;)if(Dn(t[n][0],e))return n;return-1}function bn(t,e){e=Fn(e,t)?[e]:xn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Tn(e[n++])];return n&&n==r?t:void 0}function vn(t){if(!Be(t)||On(t))return!1;var e=Mn(t)||tn(t)?sn:Zt;return e.test(An(t))}function Rn(t){if(typeof t=="string")return t;if(Se(t))return be?be.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function xn(t){return Ke(t)?t:In(t)}function te(t,e){var n=t.__data__;return Pn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ge(t,e){var n=en(t,e);return vn(n)?n:void 0}function Fn(t,e){if(Ke(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||Se(t)?!0:Bt.test(t)||!Kt.test(t)||e!=null&&t in Object(e)}function Pn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function On(t){return!!Ee&&Ee in t}var In=me(function(t){t=kn(t);var e=[];return Ht.test(t)&&e.push(""),t.replace(zt,function(n,r,s,i){e.push(s?i.replace(Jt,"$1"):r||n)}),e});function Tn(t){if(typeof t=="string"||Se(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function An(t){if(t!=null){try{return je.call(t)}catch{}try{return t+""}catch{}}return""}function me(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Qt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(me.Cache||G),n}me.Cache=G;function Dn(t,e){return t===e||t!==t&&e!==e}var Ke=Array.isArray;function Mn(t){var e=Be(t)?We.call(t):"";return e==jt||e==Wt}function Be(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Nn(t){return!!t&&typeof t=="object"}function Se(t){return typeof t=="symbol"||Nn(t)&&We.call(t)==Gt}function kn(t){return t==null?"":Rn(t)}function Ln(t,e,n){var r=t==null?void 0:bn(t,e);return r===void 0?n:r}var qn=Ln;const J=$t(qn);function He(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=J(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>J(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function ze(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=d.useRef([]),c=d.useRef(null),l=d.useRef(null),u=d.useRef(s);u.current=s;const y=d.useCallback(()=>{const f=a.current;if(a.current=[],c.current=null,l.current=null,!(f.length===0||!r)){t.setQueryData(e,g=>He(g,f,r));for(const g of f)(g.type==="ADD"||g.type==="UPDATE")&&t.setQueryData(n(g.payload.id,g.payload.namespace),{result:g.payload.data})}},[t,e,n,r]),p=d.useCallback(f=>{a.current.push(f),!(c.current!==null||l.current!==null)&&(u.current===1?c.current=setTimeout(y,o):l.current=requestAnimationFrame(y))},[y,o]);return d.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null)},[]),p}const Un=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=I(t),o=m.useQueryClient(),{showSnackbar:a}=U(),c=d.useMemo(()=>s??[],[s]),l=d.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=d.useCallback((R,C)=>[i,e,n,C,R],[i,e,n]),{mutateAsync:y}=m.useMutation({mutationFn:async R=>h.Create(i,e,n,D.CreateInput.createFrom({input:R.input,namespace:R.namespace??(c.length===1?c[0]:"")})),onSuccess:async R=>{var x;const C=R==null?void 0:R.result;let E="";(x=C==null?void 0:C.metadata)!=null&&x.name?E=C.metadata.name:C!=null&&C.id?E=C.id:C!=null&&C.name?E=C.name:C!=null&&C.ID?E=C.ID:C!=null&&C.Name&&(E=C.Name);const S=E?`Resource ${E} created`:"Resource created";a(S,"success"),await o.invalidateQueries({queryKey:l})},onError:N(a,"Failed to create resource")}),p=m.useQuery({queryKey:l,queryFn:async()=>h.List(i,e,n,D.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(R,C)=>R,retry:!1}),[f,g]=d.useState(P.WatchStateIdle);d.useEffect(()=>T.On(`${i}/${e}/watch/STATE`,C=>{const E=C.data;E.resourceKey===n&&g(E.state)}),[i,e,n]);const w=ze(o,l,u,r,f);return d.useEffect(()=>{if(!r)return;h.SubscribeResource(i,e,n);const R=T.On(`${i}/${e}/${n}/ADD`,S=>w({type:"ADD",payload:S.data})),C=T.On(`${i}/${e}/${n}/UPDATE`,S=>w({type:"UPDATE",payload:S.data})),E=T.On(`${i}/${e}/${n}/DELETE`,S=>w({type:"DELETE",payload:S.data}));return()=>{R(),C(),E(),h.UnsubscribeResource(i,e,n)}},[i,e,n,w]),{resources:p,create:y,watchState:f,isSyncing:f===P.WatchStateSyncing,isSynced:f===P.WatchStateSynced,watchError:f===P.WatchStateError}},$n=({pluginID:t})=>{const e=I(t),{showSnackbar:n}=U(),r=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Create(e,o.connectionID,o.resourceKey,D.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){j(n,o,`Failed to create resource ${a.resourceID}`)}}),s=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Update(e,o.connectionID,o.resourceKey,D.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){j(n,o,`Failed to update resource ${a.resourceID}`)}}),i=m.useMutation({mutationFn:async({opts:o,input:a})=>h.Delete(e,o.connectionID,o.resourceKey,D.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){j(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Qn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=I(t),i=m.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>h.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},jn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=I(t),s=m.useQueryClient(),{showSnackbar:i}=U(),o=m.useMutation({mutationFn:async({actionID:a,id:c="",namespace:l="",params:u={}})=>h.ExecuteAction(r,e,n,a,D.ActionInput.createFrom({id:c,namespace:l,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{j(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Wn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=I(t),s=m.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>h.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}},Gn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=I(t),s=m.useQueryClient(),i=[r,e,"watch-state"],o=d.useRef([]),a=d.useRef(!1),c=d.useCallback(p=>{s.setQueryData(i,f=>{if(!f)return f;const g={...f.resources,[p.resourceKey]:p.state},w={...f.resourceCounts,[p.resourceKey]:p.resourceCount};let R=0,C=0;for(const E of Object.values(g))E===P.WatchStateSynced&&R++,(E===P.WatchStateError||E===P.WatchStateFailed)&&C++;return{...f,resources:g,resourceCounts:w,totalResources:Object.keys(g).length,syncedCount:R,errorCount:C}})},[s,r,e]),l=m.useQuery({queryKey:i,queryFn:async()=>{const p=await h.GetWatchState(r,e);if(!p)throw new Error("Failed to get watch state: null response");const f={};let g=0,w=0;for(const[C,E]of Object.entries(p.resources??{}))E!=null&&(f[C]=E,E===P.WatchStateSynced&&g++,E===P.WatchStateError&&w++);const R={};for(const[C,E]of Object.entries(p.resourceCounts??{}))E!=null&&(R[C]=E);return{connection:p.connectionId,resources:f,resourceCounts:R,totalResources:Object.keys(f).length,syncedCount:g,errorCount:w}},enabled:n&&!!r&&!!e,refetchInterval:p=>{const f=p.state.data;if(!f||f.totalResources===0)return 3e3;let g=0;for(const w of Object.values(f.resources))(w===P.WatchStateSynced||w===P.WatchStateError||w===P.WatchStateStopped||w===P.WatchStateFailed||w===P.WatchStateForbidden||w===P.WatchStateSkipped)&&g++;return g>=f.totalResources?!1:3e3}});d.useEffect(()=>{if(!l.data||a.current)return;a.current=!0;const p=o.current;o.current=[];for(const f of p)c(f)},[l.data,c]),d.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const p=T.On(`${r}/${e}/watch/STATE`,f=>{const g=f.data;a.current?c(g):o.current.push(g)});return()=>{p(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=l.data;let y=0;if(u!=null&&u.resources)for(const p of Object.values(u.resources))(p===P.WatchStateSynced||p===P.WatchStateError||p===P.WatchStateStopped||p===P.WatchStateFailed||p===P.WatchStateForbidden||p===P.WatchStateSkipped)&&y++;return{summary:l,getResourceState:p=>u==null?void 0:u.resources[p],isFullySynced:u?u.totalResources>0&&y===u.totalResources:!1,syncProgress:u&&u.totalResources>0?y/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Kn=()=>{const[t,e]=d.useState(new Map),n=d.useRef(new Map),r=d.useRef(new Map),s=d.useCallback(l=>{const u=l.data,y=pe(u),p=qe(n.current,u),f=ue(p);if(e(g=>{const w=new Map(g);return w.set(y,f),w}),r.current.has(y)&&(clearTimeout(r.current.get(y)),r.current.delete(y)),Z(f)){const g=setTimeout(()=>{e(w=>{const R=new Map(w);return R.delete(y),R}),n.current.delete(y),r.current.delete(y)},5e3);r.current.set(y,g)}},[]);d.useEffect(()=>{const l=T.On("watch/STATE",s);return()=>{l();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(t.values()),o=ke(i),a=i.find(l=>!Z(l))??i[0]??null,c=Le(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},Ye=()=>{const t=d.useContext(fe);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Bn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=I(t),{showSnackbar:s}=U(),{addOperation:i,updateOperation:o}=Ye(),a=d.useRef([]);return d.useEffect(()=>()=>{a.current.forEach(l=>l())},[]),{startStreamAction:d.useCallback(async({actionID:l,id:u,namespace:y,label:p,params:f={}})=>{try{const g=await h.StreamAction(r,e,n,l,D.ActionInput.createFrom({id:u,namespace:y,params:f}));i({id:g,label:p,resourceKey:n,resourceName:u,namespace:y,connectionID:e,status:"running",startedAt:Date.now()});const w=`action/stream/${g}`,R=T.On(w,C=>{var S,x,F,b;const E=C.data;switch(E.type){case"progress":{const _=E.data??{};o(g,{message:_.message,progress:_.ready!==void 0&&_.desired!==void 0?{ready:_.ready,desired:_.desired}:void 0});break}case"complete":o(g,{status:"completed",message:((S=E.data)==null?void 0:S.message)??"Completed",completedAt:Date.now()}),s(((x=E.data)==null?void 0:x.message)??p+" completed","success"),T.Off(w);break;case"error":o(g,{status:"error",message:((F=E.data)==null?void 0:F.message)??"Failed",completedAt:Date.now()}),s(((b=E.data)==null?void 0:b.message)??p+" failed","error"),T.Off(w);break}});return a.current.push(()=>{R(),T.Off(w)}),g}catch(g){throw j(s,g,`Failed to start "${l}"`),g}},[r,e,n,i,o,s])}};function Je(t,e){return`${t}/${e}/graph/CHANGED`}function ne(t,e,n,r){const s=m.useQueryClient(),i=d.useRef(n);i.current=n;const o=JSON.stringify(n);d.useEffect(()=>{if(!r||!t||!e)return;const a=T.On(Je(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const Hn={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function zn(t,e){const n=Hn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function Yn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function Ze(t,e){return e.map(n=>{const r=Yn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const Jn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const l=I(t),u=["RESOURCE_RELATED",l,e,n,s,r,i,o??null],y=a&&!!l&&!!e&&!!n&&!!r;ne(l,e,u,y);const p=m.useQuery({queryKey:u,queryFn:async()=>h.GetRelated(l,e,n,s,r,i,o??null),enabled:y,refetchInterval:c}),f={pluginId:l,connectionId:e,resourceKey:n,id:r,namespace:s},g=p.data??[];return{related:Ze(f,g),edges:g,isLoading:p.isLoading,isFetching:p.isFetching,error:p.error,refetch:p.refetch}},Zn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=I(t),l=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],u=o&&!!c&&!!e&&!!n&&!!r;ne(c,e,l,u);const y=m.useQuery({queryKey:l,queryFn:async()=>h.GetDependencyTree(c,e,n,s,r,i),enabled:u,refetchInterval:a});return{tree:y.data??null,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},Xn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=I(t),l=["RESOURCE_GRAPH",c,e,n,s,r,i,o],u=a&&!!c&&!!e&&!!n&&!!r;ne(c,e,l,u);const y=m.useQuery({queryKey:l,queryFn:async()=>h.GetSubgraph(c,e,n,s,r,i,o),enabled:u});return{graph:y.data??null,isLoading:y.isLoading,isFetching:y.isFetching,error:y.error,refetch:y.refetch}},Vn=()=>{const t=d.useContext(de);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},er=({to:t,withinContext:e,...n})=>{const{pluginId:r}=V();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return d.useMemo(()=>A.jsx(B.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function tr(){const t=B.useNavigate(),e=B.useLocation(),{pluginId:n}=V();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=d.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return d.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class nr{}class rr{constructor(){M(this,"_extensions");M(this,"root");M(this,"pages");M(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 A.jsx(this.root,{});const e=B.createMemoryRouter(this._routes||[]);return A.jsx(B.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 Xe=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(Xe||{});const sr=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]}},or=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=Q;exports.BottomDrawerContext=Fe;exports.ConfirmationModalContext=Oe;exports.ErrorTypes=q;exports.ExtensionPointRegistry=ht;exports.ExtensionPointStore=De;exports.ExtensionProvider=gt;exports.Link=er;exports.OperationsContext=fe;exports.OperationsProvider=ut;exports.PluginContext=X;exports.PluginContextProvider=ot;exports.PluginErrorCode=Xe;exports.PluginWindow=rr;exports.PluginWindowRootProps=nr;exports.RightDrawerContext=Pe;exports.SettingsContext=de;exports.SettingsProvider=at;exports.SnackbarProvider=St;exports.WatchState=P;exports.actionToSnackbar=ve;exports.applyBatch=He;exports.connectionListQueryKey=Ne;exports.createErrorHandler=N;exports.defaultState=xe;exports.formatGroup=or;exports.graphChangedEvent=Je;exports.isCancelledError=le;exports.parseAppError=$;exports.parseResourceKey=sr;exports.relationshipLabel=zn;exports.showAppError=j;exports.toRelatedResources=Ze;exports.useActiveSyncs=Kn;exports.useBottomDrawer=ye;exports.useConfirmationModal=Dt;exports.useConnection=Ct;exports.useConnectionNamespaces=_t;exports.useConnectionStatus=wt;exports.useConnections=Et;exports.useDependencyTree=Zn;exports.useEditorSchemas=Wn;exports.useEventBatcher=ze;exports.useExec=xt;exports.useExecuteAction=jn;exports.useExtensionPoint=yt;exports.useExtensionRegistry=Ae;exports.useLogs=Ft;exports.useMetricProviders=Pt;exports.useMetricProvidersForResource=Ue;exports.useMetricStream=It;exports.useOperations=Ye;exports.usePluginContext=V;exports.usePluginData=vt;exports.usePluginRouter=tr;exports.usePluginSettings=it;exports.usePortForwardSessions=Tt;exports.useRefetchOnGraphChange=ne;exports.useRelatedResources=Jn;exports.useResolvedPluginId=I;exports.useResource=Mt;exports.useResourceActions=Qn;exports.useResourceAreaComponent=Nt;exports.useResourceGraph=Xn;exports.useResourceGroups=kt;exports.useResourceMetrics=Ot;exports.useResourceMutations=$n;exports.useResourcePortForwarder=At;exports.useResourceSearch=Lt;exports.useResourceType=qt;exports.useResourceTypes=Ut;exports.useResources=Un;exports.useRightDrawer=Rt;exports.useSettings=Vn;exports.useSnackbar=U;exports.useStreamAction=Bn;exports.useWatchState=Gn;
1
+ "use strict";var et=Object.defineProperty;var tt=(t,e,n)=>e in t?et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var N=(t,e,n)=>tt(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),l=require("react"),B=require("react-router-dom");require("./index-D_aIcqH0.cjs");const m=require("./graphservice-Cb7rr7SB.cjs"),D=require("./models-CGYstu7u.cjs"),I=require("./events-BTiuwc-0.cjs"),S=require("@tanstack/react-query"),nt=require("@omniviewdev/base-ui"),rt=require("./legacyEnum-DkV5yRdA.cjs"),X=l.createContext(void 0),q={PLUGIN_NOT_FOUND:"omniview:plugin/not-found",PLUGIN_NOT_LOADED:"omniview:plugin/not-loaded",PLUGIN_ALREADY_LOADED:"omniview:plugin/already-loaded",PLUGIN_INSTALL_FAILED:"omniview:plugin/install-failed",PLUGIN_LOAD_FAILED:"omniview:plugin/load-failed",PLUGIN_BUILD_FAILED:"omniview:plugin/build-failed",PLUGIN_COMMITTED_CLEANUP_PENDING:"omniview:plugin/committed-cleanup-pending",PLUGIN_COMMIT_UNCERTAIN:"omniview:plugin/commit-uncertain",SETTINGS_MISSING_CONFIG:"omniview:settings/missing-config",SETTINGS_INVALID_CONFIG:"omniview:settings/invalid-config",RESOURCE_NOT_FOUND:"omniview:resource/not-found",RESOURCE_FORBIDDEN:"omniview:resource/forbidden",RESOURCE_UNAUTHORIZED:"omniview:resource/unauthorized",RESOURCE_CONFLICT:"omniview:resource/conflict",RESOURCE_TIMEOUT:"omniview:resource/timeout",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 st(t){switch(t){case"NOT_FOUND":return{typeUri:q.RESOURCE_NOT_FOUND,status:404};case"FORBIDDEN":return{typeUri:q.RESOURCE_FORBIDDEN,status:403};case"UNAUTHORIZED":return{typeUri:q.RESOURCE_UNAUTHORIZED,status:401};case"CONFLICT":case"ALREADY_EXISTS":return{typeUri:q.RESOURCE_CONFLICT,status:409};case"TIMEOUT":return{typeUri:q.RESOURCE_TIMEOUT,status:408};case"CONNECTION_ERROR":return{typeUri:q.RESOURCE_CONNECTION_ERROR,status:503};case"CERTIFICATE_ERROR":return{typeUri:q.RESOURCE_CERTIFICATE_ERROR,status:502};default:return{typeUri:q.INTERNAL,status:500}}}function $(t){if(t==null)return{type:q.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}=st(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:q.INTERNAL,title:"Error",status:500,detail:e}}function le(t){return t==null?!1:(typeof t=="string"?t:t instanceof Error?t.message:String(t))==="cancelled"?!0:$(t).type===q.CANCELLED}function ve(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 Re(t,e){var s,i;const n=[t.detail,...((s=t.suggestions)==null?void 0:s.map(o=>`• ${o}`))??[]].join(`
2
+ `);return{message:e||(t.title!=="Error"?t.title:"Operation failed"),status:"error",details:n,actions:(i=t.actions)==null?void 0:i.map(ve)}}function j(t,e,n){if(le(e))return;const r=$(e);t(Re(r,n))}function M(t,e){return n=>{if(le(n))return;const r=$(n);t(Re(r,r.title!=="Error"?r.title:e))}}function ot(t){const{children:e,pluginId:n}=t,[r,s]=l.useState({}),[i,o]=l.useState(new D.PluginMeta),[a,c]=l.useState(!1),[d,u]=l.useState(null),p=l.useRef(0),f=l.useRef(0);console.debug("[PluginContextProvider] render",{pluginId:n,metaLoaded:a,metaError:!!d});const y=l.useCallback(()=>{if(n===void 0||n==="")return;const _=++p.current;console.debug(`[PluginContextProvider] fetching settings for "${n}"`),m.PluginValues(n).then(E=>{_===p.current&&(console.debug(`[PluginContextProvider] settings loaded for "${n}"`,Object.keys(E)),s(E))}).catch(E=>{if(_!==p.current)return;const h=$(E);console.error(`[PluginContextProvider] error fetching settings for "${n}":`,h.detail)})},[n]),g=l.useCallback(()=>{if(n===void 0||n===""){console.debug("[PluginContextProvider] skipping meta fetch — empty pluginId");return}const _=++f.current;console.debug(`[PluginContextProvider] fetching meta for "${n}"`),u(null),m.GetPluginMeta(n).then(E=>{_===f.current&&(console.debug(`[PluginContextProvider] meta loaded for "${n}"`,{name:E==null?void 0:E.name,version:E==null?void 0:E.version}),o(E),c(!0))}).catch(E=>{if(_!==f.current)return;const h=$(E);console.error(`[PluginContextProvider] error fetching meta for "${n}":`,h.detail),u(h.detail),c(!1)})},[n]);return l.useEffect(()=>{if(a)return;const _=()=>{y(),g()},E=[I.On("plugin/init_complete",_),I.On("plugin/dev_install_complete",h=>{var w;((w=h.data)==null?void 0:w.id)===n&&_()}),I.On("plugin/inventory_changed",_)];return()=>{for(const h of E)h()}},[n,a,y,g]),l.useEffect(()=>(console.debug(`[PluginContextProvider] useEffect — pluginId changed to "${n}"`),c(!1),u(null),s({}),y(),g(),()=>{++p.current,++f.current}),[n,y,g]),d?A.jsx("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center",padding:24},children:A.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:[A.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[A.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#EF4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("circle",{cx:"12",cy:"12",r:"10"}),A.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),A.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),A.jsx("span",{style:{fontSize:14,fontWeight:600,color:"#FECACA"},children:"Plugin failed to load"})]}),A.jsx("p",{style:{fontSize:13,color:"#A1A1AA",margin:"0 0 16px"},children:d}),A.jsx("button",{onClick:()=>g(),style:{background:"transparent",color:"#F87171",border:"1px solid #7F1D1D",borderRadius:6,padding:"6px 14px",fontSize:13,fontWeight:500,cursor:"pointer"},children:"Retry"})]})}):a?A.jsx(X.Provider,{value:{pluginId:n,settings:r,meta:i},children:e}):A.jsxs("div",{style:{display:"flex",flex:1,alignItems:"center",justifyContent:"center"},children:[A.jsx("div",{style:{width:24,height:24,border:"2px solid #3F3F46",borderTopColor:"#A1A1AA",borderRadius:"50%",animation:"plugin-spin 0.8s linear infinite"}}),A.jsx("style",{children:"@keyframes plugin-spin { to { transform: rotate(360deg); } }"})]})}function V(){const t=l.useContext(X);if(!t)throw new Error("usePluginContext must be used within a PluginContextProvider");return t}function it(){return V().settings}const de=l.createContext(void 0),at=({children:t})=>{const[e,n]=l.useState({}),r=l.useRef(0),s=l.useCallback(()=>{const o=r.current+1;r.current=o,m.Values().then(a=>{o===r.current&&n(a)}).catch(a=>{o===r.current&&console.error("Error fetching settings:",a)})},[]);l.useEffect(()=>{const o=I.On("settings/changed",()=>s());return s(),()=>{r.current+=1,o()}},[s]);const i=l.useCallback(()=>{s()},[s]);return A.jsx(de.Provider,{value:{settings:e,reload:i},children:t})},xe={height:32,focused:0,tabs:[],createTab:()=>{},createTabs:()=>{},updateTab:()=>{},focusTab:()=>{},reorderTab:()=>{},closeTab:()=>{},closeTabs:()=>{},resizeDrawer:()=>{},closeDrawer:()=>{},fullscreenDrawer:()=>{}},Oe=l.createContext(xe),Pe=l.createContext(void 0),Fe=l.createContext(void 0),fe=l.createContext(void 0),ct=3e4,ut=({children:t})=>{const[e,n]=l.useState([]),r=l.useCallback(a=>{n(c=>[a,...c])},[]),s=l.useCallback((a,c)=>{n(d=>d.map(u=>u.id===a?{...u,...c}:u))},[]),i=l.useCallback(a=>{n(c=>c.filter(d=>d.id!==a))},[]);l.useEffect(()=>{const a=[];for(const c of e)if(c.status==="completed"||c.status==="error"){const d=Date.now()-(c.completedAt??c.startedAt),u=Math.max(0,ct-d);a.push(setTimeout(()=>i(c.id),u))}return()=>a.forEach(clearTimeout)},[e,i]);const o=l.useMemo(()=>({operations:e,addOperation:r,updateOperation:s,removeOperation:i}),[e,r,s,i]);return A.jsx(fe.Provider,{value:o,children:t})};var ae=function(t,e){return ae=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])},ae(t,e)};function lt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ae(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var se="Invariant Violation",Ce=Object.setPrototypeOf,dt=Ce===void 0?function(t,e){return t.__proto__=e,t}:Ce,ft=function(t){lt(e,t);function e(n){n===void 0&&(n=se);var r=t.call(this,typeof n=="number"?se+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=se,dt(r,e.prototype),r}return e}(Error);function ce(t,e){if(!t)throw new ft(e)}var Ie=["debug","log","warn","error","silent"],pt=Ie.indexOf("log");function z(t){return function(){if(Ie.indexOf(t)>=pt){var e=console[t]||console.log;return e.apply(console,arguments)}}}(function(t){t.debug=z("debug"),t.log=z("log"),t.warn=z("warn"),t.error=z("error")})(ce||(ce={}));const Te=l.createContext(void 0),Ae=()=>l.useContext(Te);function yt(t){const e=Ae(),n=l.useRef(null),r=e==null?void 0:e.getExtensionPoint(t),s=l.useCallback(o=>{const a=[];return e&&a.push(e.subscribe(o)),r&&a.push(r.subscribe(o)),()=>{for(const c of a)c()}},[e,t,r]),i=l.useCallback(()=>{const o=e==null?void 0:e.getExtensionPoint(t);if(!o){if(n.current&&n.current.store===void 0)return n.current.sentinel;const d={};return n.current={store:void 0,version:-1,sentinel:d},d}const a=n.current;if(a&&a.store===o&&a.version===o.version)return a.sentinel;const c={};return n.current={store:o,version:o.version,sentinel:c},c},[e,t]);return l.useSyncExternalStore(s,i),e==null?void 0:e.getExtensionPoint(t)}const gt=({registry:t,children:e})=>{const n=l.useRef(t);return ce(n.current===t,"You can't change the extension registry after it has been rendered"),A.jsx(Te.Provider,{value:n.current,children:e})},oe=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){N(this,"id");N(this,"mode");N(this,"_pluginId");N(this,"_version",0);N(this,"_contributions",new Map);N(this,"_lookupCache",new Map);N(this,"_matcher");N(this,"_select");N(this,"_listeners",new Set);this.id=e.id,this.mode=e.mode??"multiple",this._pluginId=e.pluginId,this._matcher=e.matcher,this._select=e.select}get pluginId(){return this._pluginId}get version(){return this._version}register(e){if(this._contributions.has(e.id))throw new Error(`Contribution with id "${e.id}" already exists in extension point "${this.id}"`);this._contributions.set(e.id,e),this._invalidateCache(),this._notify()}unregister(e){this._contributions.delete(e)&&(this._invalidateCache(),this._notify())}provide(e){return this._getMatched(e).map(r=>r.value)}list(e){return this._getMatched(e)}listAll(){return Array.from(this._contributions.values())}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeContributionsByPlugin(e){let n=!1;for(const[r,s]of this._contributions)s.plugin===e&&(this._contributions.delete(r),n=!0);n&&(this._invalidateCache(),this._notify())}_getMatched(e){const n=this._getCacheKey(e);if(n!=null){const s=this._lookupCache.get(n);if(s){const i=s.map(o=>this._contributions.get(o)).filter(o=>o!=null);return this._applyMode(i,e)}}let r=this._sortDeterministic(Array.from(this._contributions.values()));return this._matcher&&e!==void 0&&(r=r.filter(s=>this._matcher(s,e))),n!=null&&this._lookupCache.set(n,r.map(s=>s.id)),this._applyMode(r,e)}_applyMode(e,n){if(this.mode==="single"){if(this._select){const r=this._select(e,n);return r?[r]:[]}return e.length>0?[e[0]]:[]}return e}_sortDeterministic(e){return[...e].sort((n,r)=>{const s=n.plugin.localeCompare(r.plugin);return s!==0?s:n.id.localeCompare(r.id)})}_getCacheKey(e){if(e!=null&&typeof e=="object"&&"getCacheKey"in e){const n=e.getCacheKey;if(typeof n=="function")return n()}}_invalidateCache(){this._lookupCache.clear()}_notify(){this._version++;for(const e of this._listeners)e()}}class ht{constructor(e){N(this,"_stores",new Map);N(this,"_storeUnsubs",new Map);N(this,"_listeners",new Set);if(e!=null&&e.initialStores)for(const n of e.initialStores)this.addExtensionPoint(n)}addExtensionPoint(e){const n=oe(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=oe(e);return this._stores.get(n)}hasExtensionPoint(e){const n=oe(e);return this._stores.has(n)}listExtensionPoints(){return Array.from(this._stores.keys())}removeExtensionPoints(e){var r;let n=!1;for(const[s,i]of this._stores)i.pluginId===e&&((r=this._storeUnsubs.get(s))==null||r(),this._storeUnsubs.delete(s),this._stores.delete(s),n=!0);n&&this._notify()}removeContributions(e){for(const n of this._stores.values())n.removeContributionsByPlugin(e);this._notify()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}_notify(){for(const e of this._listeners)e()}}const Ne=l.createContext(void 0),mt={default:"info",info:"info",success:"success",warning:"warning",error:"danger"},St=({children:t})=>{const{toast:e}=nt.useToast(),[n,r]=l.useState([]),s=o=>{r(a=>[...a,o])},i=(o,a,c)=>{const d=typeof o=="object";let u="",p="info",f,y=5e3,g;if(d){if(u=o.message,o.showOnce){if(n.includes(u))return;s(u)}p=o.status,f=o.details,y=o.autoHideDuration??5e3,g=o.actions}else u=o,p=a,f=c;e(f??u,{severity:mt[p]??"info",title:f?u:void 0,duration:y,action:g==null?void 0:g[0]})};return A.jsx(Ne.Provider,{value:{showSnackbar:i},children:t})},U=()=>{const t=l.useContext(Ne);if(t===void 0)throw new Error("useCustomSnackbar must be used within a CustomSnackbarProvider");return t};function T(t){const e=l.useContext(X),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 Ct=({pluginID:t,connectionID:e})=>{const n=T(t),r=S.useQueryClient(),{showSnackbar:s}=U(),i=[n,"connection","detail",e],{mutateAsync:o}=S.useMutation({mutationFn:async()=>m.StartConnection(n,e),onSuccess(p){r.setQueryData(i,p),r.invalidateQueries({queryKey:["EDITOR_SCHEMAS",n,e]})},onError:M(s,"Failed to start connection")}),{mutateAsync:a}=S.useMutation({mutationFn:async()=>m.StopConnection(n,e),onSuccess(p){r.setQueryData(i,p)},onError:M(s,"Failed to stop connection")}),{mutateAsync:c}=S.useMutation({mutationFn:async p=>m.UpdateConnection(n,p),onSuccess(p,{name:f}){s({message:`Connection ${f} successfully updated`,status:"success"}),r.setQueryData(i,p),r.setQueriesData({queryKey:[n,"connection","list"]},y=>y==null?void 0:y.map(g=>g.id===e?p:g))},onError:M(s,"Failed to update connection")}),{mutateAsync:d}=S.useMutation({mutationFn:async()=>m.RemoveConnection(n,e),onSuccess(){s({message:"Connection successfully removed",status:"success"}),r.setQueryData(i,void 0),r.setQueriesData({queryKey:[n,"connection","list"]},p=>p==null?void 0:p.filter(f=>f.id!==e))},onError:M(s,"Failed to remove connection")});return{connection:S.useQuery({queryKey:i,queryFn:async()=>m.GetConnection(n,e)}),startConnection:o,stopConnection:a,updateConnection:c,deleteConnection:d}},Me=t=>[t,"connection","list"],Et=({plugin:t})=>{const e=T(t),n=S.useQueryClient(),{showSnackbar:r}=U(),s=Me(e),{mutateAsync:i}=S.useMutation({mutationFn:async d=>m.StartConnectionWatch(e,d.id),onError:M(r,"Failed to start connection watch")}),{mutateAsync:o}=S.useMutation({mutationFn:async d=>m.StopConnectionWatch(e,d.id),onError:M(r,"Failed to stop connection watch")}),a=l.useCallback(d=>{const u=d.data;console.log("got update to connections",u),n.setQueryData(s,u)},[n,s]);return l.useEffect(()=>{const d=I.On(`${e}/connection/sync`,a);return()=>{d()}},[e,a]),{connections:S.useQuery({queryKey:s,queryFn:async()=>{try{return await m.ListConnections(e)}catch(d){console.log(d),M(r,"Failed to load connections")(d)}return[]},staleTime:3e4,placeholderData:S.keepPreviousData}),startWatch:i,stopWatch:o}},_t=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"connection","namespaces",e];return{namespaces:S.useQuery({queryKey:r,queryFn:async()=>m.GetConnectionNamespaces(n,e)})}},P=rt.withLegacyNames(D.WatchState,"WatchState");function ue(t){const e=Object.values(t.states),n=e.length;let r=0,s=0,i=0,o=0;for(const u of e)u===P.WatchStateSynced&&r++,(u===P.WatchStateError||u===P.WatchStateFailed)&&s++,u===P.WatchStateForbidden&&i++,u===P.WatchStateSkipped&&o++;const a=n-o,c=e.filter(u=>u===P.WatchStateSynced||u===P.WatchStateError||u===P.WatchStateStopped||u===P.WatchStateFailed||u===P.WatchStateForbidden).length,d=a>0?c/a:0;return{pluginID:t.pluginID,connectionID:t.connectionID,totalResources:n,watchedTotal:a,syncedCount:r,errorCount:s,forbiddenCount:i,skippedCount:o,doneCount:c,progress:d}}function Z(t){return t.watchedTotal>0&&t.doneCount>=t.watchedTotal}function ke(t){return t.some(e=>!Z(e))}function Le(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 pe(t){return`${t.pluginId}/${t.connection}`}function qe(t,e){const n=pe(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 wt(){const[t,e]=l.useState(new Set),[n,r]=l.useState({}),[s,i]=l.useState(new Map),o=l.useRef(new Map),[a,c]=l.useState(new Map);l.useEffect(()=>{const C=I.On("plugin/crash_recovery_failed",O=>{const v=O.data,b=v==null?void 0:v.pluginID;b&&c(R=>{const F=new Map(R);return F.set(b,v.error??"Crash recovery failed"),F})}),x=I.On("plugin/recovered",O=>{const v=O.data,b=v==null?void 0:v.pluginID;b&&c(R=>{if(!R.has(b))return R;const F=new Map(R);return F.delete(b),F})});return()=>{C(),x()}},[]),l.useEffect(()=>{m.GetAllConnectionStates().then(C=>{if(!C)return;const x={},O=new Set,v=new Map;for(const[b,R]of Object.entries(C))if(R){x[b]=R.map(F=>F.connection);for(const F of R){if(!F.started)continue;const L=`${b}/${F.connection.id}`;O.add(L);const k={pluginID:b,connectionID:F.connection.id,states:{}};if(F.resources)for(const[re,Ve]of Object.entries(F.resources))k.states[re]=Ve;o.current.set(L,k),v.set(L,ue(k))}}r(x),e(O),i(v)}).catch(()=>{})},[]),l.useEffect(()=>I.On("connection/status",x=>{const O=x.data,v=`${O.pluginID}/${O.connectionID}`;O.status==="DISCONNECTED"?(e(b=>{const R=new Set(b);return R.delete(v),R}),i(b=>{const R=new Map(b);return R.delete(v),R}),o.current.delete(v)):e(b=>{const R=new Set(b);return R.add(v),R}),m.ListAllConnections().then(b=>{if(!b)return;const R={};for(const[F,L]of Object.entries(b))L!=null&&(R[F]=L);r(R)}).catch(()=>{})}),[]);const d=l.useCallback(C=>{const x=C.data,O=pe(x);e(R=>{if(R.has(O))return R;const F=new Set(R);return F.add(O),F});const v=qe(o.current,x),b=ue(v);i(R=>{const F=new Map(R);return F.set(O,b),F})},[]);l.useEffect(()=>I.On("watch/STATE",d),[d]);const u=l.useCallback(async(C,x)=>{await m.StopConnection(C,x)},[]),p=l.useCallback(async(C,x)=>{await m.StartConnectionWatch(C,x)},[]),f=l.useCallback(async C=>{const x=a.get(C);c(O=>{if(!O.has(C))return O;const v=new Map(O);return v.delete(C),v});try{await m.RetryFailedPlugin(C)}catch(O){throw c(v=>{const b=new Map(v);return b.set(C,x??"Reload failed"),b}),O}},[a]),y=[];for(const C of t){const[x,O]=C.split("/",2),b=(n[x]??[]).find(re=>re.id===O),R=s.get(C),F=R!=null&&!Z(R),L=R!=null&&R.errorCount>0,k=a.get(x);y.push({pluginID:x,connectionID:O,name:(b==null?void 0:b.name)??O,avatar:(b==null?void 0:b.avatar)??"",isStarted:!0,sync:R,isSyncing:F,hasErrors:L||k!=null,pluginFailed:k!=null,pluginError:k})}const g=new Map;for(const C of y){const x=g.get(C.pluginID)??[];x.push(C),g.set(C.pluginID,x)}const _=Array.from(s.values()),E=y.filter(C=>C.isSyncing),h=y.filter(C=>C.hasErrors),w=y.filter(C=>C.pluginFailed);return{entries:y,grouped:g,connectedCount:y.length,syncingCount:E.length,errorCount:h.length,failedCount:w.length,hasSyncing:ke(_),aggregateProgress:Le(_),disconnect:u,retryWatch:p,retryPlugin:f}}function bt(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 vt(t,e,n){const r=T(t),s=S.useQueryClient(),i=[r,"data",e],o=S.useQuery({queryKey:i,queryFn:async()=>{const c=await m.Get(r,e);return c==null?n:bt(c,n)?c:(console.warn(`[usePluginData] stored value for "${e}" has unexpected type (expected ${Array.isArray(n)?"array":typeof n}, got ${Array.isArray(c)?"array":typeof c}). Using default.`),n)}}),a=S.useMutation({mutationFn:async c=>{await m.Set(r,e,c)},onMutate:async c=>{await s.cancelQueries({queryKey:i});const d=s.getQueryData(i);return s.setQueryData(i,c),{previous:d}},onError:(c,d,u)=>{(u==null?void 0:u.previous)!==void 0&&s.setQueryData(i,u.previous)},onSettled:()=>{s.invalidateQueries({queryKey:i})}});return{data:o.data??n,update:async c=>{await a.mutateAsync(c)},isLoading:o.isLoading}}const Rt=()=>{const t=l.useContext(Pe);if(!t)throw new Error("useRightDrawer must be used within a RightDrawerProvider");return t},ye=()=>{const t=l.useContext(Oe);if(t===void 0)throw new Error("useBottomDrawer must be used within a BottomDrawerProvider");return t},xt=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r,updateTab:s}=ye();return{createSession:S.useMutation({mutationFn:async({connectionID:o,icon:a,label:c,opts:d})=>{const u=`pending-${crypto.randomUUID()}`;r({id:u,title:c??"Connecting...",variant:"terminal",icon:a??"LuSquareTerminal",properties:{status:"connecting",pluginID:e,connectionID:o,opts:{...d}}});const p=D.SessionOptions.createFrom({command:["/bin/bash"],tty:!0,...d});try{const f=await m.CreateSession(e,o,p);if(!f)throw new Error("Failed to create session: null response");s({id:u},{id:f.id,title:c??`Session ${f.id.substring(0,8)}`,properties:{status:"connected",pluginID:e,connectionID:o,opts:{...d}}})}catch(f){const y=$(f);s({id:u},{properties:{status:"error",error:y.detail,pluginID:e,connectionID:o,opts:{...d}}}),j(n,f,"Failed to start session")}}}).mutateAsync}},Ot=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),{createTab:r}=ye(),s=S.useMutation({mutationFn:async({connectionID:o,resourceKey:a,resourceID:c,resourceData:d,icon:u,label:p,target:f,follow:y=!0,tailLines:g=1e3,params:_})=>{const E=D.CreateSessionOptions.createFrom({resource_key:a,resource_id:c,resource_data:d,options:D.LogSessionOptions.createFrom({target:f??"",follow:y,include_previous:!1,include_timestamps:!0,tail_lines:g,since_seconds:0,limit_bytes:0,include_source_events:!0,params:_??{}})}),h=await m.CreateSession$1(e,o,E);if(!h)throw new Error("Failed to create log session: null response");return r({id:h.id,title:p??`Logs ${h.id.substring(0,8)}`,variant:"logs",icon:u??"LuLogs"}),h},onError:M(n,"Failed to start log session")}),i=S.useMutation({mutationFn:async o=>{await m.CloseSession(o)},onError:M(n,"Failed to close log session")});return{createLogSession:s.mutateAsync,closeLogSession:i.mutateAsync}},Pt=()=>S.useQuery({queryKey:["metric","providers"],queryFn:m.GetProviders,staleTime:3e4}),Ue=t=>S.useQuery({queryKey:["metric","providers",t],queryFn:()=>m.GetProvidersForResource(t),enabled:!!t,staleTime:3e4}),Ft=t=>{var E,h;const{connectionID:e,resourceKey:n,resourceID:r,resourceNamespace:s="",resourceData:i={},metricIDs:o=[],shape:a=0,timeRange:c,refreshInterval:d=0,enabled:u=!0}=t,{data:p,isLoading:f}=Ue(n),y=p??[],g=c?Math.max(Math.floor((c.end.getTime()-c.start.getTime())/250),15e3)*1e6:0,_=S.useQuery({queryKey:["metric","query",e,n,r,s,o,a,(E=c==null?void 0:c.start)==null?void 0:E.getTime(),(h=c==null?void 0:c.end)==null?void 0:h.getTime()],queryFn:async()=>{const w=await m.QueryAll(e,n,r,s,i,o,a,((c==null?void 0:c.start)??new Date(0)).toISOString(),((c==null?void 0:c.end)??new Date(0)).toISOString(),g),C={};for(const[x,O]of Object.entries(w))O!=null&&(C[x]=O);return C},enabled:u&&!!e&&!!n&&(n.startsWith("cluster::")||!!r)&&y.length>0,refetchInterval:d>0?d:void 0,staleTime:5e3,placeholderData:S.keepPreviousData});return{data:_.data??void 0,providers:y,isLoading:f||_.isLoading,error:_.error,refetch:_.refetch}},It=t=>{const{pluginID:e,connectionID:n,resourceKey:r,resourceID:s,resourceNamespace:i="",resourceData:o={},metricIDs:a=[],interval:c=1e4,enabled:d=!0}=t,u=T(e),[p,f]=l.useState(null),[y,g]=l.useState(null),[_,E]=l.useState(!1),[h,w]=l.useState(null),C=l.useRef(null),x=l.useCallback(async()=>{if(!(!d||!u||!n||!r||!s))try{const v=await m.Subscribe(u,n,{resource_key:r,resource_id:s,resource_namespace:i,resource_data:o,metric_ids:a,interval:c*1e6});g(v),E(!0),w(null);const b=I.On(`core/metrics/data/${v}`,F=>{const L=F.data;try{const k=JSON.parse(L);k.results&&f(k.results)}catch(k){console.error("Failed to parse metric stream data:",k)}}),R=I.On(`core/metrics/error/${v}`,F=>{const L=F.data;try{const k=JSON.parse(L);w(k.error||"Unknown error")}catch{w("Failed to parse metric stream error")}});C.current=()=>{b(),R()}}catch(v){w(v instanceof Error?v.message:String(v))}},[u,n,r,s,i,a,c,d]),O=l.useCallback(async()=>{if(y)try{await m.Unsubscribe(y)}catch(v){console.error("Failed to unsubscribe:",v)}C.current&&(C.current(),C.current=null),g(null),E(!1)},[y]);return l.useEffect(()=>()=>{y&&m.Unsubscribe(y).catch(console.error),C.current&&C.current()},[y]),{data:p,subscriptionID:y,isStreaming:_,error:h,start:x,stop:O}},Q=["networker","portforward","all-sessions"];function Tt(){const{showSnackbar:t}=U(),e=S.useQueryClient(),n=S.useQuery({queryKey:[...Q],queryFn:async()=>m.ListAllPortForwardSessions().catch(i=>{if($(i).detail.includes("not found"))return[];throw i}),retry:!1});l.useEffect(()=>{const i=I.On("core/networker/portforward/created",()=>{e.invalidateQueries({queryKey:[...Q]})}),o=I.On("core/networker/portforward/closed",()=>{e.invalidateQueries({queryKey:[...Q]})});return()=>{i(),o()}},[e]);const r=n.data??[],s=S.useMutation({mutationFn:async i=>m.ClosePortForwardSession(i),onError:M(t,"Failed to close port forwarding session"),onSuccess:async()=>{await e.invalidateQueries({queryKey:[...Q]})}});return{sessions:n,activeSessions:r,closeSession:s.mutateAsync,openInBrowser:i=>I.OpenURL(`http://localhost:${i}`)}}function At({pluginID:t,connectionID:e,resourceID:n}){const r=T(t),s=["networker","portforward","sessions",r,e,n],{showSnackbar:i}=U(),o=S.useQueryClient(),a=S.useQuery({queryKey:s,queryFn:async()=>m.FindPortForwardSessions(r,e,D.FindPortForwardSessionRequest.createFrom({resource_id:n,connection_id:e})).catch(u=>{const p=$(u);return p.detail.includes("not found")?[]:(i({message:"Failed to fetch port forward sessions",status:"error",details:p.detail}),[])}),retry:!1}),c=S.useMutation({mutationFn:async({opts:u})=>{const p=D.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??{}}),f=await m.StartResourcePortForwardingSession(r,e,p);if(!f)throw new Error("Failed to start port forwarding: null response");return u.openInBrowser&&I.OpenURL(`http://localhost:${f.local_port}`),f},onError:M(i,"Failed to start port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...Q]})])}}),d=S.useMutation({mutationFn:async({opts:u})=>m.ClosePortForwardSession(u.sessionID),onError:M(i,"Failed to close port forwarding session"),onSuccess:async()=>{await Promise.all([o.invalidateQueries({queryKey:s}),o.invalidateQueries({queryKey:[...Q]})])}});return{sessions:a,forward:c.mutateAsync,close:d.mutateAsync}}const Dt=()=>{const t=l.useContext(Fe);if(!t)throw new Error("useConfirmationModal must be used within a ConfirmationModalProvider");return t},Nt=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s=""})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=U(),c=["RESOURCE",i,e,n,r,s],{mutateAsync:d}=S.useMutation({mutationFn:async f=>m.Update(i,e,n,D.UpdateInput.createFrom({input:f.input,id:r,namespace:s})),onSuccess:async()=>{a(`Resource ${r} updated`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to update resource ${r}`)}),{mutateAsync:u}=S.useMutation({mutationFn:async(f={})=>m.Delete(i,e,n,D.DeleteInput.createFrom({id:r,namespace:s,gracePeriodSeconds:f.gracePeriodSeconds})),onSuccess:async()=>{a(`Resource ${r} deleted`,"success"),await o.invalidateQueries({queryKey:c})},onError:M(a,`Failed to delete resource ${r}`)});return{resource:S.useQuery({queryKey:c,queryFn:async()=>m.Get$1(i,e,n,D.GetInput.createFrom({id:r,namespace:s})),retry:!1}),update:d,remove:u}},Mt=t=>{const e=["component",t.plugin,t.resource,t.area];return{component:S.useQuery({queryKey:e,queryFn:async()=>m.GetResourceAreaComponent(t)})}},kt=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resource_groups","list"];return{groups:S.useQuery({queryKey:r,queryFn:async()=>m.GetResourceGroups(n,e),retry:!1})}},Lt=({pluginID:t,connectionID:e,searches:n})=>{const r=T(t),s=o=>[r,e,o.key,o.namespaces,"list"];return S.useQueries({queries:n.map(o=>({queryKey:s(o),queryFn:async()=>m.List(r,e,o.key,D.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:o.namespaces})).then(a=>a?(console.log(a.result),a.result&&o.postFilter?Object.values(a.result).filter(o.postFilter):Object.values(a.result||{})):[]),retry:!1}))})},qt=({pluginID:t,resourceKey:e})=>{const n=T(t),r=[n,"resources",e];return{resourceType:S.useQuery({queryKey:r,queryFn:async()=>m.GetResourceType(n,e),retry:!1})}},Ut=({pluginID:t,connectionID:e})=>{const n=T(t),r=[n,"resources","list",e];return{types:S.useQuery({queryKey:r,queryFn:async()=>m.GetResourceTypes(n,e),retry:!1})}};var Y=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qt="Expected a function",$e="__lodash_hash_undefined__",jt="[object Function]",Wt="[object GeneratorFunction]",Gt="[object Symbol]",Kt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Bt=/^\w*$/,Ht=/^\./,zt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Yt=/[\\^$.*+?()[\]{}|]/g,Jt=/\\(\\)?/g,Zt=/^\[object .+?Constructor\]$/,Xt=typeof Y=="object"&&Y&&Y.Object===Object&&Y,Vt=typeof self=="object"&&self&&self.Object===Object&&self,ge=Xt||Vt||Function("return this")();function en(t,e){return t==null?void 0:t[e]}function tn(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var nn=Array.prototype,rn=Function.prototype,Qe=Object.prototype,ie=ge["__core-js_shared__"],Ee=function(){var t=/[^.]+$/.exec(ie&&ie.keys&&ie.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),je=rn.toString,he=Qe.hasOwnProperty,We=Qe.toString,sn=RegExp("^"+je.call(he).replace(Yt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_e=ge.Symbol,on=nn.splice,an=Ge(ge,"Map"),H=Ge(Object,"create"),we=_e?_e.prototype:void 0,be=we?we.toString:void 0;function W(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__=H?H(null):{}}function un(t){return this.has(t)&&delete this.__data__[t]}function ln(t){var e=this.__data__;if(H){var n=e[t];return n===$e?void 0:n}return he.call(e,t)?e[t]:void 0}function dn(t){var e=this.__data__;return H?e[t]!==void 0:he.call(e,t)}function fn(t,e){var n=this.__data__;return n[t]=H&&e===void 0?$e:e,this}W.prototype.clear=cn;W.prototype.delete=un;W.prototype.get=ln;W.prototype.has=dn;W.prototype.set=fn;function K(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function pn(){this.__data__=[]}function yn(t){var e=this.__data__,n=ee(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():on.call(e,n,1),!0}function gn(t){var e=this.__data__,n=ee(e,t);return n<0?void 0:e[n][1]}function hn(t){return ee(this.__data__,t)>-1}function mn(t,e){var n=this.__data__,r=ee(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}K.prototype.clear=pn;K.prototype.delete=yn;K.prototype.get=gn;K.prototype.has=hn;K.prototype.set=mn;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 Sn(){this.__data__={hash:new W,map:new(an||K),string:new W}}function Cn(t){return te(this,t).delete(t)}function En(t){return te(this,t).get(t)}function _n(t){return te(this,t).has(t)}function wn(t,e){return te(this,t).set(t,e),this}G.prototype.clear=Sn;G.prototype.delete=Cn;G.prototype.get=En;G.prototype.has=_n;G.prototype.set=wn;function ee(t,e){for(var n=t.length;n--;)if(Dn(t[n][0],e))return n;return-1}function bn(t,e){e=On(e,t)?[e]:xn(e);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Tn(e[n++])];return n&&n==r?t:void 0}function vn(t){if(!Be(t)||Fn(t))return!1;var e=Nn(t)||tn(t)?sn:Zt;return e.test(An(t))}function Rn(t){if(typeof t=="string")return t;if(Se(t))return be?be.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function xn(t){return Ke(t)?t:In(t)}function te(t,e){var n=t.__data__;return Pn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Ge(t,e){var n=en(t,e);return vn(n)?n:void 0}function On(t,e){if(Ke(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||Se(t)?!0:Bt.test(t)||!Kt.test(t)||e!=null&&t in Object(e)}function Pn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Fn(t){return!!Ee&&Ee in t}var In=me(function(t){t=kn(t);var e=[];return Ht.test(t)&&e.push(""),t.replace(zt,function(n,r,s,i){e.push(s?i.replace(Jt,"$1"):r||n)}),e});function Tn(t){if(typeof t=="string"||Se(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function An(t){if(t!=null){try{return je.call(t)}catch{}try{return t+""}catch{}}return""}function me(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(Qt);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var o=t.apply(this,r);return n.cache=i.set(s,o),o};return n.cache=new(me.Cache||G),n}me.Cache=G;function Dn(t,e){return t===e||t!==t&&e!==e}var Ke=Array.isArray;function Nn(t){var e=Be(t)?We.call(t):"";return e==jt||e==Wt}function Be(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Mn(t){return!!t&&typeof t=="object"}function Se(t){return typeof t=="symbol"||Mn(t)&&We.call(t)==Gt}function kn(t){return t==null?"":Rn(t)}function Ln(t,e,n){var r=t==null?void 0:bn(t,e);return r===void 0?n:r}var qn=Ln;const J=$t(qn);function He(t,e,n){const r=t??{result:[],success:!0,totalCount:0},s=[...r.result??[]];for(const i of e){const o=J(i.payload.data,n);switch(i.type){case"ADD":{s.findIndex(c=>J(c,n)===o)===-1&&s.push(i.payload.data);break}case"UPDATE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&(s[a]=i.payload.data);break}case"DELETE":{const a=s.findIndex(c=>J(c,n)===o);a!==-1&&s.splice(a,1);break}}}return{...r,result:s}}function ze(t,e,n,r,s,i){const o=(i==null?void 0:i.syncWindowMs)??500,a=l.useRef([]),c=l.useRef(null),d=l.useRef(null),u=l.useRef(s);u.current=s;const p=l.useCallback(()=>{const y=a.current;if(a.current=[],c.current=null,d.current=null,!(y.length===0||!r)){t.setQueryData(e,g=>He(g,y,r));for(const g of y)(g.type==="ADD"||g.type==="UPDATE")&&t.setQueryData(n(g.payload.id,g.payload.namespace),{result:g.payload.data})}},[t,e,n,r]),f=l.useCallback(y=>{a.current.push(y),!(c.current!==null||d.current!==null)&&(u.current===1?c.current=setTimeout(p,o):d.current=requestAnimationFrame(p))},[p,o]);return l.useEffect(()=>()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)},[]),f}const Un=({pluginID:t,connectionID:e,resourceKey:n,idAccessor:r,namespaces:s})=>{const i=T(t),o=S.useQueryClient(),{showSnackbar:a}=U(),c=l.useMemo(()=>s??[],[s]),d=l.useMemo(()=>[i,e,n,c,"list"],[i,e,n,c]),u=l.useCallback((E,h)=>[i,e,n,h,E],[i,e,n]),{mutateAsync:p}=S.useMutation({mutationFn:async E=>m.Create(i,e,n,D.CreateInput.createFrom({input:E.input,namespace:E.namespace??(c.length===1?c[0]:"")})),onSuccess:async E=>{var x;const h=E==null?void 0:E.result;let w="";(x=h==null?void 0:h.metadata)!=null&&x.name?w=h.metadata.name:h!=null&&h.id?w=h.id:h!=null&&h.name?w=h.name:h!=null&&h.ID?w=h.ID:h!=null&&h.Name&&(w=h.Name);const C=w?`Resource ${w} created`:"Resource created";a(C,"success"),await o.invalidateQueries({queryKey:d})},onError:M(a,"Failed to create resource")}),f=S.useQuery({queryKey:d,queryFn:async()=>m.List(i,e,n,D.ListInput.createFrom({order:[{field:"name",descending:!1}],pagination:{page:1,pageSize:200},namespaces:c})),placeholderData:(E,h)=>E,retry:!1}),[y,g]=l.useState(P.WatchStateIdle);l.useEffect(()=>I.On(`${i}/${e}/watch/STATE`,h=>{const w=h.data;w.resourceKey===n&&g(w.state)}),[i,e,n]);const _=ze(o,d,u,r,y);return l.useEffect(()=>{if(!r)return;m.SubscribeResource(i,e,n);const E=I.On(`${i}/${e}/${n}/ADD`,C=>_({type:"ADD",payload:C.data})),h=I.On(`${i}/${e}/${n}/UPDATE`,C=>_({type:"UPDATE",payload:C.data})),w=I.On(`${i}/${e}/${n}/DELETE`,C=>_({type:"DELETE",payload:C.data}));return()=>{E(),h(),w(),m.UnsubscribeResource(i,e,n)}},[i,e,n,_]),{resources:f,create:p,watchState:y,isSyncing:y===P.WatchStateSyncing,isSynced:y===P.WatchStateSynced,watchError:y===P.WatchStateError}},$n=({pluginID:t})=>{const e=T(t),{showSnackbar:n}=U(),r=S.useMutation({mutationFn:async({opts:o,input:a})=>m.Create(e,o.connectionID,o.resourceKey,D.CreateInput.createFrom({input:a.input,namespace:a.namespace??o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} created`,"success")},onError(o,{opts:a}){j(n,o,`Failed to create resource ${a.resourceID}`)}}),s=S.useMutation({mutationFn:async({opts:o,input:a})=>m.Update(e,o.connectionID,o.resourceKey,D.UpdateInput.createFrom({input:a.input,id:o.resourceID,namespace:o.namespace??""})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} updated`,"success")},onError(o,{opts:a}){j(n,o,`Failed to update resource ${a.resourceID}`)}}),i=S.useMutation({mutationFn:async({opts:o,input:a})=>m.Delete(e,o.connectionID,o.resourceKey,D.DeleteInput.createFrom({id:o.resourceID,namespace:o.namespace??"",gracePeriodSeconds:a.gracePeriodSeconds})),onSuccess:(o,{opts:a})=>{n(`Resource ${a.resourceID} deleted`,"success")},onError(o,{opts:a}){j(n,o,`Failed to delete resource ${a.resourceID}`)}});return{create:r.mutateAsync,update:s.mutateAsync,remove:i.mutateAsync}},Qn=({pluginID:t,connectionID:e,resourceKey:n,enabled:r=!0})=>{const s=T(t),i=S.useQuery({queryKey:["RESOURCE_ACTIONS",s,e,n],queryFn:()=>m.GetActions(s,e,n),enabled:r&&!!s&&!!e&&!!n,staleTime:5*60*1e3});return{actions:i.data??[],isLoading:i.isLoading,error:i.error}},jn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),s=S.useQueryClient(),{showSnackbar:i}=U(),o=S.useMutation({mutationFn:async({actionID:a,id:c="",namespace:d="",params:u={}})=>m.ExecuteAction(r,e,n,a,D.ActionInput.createFrom({id:c,namespace:d,params:u})),onSuccess:a=>{a!=null&&a.message&&i(a.message,"success"),s.invalidateQueries({queryKey:["RESOURCES",r,e,n]})},onError:(a,c)=>{j(i,a,`Failed to execute action "${c.actionID}"`)}});return{executeAction:o.mutateAsync,isExecuting:o.isPending,error:o.error}},Wn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=S.useQuery({queryKey:["EDITOR_SCHEMAS",r,e],queryFn:()=>m.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}},Gn=({pluginID:t,connectionID:e,enabled:n=!0})=>{const r=T(t),s=S.useQueryClient(),i=[r,e,"watch-state"],o=l.useRef([]),a=l.useRef(!1),c=l.useCallback(f=>{s.setQueryData(i,y=>{if(!y)return y;const g={...y.resources,[f.resourceKey]:f.state},_={...y.resourceCounts,[f.resourceKey]:f.resourceCount};let E=0,h=0;for(const w of Object.values(g))w===P.WatchStateSynced&&E++,(w===P.WatchStateError||w===P.WatchStateFailed)&&h++;return{...y,resources:g,resourceCounts:_,totalResources:Object.keys(g).length,syncedCount:E,errorCount:h}})},[s,r,e]),d=S.useQuery({queryKey:i,queryFn:async()=>{const f=await m.GetWatchState(r,e);if(!f)throw new Error("Failed to get watch state: null response");const y={};let g=0,_=0;for(const[h,w]of Object.entries(f.resources??{}))w!=null&&(y[h]=w,w===P.WatchStateSynced&&g++,w===P.WatchStateError&&_++);const E={};for(const[h,w]of Object.entries(f.resourceCounts??{}))w!=null&&(E[h]=w);return{connection:f.connectionId,resources:y,resourceCounts:E,totalResources:Object.keys(y).length,syncedCount:g,errorCount:_}},enabled:n&&!!r&&!!e,refetchInterval:f=>{const y=f.state.data;if(!y||y.totalResources===0)return 3e3;let g=0;for(const _ of Object.values(y.resources))(_===P.WatchStateSynced||_===P.WatchStateError||_===P.WatchStateStopped||_===P.WatchStateFailed||_===P.WatchStateForbidden||_===P.WatchStateSkipped)&&g++;return g>=y.totalResources?!1:3e3}});l.useEffect(()=>{if(!d.data||a.current)return;a.current=!0;const f=o.current;o.current=[];for(const y of f)c(y)},[d.data,c]),l.useEffect(()=>{if(!n||!r||!e)return;a.current=!1,o.current=[];const f=I.On(`${r}/${e}/watch/STATE`,y=>{const g=y.data;a.current?c(g):o.current.push(g)});return()=>{f(),a.current=!1,o.current=[]}},[r,e,n,c]);const u=d.data;let p=0;if(u!=null&&u.resources)for(const f of Object.values(u.resources))(f===P.WatchStateSynced||f===P.WatchStateError||f===P.WatchStateStopped||f===P.WatchStateFailed||f===P.WatchStateForbidden||f===P.WatchStateSkipped)&&p++;return{summary:d,getResourceState:f=>u==null?void 0:u.resources[f],isFullySynced:u?u.totalResources>0&&p===u.totalResources:!1,syncProgress:u&&u.totalResources>0?p/u.totalResources:0,errorCount:(u==null?void 0:u.errorCount)??0}},Kn=()=>{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,p=pe(u),f=qe(n.current,u),y=ue(f);if(e(g=>{const _=new Map(g);return _.set(p,y),_}),r.current.has(p)&&(clearTimeout(r.current.get(p)),r.current.delete(p)),Z(y)){const g=setTimeout(()=>{e(_=>{const E=new Map(_);return E.delete(p),E}),n.current.delete(p),r.current.delete(p)},5e3);r.current.set(p,g)}},[]);l.useEffect(()=>{const d=I.On("watch/STATE",s);return()=>{d();for(const u of r.current.values())clearTimeout(u)}},[s]);const i=Array.from(t.values()),o=ke(i),a=i.find(d=>!Z(d))??i[0]??null,c=Le(i);return{syncs:i,hasSyncing:o,primarySync:a,aggregateProgress:c}},Ye=()=>{const t=l.useContext(fe);if(!t)throw new Error("useOperations must be used within an OperationsProvider");return t},Bn=({pluginID:t,connectionID:e,resourceKey:n})=>{const r=T(t),{showSnackbar:s}=U(),{addOperation:i,updateOperation:o}=Ye(),a=l.useRef([]);return l.useEffect(()=>()=>{a.current.forEach(d=>d())},[]),{startStreamAction:l.useCallback(async({actionID:d,id:u,namespace:p,label:f,params:y={}})=>{try{const g=await m.StreamAction(r,e,n,d,D.ActionInput.createFrom({id:u,namespace:p,params:y}));i({id:g,label:f,resourceKey:n,resourceName:u,namespace:p,connectionID:e,status:"running",startedAt:Date.now()});const _=`action/stream/${g}`,E=I.On(_,h=>{var C,x,O,v;const w=h.data;switch(w.type){case"progress":{const b=w.data??{};o(g,{message:b.message,progress:b.ready!==void 0&&b.desired!==void 0?{ready:b.ready,desired:b.desired}:void 0});break}case"complete":o(g,{status:"completed",message:((C=w.data)==null?void 0:C.message)??"Completed",completedAt:Date.now()}),s(((x=w.data)==null?void 0:x.message)??f+" completed","success"),I.Off(_);break;case"error":o(g,{status:"error",message:((O=w.data)==null?void 0:O.message)??"Failed",completedAt:Date.now()}),s(((v=w.data)==null?void 0:v.message)??f+" failed","error"),I.Off(_);break}});return a.current.push(()=>{E(),I.Off(_)}),g}catch(g){throw j(s,g,`Failed to start "${d}"`),g}},[r,e,n,i,o,s])}};function Je(t,e){return`${t}/${e}/graph/CHANGED`}function ne(t,e,n,r){const s=S.useQueryClient(),i=l.useRef(n);i.current=n;const o=JSON.stringify(n);l.useEffect(()=>{if(!r||!t||!e)return;const a=I.On(Je(t,e),()=>{s.invalidateQueries({queryKey:i.current,exact:!0})});return()=>{a()}},[s,t,e,o,r])}const Hn={owns:{outgoing:"Owns",incoming:"Owned by"},runs_on:{outgoing:"Runs on",incoming:"Running here"},uses:{outgoing:"Uses",incoming:"Used by"},exposes:{outgoing:"Exposes",incoming:"Exposed by"},manages:{outgoing:"Manages",incoming:"Managed by"},member_of:{outgoing:"Member of",incoming:"Members"},selects:{outgoing:"Selects",incoming:"Selected by"}};function zn(t,e){const n=Hn[t];if(n)return n[e];const r=t.replace(/_/g," ");return e==="outgoing"?r:`${r} (incoming)`}function Yn(t,e){return t.pluginId===e.pluginId&&t.connectionId===e.connectionId&&t.resourceKey===e.resourceKey&&t.id===e.id&&(t.namespace??"")===(e.namespace??"")}function Ze(t,e){return e.map(n=>{const r=Yn(n.source,t);return{resource:r?n.target:n.source,type:n.type,direction:r?"outgoing":"incoming",label:n.label}})}const Jn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",direction:i="both",relationshipType:o,enabled:a=!0,refetchInterval:c=!1})=>{const d=T(t),u=["RESOURCE_RELATED",d,e,n,s,r,i,o??null],p=a&&!!d&&!!e&&!!n&&!!r;ne(d,e,u,p);const f=S.useQuery({queryKey:u,queryFn:async()=>m.GetRelated(d,e,n,s,r,i,o??null),enabled:p,refetchInterval:c}),y={pluginId:d,connectionId:e,resourceKey:n,id:r,namespace:s},g=f.data??[];return{related:Ze(y,g),edges:g,isLoading:f.isLoading,isFetching:f.isFetching,error:f.error,refetch:f.refetch}},Zn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",maxDepth:i=3,enabled:o=!0,refetchInterval:a=!1})=>{const c=T(t),d=["RESOURCE_DEPENDENCY_TREE",c,e,n,s,r,i],u=o&&!!c&&!!e&&!!n&&!!r;ne(c,e,d,u);const p=S.useQuery({queryKey:d,queryFn:async()=>m.GetDependencyTree(c,e,n,s,r,i),enabled:u,refetchInterval:a});return{tree:p.data??null,isLoading:p.isLoading,isFetching:p.isFetching,error:p.error,refetch:p.refetch}},Xn=({pluginID:t,connectionID:e,resourceKey:n,resourceID:r,namespace:s="",upDepth:i=2,downDepth:o=3,enabled:a=!0})=>{const c=T(t),d=["RESOURCE_GRAPH",c,e,n,s,r,i,o],u=a&&!!c&&!!e&&!!n&&!!r;ne(c,e,d,u);const p=S.useQuery({queryKey:d,queryFn:async()=>m.GetSubgraph(c,e,n,s,r,i,o),enabled:u});return{graph:p.data??null,isLoading:p.isLoading,isFetching:p.isFetching,error:p.error,refetch:p.refetch}},Vn=()=>{const t=l.useContext(de);if(!t)throw new Error("useSettings must be used within a SettingsProvider");return t},er=({to:t,withinContext:e,...n})=>{const{pluginId:r}=V();r||console.error("Link used outside of a plugin context");const s=`/_plugin/${r}${t.startsWith("/")?"":"/"}${t}`;return l.useMemo(()=>A.jsx(B.Link,{style:{textDecoration:"none",color:"inherit"},...n,to:s}),[n,s])};function tr(){const t=B.useNavigate(),e=B.useLocation(),{pluginId:n}=V();n||console.error("usePluginRouter used outside of a plugin context");const r=`/_plugin/${n}`,s=e.pathname.startsWith(r)?e.pathname.slice(r.length)||"/":e.pathname,i=l.useCallback((o,a)=>{const{...c}=a??{};o.startsWith("/")?t(`${r}${o}`,c):t(o,c)},[t,r]);return l.useMemo(()=>({location:e,navigate:i,pluginPath:s}),[e,i,s])}class nr{}class rr{constructor(){N(this,"_extensions");N(this,"root");N(this,"pages");N(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 A.jsx(this.root,{});const e=B.createMemoryRouter(this._routes||[]);return A.jsx(B.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 Xe=(t=>(t.MISSING_MANIFEST="MISSING_MANIFEST",t.MISSING_PLUGIN="MISSING_PLUGIN",t.MISSING_ENTRYPOINT="MISSING_ENTRYPOINT",t))(Xe||{});const sr=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]}},or=t=>!t||t==="core"?"Core":t.charAt(0).toUpperCase()+t.slice(1);exports.ALL_SESSIONS_KEY=Q;exports.BottomDrawerContext=Oe;exports.ConfirmationModalContext=Fe;exports.ErrorTypes=q;exports.ExtensionPointRegistry=ht;exports.ExtensionPointStore=De;exports.ExtensionProvider=gt;exports.Link=er;exports.OperationsContext=fe;exports.OperationsProvider=ut;exports.PluginContext=X;exports.PluginContextProvider=ot;exports.PluginErrorCode=Xe;exports.PluginWindow=rr;exports.PluginWindowRootProps=nr;exports.RightDrawerContext=Pe;exports.SettingsContext=de;exports.SettingsProvider=at;exports.SnackbarProvider=St;exports.WatchState=P;exports.actionToSnackbar=ve;exports.applyBatch=He;exports.connectionListQueryKey=Me;exports.createErrorHandler=M;exports.defaultState=xe;exports.formatGroup=or;exports.graphChangedEvent=Je;exports.isCancelledError=le;exports.parseAppError=$;exports.parseResourceKey=sr;exports.relationshipLabel=zn;exports.showAppError=j;exports.toRelatedResources=Ze;exports.useActiveSyncs=Kn;exports.useBottomDrawer=ye;exports.useConfirmationModal=Dt;exports.useConnection=Ct;exports.useConnectionNamespaces=_t;exports.useConnectionStatus=wt;exports.useConnections=Et;exports.useDependencyTree=Zn;exports.useEditorSchemas=Wn;exports.useEventBatcher=ze;exports.useExec=xt;exports.useExecuteAction=jn;exports.useExtensionPoint=yt;exports.useExtensionRegistry=Ae;exports.useLogs=Ot;exports.useMetricProviders=Pt;exports.useMetricProvidersForResource=Ue;exports.useMetricStream=It;exports.useOperations=Ye;exports.usePluginContext=V;exports.usePluginData=vt;exports.usePluginRouter=tr;exports.usePluginSettings=it;exports.usePortForwardSessions=Tt;exports.useRefetchOnGraphChange=ne;exports.useRelatedResources=Jn;exports.useResolvedPluginId=T;exports.useResource=Nt;exports.useResourceActions=Qn;exports.useResourceAreaComponent=Mt;exports.useResourceGraph=Xn;exports.useResourceGroups=kt;exports.useResourceMetrics=Ft;exports.useResourceMutations=$n;exports.useResourcePortForwarder=At;exports.useResourceSearch=Lt;exports.useResourceType=qt;exports.useResourceTypes=Ut;exports.useResources=Un;exports.useRightDrawer=Rt;exports.useSettings=Vn;exports.useSnackbar=U;exports.useStreamAction=Bn;exports.useWatchState=Gn;