@skyhook-io/radar-app 1.18.1 → 1.18.2

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 (72) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +23 -8
  3. package/src/api/client.deleteResource.test.tsx +111 -0
  4. package/src/api/client.resourceAudit.test.tsx +57 -0
  5. package/src/api/client.resourcePath.test.ts +107 -0
  6. package/src/api/client.ts +136 -37
  7. package/src/components/capacity/CapacityDemand.tsx +6 -3
  8. package/src/components/capacity/CapacityOverview.tsx +14 -7
  9. package/src/components/capacity/CapacityPoolDetail.tsx +7 -5
  10. package/src/components/capacity/ClusterSchedulingCard.tsx +3 -3
  11. package/src/components/capacity/shared.tsx +9 -5
  12. package/src/components/cnpg/CNPGOverview.tsx +4 -1
  13. package/src/components/cnpg/actions/useCNPGWriteGuard.tsx +1 -0
  14. package/src/components/diagnose/ApplyDialog.test.tsx +10 -0
  15. package/src/components/diagnose/ApplyDialog.tsx +8 -1
  16. package/src/components/diagnose/AssessmentCard.tsx +60 -0
  17. package/src/components/diagnose/DiagnoseSurface.tsx +5 -0
  18. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +62 -2
  19. package/src/components/diagnose/InvestigationEvidenceSections.tsx +6 -5
  20. package/src/components/diagnose/InvestigationView.tsx +47 -13
  21. package/src/components/diagnose/assessmentCopy.ts +11 -0
  22. package/src/components/diagnose/investigationEvidence/adapters/changes.ts +36 -1
  23. package/src/components/diagnose/investigationEvidence/adapters/crossplane.test.tsx +85 -0
  24. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +1 -0
  25. package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +2 -1
  26. package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +2 -1
  27. package/src/components/diagnose/investigationEvidence/adapters/testdata/crossplane-paused-get-resource.json +28 -0
  28. package/src/components/diagnose/investigationEvidence/bodies/index.tsx +2 -0
  29. package/src/components/diagnose/investigationEvidence/bodies/workload.tsx +5 -1
  30. package/src/components/diagnose/investigationEvidence/builder.ts +3 -1
  31. package/src/components/diagnose/investigationEvidence/cardParts.tsx +7 -2
  32. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  33. package/src/components/diagnose/investigationEvidence/observations.ts +7 -3
  34. package/src/components/diagnose/investigationEvidence/projection.test.ts +57 -3
  35. package/src/components/diagnose/investigationEvidencePresentation.test.ts +36 -2
  36. package/src/components/diagnose/investigationEvidencePresentation.ts +33 -8
  37. package/src/components/diagnose/storyParts.test.tsx +53 -0
  38. package/src/components/helm/ChartBrowser.tsx +4 -4
  39. package/src/components/helm/HelmReleaseDrawer.tsx +6 -2
  40. package/src/components/helm/HelmView.tsx +34 -23
  41. package/src/components/helm/InstallWizard.tsx +6 -2
  42. package/src/components/helm/ValuesViewer.test.tsx +1 -0
  43. package/src/components/helm/ValuesViewer.tsx +4 -2
  44. package/src/components/home/ClusterHealthCard.tsx +28 -21
  45. package/src/components/home/MCPSetupDialog.test.tsx +27 -2
  46. package/src/components/home/MCPSetupDialog.tsx +14 -2
  47. package/src/components/home/mcpToolCatalog.ts +29 -2
  48. package/src/components/issues/IssuesPane.render.test.tsx +5 -5
  49. package/src/components/nav/PrimaryNavRail.tsx +34 -2
  50. package/src/components/product-hunt/ProductHuntNotice.render.test.tsx +120 -0
  51. package/src/components/product-hunt/ProductHuntNotice.test.ts +121 -0
  52. package/src/components/product-hunt/ProductHuntNotice.tsx +202 -0
  53. package/src/components/product-hunt/launchWindow.ts +78 -0
  54. package/src/components/product-hunt/useProductHuntRailEntry.test.tsx +76 -0
  55. package/src/components/product-hunt/useProductHuntRailEntry.ts +27 -0
  56. package/src/components/resources/CompositeRenderer.tsx +4 -0
  57. package/src/components/resources/ResourcesView.tsx +1 -1
  58. package/src/components/settings/LocalConnectionSettings.tsx +1 -0
  59. package/src/components/ui/RadarOmnibar.test.tsx +18 -0
  60. package/src/components/ui/RadarOmnibar.tsx +1 -0
  61. package/src/components/ui/SearchSyntaxHelp.test.tsx +39 -0
  62. package/src/components/ui/SearchSyntaxHelp.tsx +23 -2
  63. package/src/components/ui/UpdateNotification.test.tsx +2 -0
  64. package/src/components/ui/UpdateNotification.tsx +32 -5
  65. package/src/components/usage-data/UsageDataPrompt.tsx +19 -1
  66. package/src/components/workload/WorkloadView.tsx +10 -4
  67. package/src/components/workspace/layout.tsx +2 -1
  68. package/src/contexts/CapabilitiesContext.tsx +1 -0
  69. package/src/hooks/useGitOpsWriteGuard.test.tsx +126 -2
  70. package/src/hooks/useGitOpsWriteGuard.ts +25 -3
  71. package/src/hooks/useResolvedGitOpsOwner.ts +14 -9
  72. package/src/index.css +85 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyhook-io/radar-app",
3
- "version": "1.18.1",
3
+ "version": "1.18.2",
4
4
  "description": "Radar's full web UI as a reusable React component. Used by Radar's own binary and by external consumers like Radar Cloud.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/App.tsx CHANGED
@@ -9,7 +9,7 @@ import { DebugOverlay } from './components/DebugOverlay'
9
9
  import { GlobalDiagnoseButton } from './components/diagnose/LocalDiagnoseAction'
10
10
  import { investigationWorkspaceSearch, isInvestigationWorkspacePath, useDiagnoseLayout } from './components/diagnose/DiagnoseContext'
11
11
  import { DiagnoseSurface } from './components/diagnose/DiagnoseSurface'
12
- import { TopologyGraph, TopologySearch, TopologyBreadcrumb, TopologyFilterSidebar, TopologyControls, FreshnessControl, gitOpsRouteForKind, gitOpsRouteForResource, ScopePill, PaneLoader, usePhoneLayout } from '@skyhook-io/k8s-ui'
12
+ import { TopologyGraph, TopologySearch, TopologyBreadcrumb, TopologyFilterSidebar, TopologyControls, FreshnessControl, gitOpsRouteForKind, gitOpsRouteForResource, ScopePill, PaneLoader, usePhoneLayout, PHONE_MEDIA_QUERY } from '@skyhook-io/k8s-ui'
13
13
  import { resetNavigationMap } from '@skyhook-io/k8s-ui/utils/navigation'
14
14
  import { topologyNodeResourceKind } from '@skyhook-io/k8s-ui/utils/topology-neighborhood'
15
15
  import { useAPIResources, findAPIResourceForRoute } from './api/apiResources'
@@ -57,6 +57,8 @@ import { UpdateNotification } from './components/ui/UpdateNotification'
57
57
  import { openWhatsNew, useWhatsNewStatus, WhatsNew } from './components/whats-new/WhatsNew'
58
58
  import { useUsageData, useUsageRecording } from './api/usage-data'
59
59
  import { UsageDataPrompt } from './components/usage-data/UsageDataPrompt'
60
+ import { ProductHuntNotice } from './components/product-hunt/ProductHuntNotice'
61
+ import { useProductHuntRailEntry } from './components/product-hunt/useProductHuntRailEntry'
60
62
  import { ShortcutHelpOverlay } from './components/ui/ShortcutHelpOverlay'
61
63
  import { DiagnosticsOverlay, type DiagnosticsFocus } from './components/ui/DiagnosticsOverlay'
62
64
  import { useEventSource } from './hooks/useEventSource'
@@ -135,7 +137,7 @@ type ExtendedMainView = MainView | 'traffic' | 'cost' | 'capacity' | 'cnpg' | 'w
135
137
  // Views that have been laid out for phone width (640px and below). The rest
136
138
  // keep their desktop width on a phone and scroll sideways; add a view here in
137
139
  // the PR that gives it a phone layout.
138
- const PHONE_READY_VIEWS: ReadonlySet<ExtendedMainView> = new Set<ExtendedMainView>(['issues'])
140
+ const PHONE_READY_VIEWS: ReadonlySet<ExtendedMainView> = new Set<ExtendedMainView>(['issues', 'resources', 'helm', 'home', 'topology', 'capacity'])
139
141
 
140
142
  // Extract view from URL path
141
143
  function getViewFromPath(pathname: string): ExtendedMainView {
@@ -553,6 +555,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
553
555
  }, [location.search, navigate, takeover, goHost, viewMemory, kindFilterStore])
554
556
 
555
557
  const whatsNewStatus = useWhatsNewStatus()
558
+ const productHuntRailEntry = useProductHuntRailEntry()
556
559
 
557
560
  const navigateToPath = useCallback((path: string) => {
558
561
  navigate(withCrossViewParams(path, location.search))
@@ -603,7 +606,11 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
603
606
  const [showPolicyEffect, setShowPolicyEffect] = useState(false)
604
607
  // Topology filter state
605
608
  const [visibleKinds, setVisibleKinds] = useState<Set<NodeKind>>(() => new Set(DEFAULT_VISIBLE_KINDS))
606
- const [filterSidebarCollapsed, setFilterSidebarCollapsed] = useState(false)
609
+ // Phones start with the filters collapsed to their icon rail: expanded, the
610
+ // panel took two thirds of the width from the graph.
611
+ const [filterSidebarCollapsed, setFilterSidebarCollapsed] = useState(
612
+ () => typeof window !== 'undefined' && window.matchMedia(PHONE_MEDIA_QUERY).matches,
613
+ )
607
614
  // Topology node-search → canvas focus request (nonce lets the same node re-focus)
608
615
  const [topologyFocus, setTopologyFocus] = useState<{ id: string; nonce: number } | null>(null)
609
616
  // The topology pane element — the search overlay portals into it so its
@@ -1827,6 +1834,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1827
1834
  onOpenSettings={() => openSettings()}
1828
1835
  accountSlot={<UserMenu variant="rail" pinned={navRailEffectivePinned} />}
1829
1836
  whatsNew={whatsNewStatus.available ? { unread: whatsNewStatus.unread, onOpen: openWhatsNew } : undefined}
1837
+ productHunt={productHuntRailEntry}
1830
1838
  />
1831
1839
  )}
1832
1840
  {/* `relative` makes this column the containing block for the absolute
@@ -2185,8 +2193,12 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2185
2193
  </div>
2186
2194
  </div>
2187
2195
  ) : (
2188
- <>
2189
- {/* Filter sidebar */}
2196
+ // On a phone, its own positioned box so the filter overlay below
2197
+ // anchors to the topology area, not the whole content column.
2198
+ <div className={isMobile ? 'relative flex flex-1 min-w-0 min-h-0' : 'contents'}>
2199
+ {/* Filter sidebar. On phones, expanded it overlays the graph
2200
+ instead of squeezing it. */}
2201
+ <div className={isMobile && !filterSidebarCollapsed ? 'absolute inset-y-0 left-0 z-20 flex shadow-theme-lg' : 'contents'}>
2190
2202
  <TopologyFilterSidebar
2191
2203
  nodes={filterSidebarNodes}
2192
2204
  visibleKinds={visibleKinds}
@@ -2201,6 +2213,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2201
2213
  console.log(`[topology] User requested to show hidden kind: ${kind}`)
2202
2214
  }}
2203
2215
  />
2216
+ </div>
2204
2217
 
2205
2218
  <div ref={setTopologyPane} className="flex-1 relative">
2206
2219
  <TopologyGraph
@@ -2220,8 +2233,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2220
2233
  {/* Overlay row: left column (namespace breadcrumb over search)
2221
2234
  + controls. items-start pins the controls to the top even
2222
2235
  when the breadcrumb grows the left column; w-full so
2223
- justify-between spans the canvas. */}
2224
- <div className="flex w-full items-start justify-between gap-2">
2236
+ justify-between spans the canvas. Phones: the controls
2237
+ wrap below the search instead of running off the canvas. */}
2238
+ <div className="flex w-full items-start justify-between gap-2 phone:flex-wrap">
2225
2239
  <div className="flex flex-col items-start gap-2">
2226
2240
  {namespaces.length === 1 && (
2227
2241
  <TopologyBreadcrumb
@@ -2263,7 +2277,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2263
2277
  </div>
2264
2278
  </TopologyGraph>
2265
2279
  </div>
2266
- </>
2280
+ </div>
2267
2281
  )}
2268
2282
  </>
2269
2283
  )}
@@ -2568,6 +2582,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2568
2582
  {!navCustomization.embedded && <UpdateNotification />}
2569
2583
  {!navCustomization.embedded && <WhatsNew onNavigate={navigateToPath} usageData={usageData.data} />}
2570
2584
  {!navCustomization.embedded && <UsageDataPrompt status={usageData.data} />}
2585
+ {!navCustomization.embedded && <ProductHuntNotice usageData={usageData.data} usageDataPending={usageData.isPending} />}
2571
2586
 
2572
2587
  {/* Bottom Dock for Terminal/Logs */}
2573
2588
  <BottomDock viewNamespaces={namespaces} />
@@ -0,0 +1,111 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, expect, it, vi, type MockInstance } from 'vitest'
6
+ import { useBulkDeleteResources, useDeleteResource } from './client'
7
+
8
+ let success: MockInstance
9
+ let notice: MockInstance
10
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
11
+ beforeEach(() => {
12
+ success = vi.spyOn(console, 'log').mockImplementation(() => {})
13
+ notice = vi.spyOn(console, 'warn').mockImplementation(() => {})
14
+ })
15
+ afterEach(() => {
16
+ vi.unstubAllGlobals()
17
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
18
+ vi.restoreAllMocks()
19
+ })
20
+
21
+ async function remove(responses: (Response | Error)[], bulk: boolean, count = 1, namespace = 'shop') {
22
+ const fetchMock = vi.fn<typeof fetch>(async () => {
23
+ const response = responses.shift()!
24
+ if (response instanceof Error) throw response
25
+ return response
26
+ })
27
+ vi.stubGlobal('fetch', fetchMock)
28
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
29
+ let run: (() => Promise<unknown>) | undefined
30
+ function Probe() {
31
+ const single = useDeleteResource()
32
+ const many = useBulkDeleteResources()
33
+ const items = Array.from({ length: count }, (_, i) => ({ kind: 'configmaps', namespace, name: i ? `app-${i}` : 'app' }))
34
+ run = () => bulk ? many.mutateAsync({ items }) : single.mutateAsync(items[0])
35
+ return null
36
+ }
37
+ const root = createRoot(document.createElement('div'))
38
+ await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
39
+ let failure: unknown
40
+ await act(async () => { try { await run!() } catch (err) { failure = err } })
41
+ act(() => root.unmount())
42
+ client.clear()
43
+ expect(fetchMock).toHaveBeenCalledTimes(count)
44
+ expect(fetchMock.mock.calls[0]?.[0]).toContain(`/api/resources/configmaps/${namespace || "_"}/app`)
45
+ return failure
46
+ }
47
+
48
+
49
+ for (const bulk of [false,true]) {
50
+ const mode=bulk?'bulk':'single'
51
+ it(`${mode}: confirms completed deletion from the current JSON contract`,async()=>{
52
+ expect(await remove([new Response('{}',{status:200})],bulk)).toBeUndefined()
53
+ expect(success).toHaveBeenCalledExactlyOnceWith('[Toast]',bulk?'1 resource deleted':'Resource deleted',undefined)
54
+ expect(notice).not.toHaveBeenCalled()
55
+ })
56
+ for(const body of ['', 'not JSON', 'null', '[]', 'true', '{"pendingFinalizers":[1]}', '{"observationError":false}']) {
57
+ it(`${mode}: an accepted malformed response is unconfirmed`,async()=>{
58
+ expect(await remove([new Response(body,{status:200})],bulk)).toBeUndefined()
59
+ expect(success).not.toHaveBeenCalled()
60
+ expect(JSON.stringify(notice.mock.calls)).toContain('did not confirm cleanup')
61
+ })
62
+ }
63
+ it(`${mode}: an accepted body-read failure is unconfirmed`,async()=>{
64
+ const response = new Response('{}', {status:200})
65
+ vi.spyOn(response, 'text').mockRejectedValue(new Error('response stream interrupted'))
66
+ expect(await remove([response],bulk)).toBeUndefined()
67
+ expect(success).not.toHaveBeenCalled()
68
+ expect(JSON.stringify(notice.mock.calls)).toContain('did not confirm cleanup')
69
+ })
70
+ for(const status of [403,409]) {
71
+ it(`${mode}: rejects HTTP ${status}`,async()=>{
72
+ expect(await remove([new Response(JSON.stringify({error:'request rejected'}),{status})],bulk)).toBeInstanceOf(Error)
73
+ expect(success).not.toHaveBeenCalled();expect(notice).not.toHaveBeenCalled()
74
+ })
75
+ }
76
+ for (const status of [408,500,502,504]) {
77
+ it(`${mode}: HTTP ${status} leaves deletion outcome unknown`,async()=>{
78
+ expect(await remove([new Response(JSON.stringify({error:'request interrupted'}),{status})],bulk)).toBeUndefined()
79
+ expect(success).not.toHaveBeenCalled()
80
+ expect(JSON.stringify(notice.mock.calls)).toContain('inspect before retrying')
81
+ })
82
+ }
83
+ it(`${mode}: a dropped DELETE response leaves outcome unknown`,async()=>{
84
+ expect(await remove([new TypeError('Failed to fetch')],bulk)).toBeUndefined()
85
+ expect(success).not.toHaveBeenCalled()
86
+ expect(JSON.stringify(notice.mock.calls)).toContain('inspect before retrying')
87
+ })
88
+ for(const result of [{deletionTimestamp:'now'}, {deletionTimestamp:'now',pendingFinalizers:['example.com/hold']}, {observationError:'no get permission'}]) {
89
+ it(`${mode}: accepted asynchronous or unconfirmed deletion stays progress`,async()=>{
90
+ expect(await remove([new Response(JSON.stringify(result))],bulk)).toBeUndefined()
91
+ expect(success).not.toHaveBeenCalled();expect(notice).toHaveBeenCalled()
92
+ expect(JSON.stringify(notice.mock.calls)).not.toContain('force delete')
93
+ })
94
+ }
95
+ it(`${mode}: cluster-scoped URLs use the namespace placeholder`,async()=>{
96
+ expect(await remove([new Response('{}')],bulk,1,'')).toBeUndefined()
97
+ })
98
+ }
99
+ it('bulk prioritizes pending finalizers while retaining unconfirmed item details',async()=>{
100
+ expect(await remove([new Response(JSON.stringify({pendingFinalizers:['hold'],deletionTimestamp:'now'})),new Response(JSON.stringify({observationError:'read denied'}))],true,2)).toBeUndefined()
101
+ expect(success).not.toHaveBeenCalled()
102
+ expect(JSON.stringify(notice.mock.calls)).toContain('waiting on finalizers')
103
+ expect(JSON.stringify(notice.mock.calls)).toContain('read denied')
104
+ })
105
+
106
+ it('bulk rejection retains unknown-outcome guidance for another item',async()=>{
107
+ const failure = await remove([new Response(JSON.stringify({error:'denied'}),{status:403}),new TypeError('Failed to fetch')],true,2)
108
+ expect(failure).toBeInstanceOf(Error)
109
+ expect((failure as Error).message).toContain('deletion outcome unknown for 1; inspect before retrying')
110
+ expect(success).not.toHaveBeenCalled()
111
+ })
@@ -0,0 +1,57 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, expect, it, vi } from 'vitest'
6
+ import { useCapabilities, useResourceAudit } from './client'
7
+ import { setApiBase } from './config'
8
+
9
+ afterEach(() => {
10
+ setApiBase('/api')
11
+ vi.unstubAllGlobals()
12
+ })
13
+
14
+ it.each(['supported', 'older', 'failed', 'namespaced'] as const)('avoids premature and duplicate audit requests across discovery: %s', async (state) => {
15
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
16
+ setApiBase('/c/review/api')
17
+ let settle!: (response: Response) => void
18
+ let fail!: (error: Error) => void
19
+ const capabilities = new Promise<Response>((resolve, reject) => { settle = resolve; fail = reject })
20
+ const paths: string[] = []
21
+ vi.stubGlobal('fetch', vi.fn(async (input: string) => {
22
+ const path = new URL(input, 'http://localhost').pathname
23
+ paths.push(path)
24
+ if (path.endsWith('/capabilities')) return capabilities
25
+ return new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } })
26
+ }))
27
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
28
+ const namespace = state === 'namespaced' ? 'shop' : ''
29
+ const kind = namespace ? 'configmaps' : 'persistentvolumes'
30
+ const segment = namespace || (state === 'supported' ? '_' : '')
31
+ const auditPath = `/c/review/api/audit/resource/${kind}/${segment}/pv-a`
32
+ function Probe() {
33
+ const audit = useResourceAudit(kind, namespace, 'pv-a')
34
+ const discovery = useCapabilities()
35
+ return <span>{audit.isSuccess ? 'loaded' : 'waiting'}|{discovery.isPending ? 'pending' : 'settled'}</span>
36
+ }
37
+ const host = document.createElement('div')
38
+ const root = createRoot(host)
39
+ try {
40
+ await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
41
+ await vi.waitFor(() => {
42
+ expect(paths).toEqual(['/c/review/api/capabilities', ...(namespace ? [auditPath] : [])])
43
+ expect(host.textContent).toBe(namespace ? 'loaded|pending' : 'waiting|pending')
44
+ })
45
+ await act(async () => {
46
+ if (state === 'failed') fail(new Error('capabilities unavailable'))
47
+ else settle(new Response(JSON.stringify({ features: state === 'supported' || state === 'namespaced' ? { clusterScopedPlaceholder: true } : {} }), { status: 200, headers: { 'Content-Type': 'application/json' } }))
48
+ })
49
+ await vi.waitFor(() => {
50
+ expect(paths).toEqual(['/c/review/api/capabilities', auditPath])
51
+ expect(host.textContent).toBe('loaded|settled')
52
+ })
53
+ } finally {
54
+ act(() => root.unmount())
55
+ client.clear()
56
+ }
57
+ })
@@ -0,0 +1,107 @@
1
+ // @vitest-environment jsdom
2
+ //
3
+ // Cluster-scoped resources have no namespace. Their per-resource URLs send "_"
4
+ // in its place to survive proxies that merge repeated slashes. Older Radar
5
+ // versions need the empty segment for edit and audit; read, preview and delete
6
+ // already support the placeholder.
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8
+ import { useMutation, useQuery } from '@tanstack/react-query'
9
+ import type { Capabilities } from '@skyhook-io/k8s-ui'
10
+ import {
11
+ fetchResourceWithRelationships,
12
+ useBulkDeleteResources,
13
+ useCascadeDeletePreview,
14
+ useDeleteResource,
15
+ useResourceAudit,
16
+ useUpdateResource,
17
+ } from './client'
18
+
19
+ vi.mock('@tanstack/react-query', async (original) => ({
20
+ ...await original<typeof import('@tanstack/react-query')>(),
21
+ useQuery: vi.fn(() => ({})),
22
+ useMutation: vi.fn(() => ({})),
23
+ useQueryClient: vi.fn(() => ({})),
24
+ }))
25
+
26
+ afterEach(() => { vi.clearAllMocks(); vi.unstubAllGlobals() })
27
+
28
+ function connectedRadar(capabilities: Partial<Capabilities> | undefined) {
29
+ vi.mocked(useQuery).mockImplementation(((options: { queryKey: unknown[] }) =>
30
+ options.queryKey[0] === 'capabilities' ? { data: capabilities, isPending: false } : {}) as unknown as typeof useQuery)
31
+ }
32
+
33
+ function captureRequests() {
34
+ const requests: { method: string; path: string }[] = []
35
+ vi.stubGlobal('fetch', vi.fn(async (input: string, init?: RequestInit) => {
36
+ requests.push({ method: init?.method ?? 'GET', path: new URL(input, 'http://localhost').pathname })
37
+ return init?.method === 'DELETE'
38
+ ? new Response(null, { status: 204 })
39
+ : new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } })
40
+ }))
41
+ return requests
42
+ }
43
+
44
+ type Ref = { kind: string; namespace: string; name: string }
45
+
46
+ type UpdateVars = Parameters<ReturnType<typeof useUpdateResource>['mutateAsync']>[0]
47
+ type DeleteVars = Parameters<ReturnType<typeof useDeleteResource>['mutateAsync']>[0]
48
+ type BulkDeleteVars = Parameters<ReturnType<typeof useBulkDeleteResources>['mutateAsync']>[0]
49
+
50
+ // Runs the requests the hooks rendered in the test registered with the mocked
51
+ // react-query, in the order they were rendered.
52
+ async function requestsFor({ kind, namespace, name }: Ref) {
53
+ const requests = captureRequests()
54
+ const [update, del, bulkDelete] = vi.mocked(useMutation).mock.calls.map(call => call[0].mutationFn)
55
+ const [cascadePreview, audit] = vi.mocked(useQuery).mock.calls
56
+ .map(call => call[0] as { queryKey: unknown[]; queryFn: () => Promise<unknown> })
57
+ .filter(options => options.queryKey[0] !== 'capabilities')
58
+ .map(options => options.queryFn)
59
+ await fetchResourceWithRelationships(kind, namespace, name)
60
+ await (update as (vars: UpdateVars) => Promise<unknown>)({ kind, namespace, name, yaml: `kind: X\nmetadata:\n name: ${name}\n` })
61
+ await (del as (vars: DeleteVars) => Promise<unknown>)({ kind, namespace, name })
62
+ await (bulkDelete as (vars: BulkDeleteVars) => Promise<unknown>)({ items: [{ kind, namespace, name }] })
63
+ await cascadePreview()
64
+ await audit()
65
+ return requests
66
+ }
67
+
68
+ function expected(ref: Ref, readSegment: string, writeSegment: string) {
69
+ const read = `/api/resources/${ref.kind}/${readSegment}/${ref.name}`
70
+ const write = `/api/resources/${ref.kind}/${writeSegment}/${ref.name}`
71
+ return [
72
+ { method: 'GET', path: read },
73
+ { method: 'PUT', path: write },
74
+ { method: 'DELETE', path: read },
75
+ { method: 'DELETE', path: read },
76
+ { method: 'GET', path: `${read}/cascade-preview` },
77
+ { method: 'GET', path: `/api/audit/resource/${ref.kind}/${writeSegment}/${ref.name}` },
78
+ ]
79
+ }
80
+
81
+ const refs: Ref[] = [
82
+ { kind: 'persistentvolumes', namespace: '', name: 'pv-a' },
83
+ { kind: 'nodes', namespace: '', name: 'worker-1' },
84
+ { kind: 'clusterroles', namespace: '', name: 'admin' },
85
+ { kind: 'namespaces', namespace: '', name: 'shop' },
86
+ { kind: 'storageclasses', namespace: '', name: 'standard' },
87
+ { kind: 'clusterissuers', namespace: '', name: 'letsencrypt' },
88
+ { kind: 'configmaps', namespace: 'shop', name: 'app' },
89
+ ]
90
+
91
+ describe.each([
92
+ { radar: 'a Radar that reads "_" as cluster-scoped', capabilities: { features: { clusterScopedPlaceholder: true } }, emptyWriteSegment: '_' },
93
+ { radar: 'an older Radar without the flag', capabilities: { features: {} }, emptyWriteSegment: '' },
94
+ { radar: 'a Radar whose capability request failed', capabilities: undefined, emptyWriteSegment: '' },
95
+ ])('$radar', ({ capabilities, emptyWriteSegment }) => {
96
+ beforeEach(() => connectedRadar(capabilities))
97
+
98
+ it.each(refs)('addresses $kind "$namespace"/$name', async (ref) => {
99
+ const { kind, namespace, name } = ref
100
+ useUpdateResource()
101
+ useDeleteResource()
102
+ useBulkDeleteResources()
103
+ useCascadeDeletePreview(kind, namespace, name, undefined, true)
104
+ useResourceAudit(kind, namespace, name)
105
+ expect(await requestsFor(ref)).toEqual(expected(ref, namespace || '_', namespace || emptyWriteSegment))
106
+ })
107
+ })