@replicated/portal-components 0.0.10 → 0.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/metadata/registry.json +2 -2
- package/components/metadata/registry.md +2 -2
- package/datadog/tracer.d.ts +3 -0
- package/datadog/tracer.js +82 -0
- package/datadog/tracer.ts +101 -0
- package/dist/esm/index.js +93 -66
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/install-card.js +8 -21
- package/dist/esm/install-card.js.map +1 -1
- package/dist/esm/license-card.js +8 -12
- package/dist/esm/license-card.js.map +1 -1
- package/dist/esm/license-details.js +1 -1
- package/dist/esm/license-details.js.map +1 -1
- package/dist/esm/support-card.js +4 -6
- package/dist/esm/support-card.js.map +1 -1
- package/dist/esm/team-settings-card.js +8 -13
- package/dist/esm/team-settings-card.js.map +1 -1
- package/dist/esm/top-nav.js +71 -31
- package/dist/esm/top-nav.js.map +1 -1
- package/dist/esm/update-layout.js +71 -31
- package/dist/esm/update-layout.js.map +1 -1
- package/dist/esm/updates-card.js +8 -14
- package/dist/esm/updates-card.js.map +1 -1
- package/dist/esm/utils/observability/index.js +193 -0
- package/dist/esm/utils/observability/index.js.map +1 -0
- package/dist/index.js +93 -66
- package/dist/index.js.map +1 -1
- package/dist/install-card.js +8 -21
- package/dist/install-card.js.map +1 -1
- package/dist/license-card.js +8 -12
- package/dist/license-card.js.map +1 -1
- package/dist/license-details.js +1 -1
- package/dist/license-details.js.map +1 -1
- package/dist/styles.css +2 -2
- package/dist/support-card.js +4 -6
- package/dist/support-card.js.map +1 -1
- package/dist/team-settings-card.js +8 -13
- package/dist/team-settings-card.js.map +1 -1
- package/dist/top-nav.js +71 -31
- package/dist/top-nav.js.map +1 -1
- package/dist/update-layout.js +71 -31
- package/dist/update-layout.js.map +1 -1
- package/dist/updates-card.js +8 -14
- package/dist/updates-card.js.map +1 -1
- package/dist/utils/observability/index.d.mts +13 -0
- package/dist/utils/observability/index.d.ts +13 -0
- package/dist/utils/observability/index.js +198 -0
- package/dist/utils/observability/index.js.map +1 -0
- package/instrumentation.d.ts +8 -0
- package/instrumentation.js +22 -0
- package/package.json +16 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/index.ts","../../src/components/top-nav.tsx","../../src/components/update-layout.tsx"],"names":["Buffer","jsxs","jsx"],"mappings":";;;;;;;;;;;;AAiBO,IAAM,eAAe,MAAc;AACxC,EAAA,OAAA,CAAQ,QAAQ,GAAA,CAAI,qBAAA,IAAyB,wBAAA,EAA0B,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC3F,CAAA;AAsaA,IAAM,0BAA0B,YAA6C;AAC3E,EAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,eAAA;AAE5B,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,MAAM,mCAAmC,CAAA;AAAA,EACrD;AAEA,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,YAAA,EAAc,CAAA,6BAAA,EAAgC,kBAAA;AAAA,IAC3D;AAAA,GACD,CAAA,CAAA;AAED,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,EAAc;AACzC,IAAA,OAAA,CAAQ,KAAA;AAAA,MACN,qDAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,IAChC,OAAA,EAAS;AAAA,MACP,MAAA,EAAQ;AAAA;AACV,GACD,CAAA;AAED,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gCAAA,EAAmC,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,UAAU,CAAA,CAAA;AAAA,KAC3E;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,IAAA,EAAK;AACpC,EAAA,MAAM,eA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A,EAAM;AACR,YAAA,uBACE,IAAA,CAAC,IAAA,EAAA,EAAiB,IAAA,EAAY,SAAA,EAC5B,QAAA,EAAA;AAAA,8BAAA,GAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAW,QAAA,GAAW,eAAA,GAAkB,iBAC3C,QAAA,EAAA,IAAA,EACH,CAAA;AAAA,8BACA,GAAA,CAAC,UAAM,QAAA,EAAA,KAAA,EAAM;AAAA,aAAA,EAAA,EAJJ,KAKX,CAAA;AAAA,UAEJ;AAEA,UAAA,uBACE,IAAA,CAAC,QAAA,EAAA,EAAmB,SAAA,EAAsB,IAAA,EAAK,QAAA,EAC7C,QAAA,EAAA;AAAA,4BAAA,GAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAW,QAAA,GAAW,eAAA,GAAkB,iBAC3C,QAAA,EAAA,IAAA,EACH,CAAA;AAAA,4BACA,GAAA,CAAC,UAAM,QAAA,EAAA,KAAA,EAAM;AAAA,WAAA,EAAA,EAJF,KAKb,CAAA;AAAA,QAEJ,CAAC,CAAA,EACH;AAAA,OAAA,EACF,CAAA,EACF;AAAA;AAAA,GACF;AAEJ,CAAA;ACpYO,IAAM,YAAA,GAAe,CAAC,EAAE,QAAA,EAAS,KAAyB;AAC/D,EAAA,uBACEC,IAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAU,uBAAA,EACb,QAAA,EAAA;AAAA,oBAAAC,GAAAA,CAAC,MAAA,EAAA,EAAO,WAAA,EAAY,SAAA,EAAU,CAAA;AAAA,oBAC9BA,GAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAU,WAAA,EACb,QAAA,kBAAAA,GAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAU,+BAAA,EACZ,QAAA,EACH,CAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ;AAEA,YAAA,CAAa,WAAA,GAAc,cAAA","file":"update-layout.js","sourcesContent":["/**\n * Light-weight type helpers for defining Server Actions that align with the\n * enterprise portal guardrails. The component library does not implement\n * specific actions, but it exports helpers so downstream portals can describe\n * their actions with consistent metadata.\n */\n\nimport { cache } from \"react\";\nimport { authenticatedFetch } from \"../utils/api-client\";\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Gets the base API origin from environment, with trailing slashes removed.\n */\nexport const getApiOrigin = (): string => {\n return (process.env.REPLICATED_APP_ORIGIN || \"https://replicated.app\").replace(/\\/+$/, \"\");\n};\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport type PortalActionVisibility = \"vendor\" | \"customer\";\n\nexport interface PortalActionContext {\n vendorId: string;\n licenseId: string;\n userId: string;\n signal?: AbortSignal;\n}\n\nexport interface PortalServerActionDefinition<Input, Output> {\n id: string;\n description: string;\n visibility: PortalActionVisibility;\n tags: string[];\n run: (input: Input, context?: PortalActionContext) => Promise<Output>;\n}\n\nexport const defineServerAction = <Input, Output>(\n definition: PortalServerActionDefinition<Input, Output>\n) => definition;\n\nexport interface CreateServiceAccountInput {\n token: string;\n name: string;\n}\n\nexport interface ServiceAccountData {\n id: string;\n customerId: string;\n token: string;\n accountName: string;\n isRevoked: boolean;\n createdAt: string;\n emailAddress: string;\n}\n\nexport interface CreateServiceAccountResult {\n service_account: ServiceAccountData;\n token: string;\n}\n\nexport const createServiceAccount = defineServerAction<\n CreateServiceAccountInput,\n CreateServiceAccountResult\n>({\n id: \"service-account/create\",\n description: \"Creates a service account for installing applications\",\n visibility: \"customer\",\n tags: [\"service-account\", \"install\"],\n async run({ token, name }) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Service account creation requires a session token\");\n }\n\n if (!name || typeof name !== \"string\" || !name.trim()) {\n throw new Error(\"Service account name is required\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/service-account`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] creating service account via %s\",\n endpoint\n );\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({ account_name: name.trim() })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Service account creation failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data: CreateServiceAccountResult = await response.json();\n return data;\n }\n});\n\nexport interface InitiateLoginInput {\n email: string;\n}\n\nexport interface InitiateLoginResult {\n status: \"ok\" | \"saml_redirect\";\n requestedAt: string;\n message: string;\n /** If SAML redirect is required, this contains the info needed to redirect */\n saml?: {\n redirectRequired: true;\n customerId: string;\n email: string;\n appSlug: string;\n };\n}\n\n/**\n * Reference server action for initiating the passwordless login flow.\n * Real portals should replace the simulated delay with a call to their auth API.\n */\nexport const initiateLogin = defineServerAction<\n InitiateLoginInput,\n InitiateLoginResult\n>({\n id: \"auth/initiate-login\",\n description:\n \"Begins the passwordless login flow by dispatching a magic link email.\",\n visibility: \"customer\",\n tags: [\"auth\", \"login\", \"session\"],\n async run(input) {\n const endpoint = `${getApiOrigin()}/v3/login/magic-link`;\n const appSlug = process.env.PORTAL_APP_SLUG;\n if (!appSlug) {\n throw new Error(\"PORTAL_APP_SLUG is not configured\");\n }\n const portalOrigin =\n process.env.PORTAL_ORIGIN ?? \"https://enterprise.replicated.com\";\n const redirectUri = `${portalOrigin.replace(/\\/+$/, \"\")}/${appSlug}/login`;\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({\n app_slug: appSlug,\n email_address: input.email,\n redirect_uri: redirectUri\n })\n });\n\n if (!response.ok) {\n throw new Error(\n `Magic link request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n\n // Check if SAML redirect is required\n if (data.saml_redirect_required && data.saml_customer_id) {\n return {\n status: \"saml_redirect\",\n requestedAt: new Date().toISOString(),\n message: \"SAML authentication required\",\n saml: {\n redirectRequired: true,\n customerId: data.saml_customer_id,\n email: input.email,\n appSlug\n }\n };\n }\n\n return {\n status: \"ok\",\n requestedAt: new Date().toISOString(),\n message: `Magic link requested for ${input.email}`\n };\n }\n});\n\nexport interface VerifyMagicLinkInput {\n nonce: string;\n}\n\nexport interface VerifyMagicLinkResult {\n token: string;\n raw: unknown;\n}\n\nexport interface VerifyMagicLinkError {\n code: \"invalid_code\" | \"expired\" | \"unknown\";\n message: string;\n isExpired?: boolean;\n}\n\nexport const verifyMagicLink = defineServerAction<\n VerifyMagicLinkInput,\n VerifyMagicLinkResult\n>({\n id: \"auth/verify-magic-link\",\n description: \"Verifies the 12-digit code provided via email and returns a JWT.\",\n visibility: \"customer\",\n tags: [\"auth\", \"login\", \"verify\"],\n async run({ nonce }) {\n const endpoint = `${getApiOrigin()}/v3/login/magic-link/verify`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] verifying magic link via %s\",\n endpoint\n );\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({ nonce })\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n // Check if the response indicates an expired link\n try {\n const errorBody = await response.json();\n if (errorBody?.is_expired === true) {\n const error: VerifyMagicLinkError = {\n code: \"expired\",\n message: \"Magic link has expired. A new link has been sent to your email.\",\n isExpired: true\n };\n throw error;\n }\n } catch (parseError) {\n // If we already threw an error, re-throw it\n if ((parseError as VerifyMagicLinkError)?.code === \"expired\") {\n throw parseError;\n }\n // Otherwise fall through to invalid_code\n }\n\n const error: VerifyMagicLinkError = {\n code: \"invalid_code\",\n message: \"Incorrect code, check your email and try again.\"\n };\n throw error;\n }\n const error: VerifyMagicLinkError = {\n code: \"unknown\",\n message: `Magic link verification failed (${response.status} ${response.statusText})`\n };\n throw error;\n }\n\n const payload = await response.json();\n const token = payload?.token ?? payload?.jwt ?? payload?.access_token;\n if (typeof token !== \"string\") {\n throw new Error(\"Magic link verification succeeded but no token returned\");\n }\n\n return { token, raw: payload };\n }\n});\n\nexport interface CustomBrandingResponse {\n brandingData: string;\n documentation: unknown;\n}\n\nexport interface PortalLicenseField {\n key: string;\n label: string;\n value: string | null;\n isSecret?: boolean;\n}\n\nexport interface PortalLicenseDetails {\n id?: string;\n status?: string;\n statusLabel?: string;\n environment?: string;\n expiresAt?: string | null;\n releaseChannels?: string[];\n installMethods?: string[];\n installNotes?: string;\n customerName?: string;\n customerId?: string;\n customerOrganization?: string;\n fields: PortalLicenseField[];\n}\n\nexport interface ListSupportBundlesInput {\n token: string;\n}\n\nexport interface SupportBundleInsight {\n level: string;\n primary: string;\n key?: string;\n detail?: string;\n}\n\nexport interface SupportBundleSummary {\n id: string;\n createdAt?: string;\n status?: string;\n size?: number;\n instanceId?: string;\n insights?: SupportBundleInsight[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ListSupportBundlesResult {\n bundles: SupportBundleSummary[];\n totalCount: number;\n raw: unknown;\n}\n\nexport interface DownloadSupportBundleInput {\n token: string;\n bundleId: string;\n}\n\nexport interface DownloadSupportBundleResult {\n signedUrl: string;\n}\n\nexport interface DeleteSupportBundleInput {\n token: string;\n bundleId: string;\n}\n\nexport interface DeleteSupportBundleResult {\n success: boolean;\n}\n\nexport interface UploadSupportBundleInput {\n token: string;\n appId: string;\n}\n\nexport interface UploadSupportBundleResult {\n uploadUrl: string;\n appId: string;\n}\n\nexport interface UploadSupportBundleCompleteInput {\n token: string;\n appId: string;\n fileContent: ArrayBuffer;\n contentLength: number;\n}\n\nexport interface UploadSupportBundleCompleteResult {\n bundleId: string;\n slug: string;\n}\n\nexport interface FetchLicenseDetailsInput {\n token: string;\n}\n\nexport interface FetchLicenseDetailsResult {\n license: PortalLicenseDetails;\n raw: unknown;\n}\n\nexport interface FetchInstallOptionsInput {\n token: string;\n}\n\nexport interface FetchInstallOptionsResult {\n showLinux: boolean;\n showHelm: boolean;\n}\n\nexport interface FetchLicenseSummaryInput {\n token: string;\n}\n\nexport interface FetchLicenseSummaryResult {\n type: string;\n expiresAt: string | null;\n}\n\nexport interface FetchCustomersInput {\n token: string;\n}\n\nexport interface Customer {\n id: string;\n name: string;\n licenseId: string;\n licenseType: string;\n expiresAt: string;\n isEnterprisePortalEnabled: boolean;\n}\n\nexport interface FetchCustomersResult {\n customers: Customer[];\n}\n\nexport interface SwitchCustomerInput {\n token: string;\n customerId: string;\n}\n\nexport interface SwitchCustomerResult {\n token: string;\n}\n\nexport interface ListReleasesInput {\n token: string;\n}\n\nexport interface ListReleasesResult {\n status: number;\n body: string | null;\n}\n\n/**\n * Internal implementation of fetchCustomBranding.\n * Wrapped with React's cache() to deduplicate calls within a single request.\n */\nconst fetchCustomBrandingImpl = async (): Promise<CustomBrandingResponse> => {\n const appSlug = process.env.PORTAL_APP_SLUG;\n\n if (!appSlug) {\n throw new Error(\"PORTAL_APP_SLUG is not configured\");\n }\n\n const url = `${getApiOrigin()}/v3/custom-branding?app_slug=${encodeURIComponent(\n appSlug\n )}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] fetching custom branding via %s\",\n url\n );\n }\n\n const response = await fetch(url, {\n headers: {\n accept: \"application/json\"\n }\n });\n\n if (!response.ok) {\n throw new Error(\n `Custom branding request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const brandingData = payload?.branding_data;\n\n if (typeof brandingData !== \"string\") {\n throw new Error(\"Custom branding response missing branding_data string\");\n }\n\n return {\n brandingData,\n documentation: payload?.documentation ?? null\n };\n};\n\n/**\n * Fetches custom branding for the portal.\n * This function is cached per-request to avoid duplicate API calls when called\n * from multiple components (e.g., TopNav and page components).\n */\nexport const fetchCustomBranding = cache(fetchCustomBrandingImpl);\n\nexport const decodeJwtPayload = (token: string): Record<string, unknown> => {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new Error(\"Invalid JWT received\");\n }\n\n const payloadSegment = parts[1];\n if (!payloadSegment) {\n throw new Error(\"JWT payload segment missing\");\n }\n\n const padded = payloadSegment.padEnd(\n payloadSegment.length + ((4 - (payloadSegment.length % 4)) % 4),\n \"=\"\n );\n const decoded = Buffer.from(padded, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as Record<string, unknown>;\n};\n\n/**\n * Extracts customer ID from JWT token. Throws if extraction fails.\n */\nexport const getCustomerIdFromToken = (token: string): string => {\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id || payload?.customerId;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n return customerId.trim();\n};\n\nconst resolveSupportBundlesEndpoint = () => {\n const fallback = `${getApiOrigin()}/v3/supportbundles`;\n const explicit = process.env.SUPPORT_BUNDLES_ENDPOINT;\n\n if (!explicit) {\n return new URL(fallback);\n }\n\n try {\n return new URL(explicit);\n } catch (error) {\n console.warn(\n `[portal-components] invalid SUPPORT_BUNDLES_ENDPOINT, using fallback`,\n error\n );\n return new URL(fallback);\n }\n};\n\nexport const listSupportBundles = defineServerAction<\n ListSupportBundlesInput,\n ListSupportBundlesResult\n>({\n id: \"support/list-bundles\",\n description:\n \"Fetches support bundles associated with the customer found in the portal session JWT.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle listing requires a session token\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const url = resolveSupportBundlesEndpoint();\n url.searchParams.set(\"customer_id\", customerId.trim());\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching support bundles via %s\", url);\n }\n\n const response = await authenticatedFetch(url.toString(), {\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (context?.signal?.aborted) {\n throw new Error(\"Support bundles request was aborted\");\n }\n\n if (!response.ok) {\n throw new Error(\n `Support bundles request failed (${response.status} ${response.statusText})`\n );\n }\n\n const raw = await response.json();\n\n const rawRecord =\n raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : undefined;\n\n const parseInsights = (raw: unknown): SupportBundleInsight[] | undefined => {\n if (!Array.isArray(raw)) return undefined;\n return raw\n .filter((i): i is Record<string, unknown> => i && typeof i === \"object\")\n .map((i) => ({\n level: String(i.level ?? \"\"),\n primary: String(i.primary ?? \"\"),\n key: typeof i.key === \"string\" ? i.key : undefined,\n detail: typeof i.detail === \"string\" ? i.detail : undefined\n }));\n };\n\n const bundles: SupportBundleSummary[] = Array.isArray(\n rawRecord?.supportBundles\n )\n ? (rawRecord?.supportBundles as unknown[]).map((item) => {\n if (!item || typeof item !== \"object\") {\n return {\n id: \"\",\n createdAt: undefined,\n status: undefined,\n size: undefined,\n instanceId: undefined,\n insights: undefined,\n metadata: undefined\n };\n }\n\n const record = item as Record<string, unknown>;\n return {\n id: String(record.id ?? \"\"),\n createdAt:\n typeof record.createdAt === \"string\"\n ? (record.createdAt as string)\n : undefined,\n status:\n typeof record.status === \"string\"\n ? (record.status as string)\n : undefined,\n size:\n typeof record.size === \"number\"\n ? record.size\n : undefined,\n instanceId:\n typeof record.instanceId === \"string\"\n ? record.instanceId\n : undefined,\n insights: parseInsights(record.insights),\n metadata: record\n };\n })\n : Array.isArray(raw)\n ? (raw as unknown[]).map((item) => {\n if (!item || typeof item !== \"object\") {\n return {\n id: \"\",\n createdAt: undefined,\n status: undefined,\n size: undefined,\n instanceId: undefined,\n insights: undefined,\n metadata: undefined\n };\n }\n const record = item as Record<string, unknown>;\n return {\n id: String(record.id ?? \"\"),\n createdAt:\n typeof record.createdAt === \"string\"\n ? (record.createdAt as string)\n : undefined,\n status:\n typeof record.status === \"string\"\n ? (record.status as string)\n : undefined,\n size:\n typeof record.size === \"number\"\n ? record.size\n : undefined,\n instanceId:\n typeof record.instanceId === \"string\"\n ? record.instanceId\n : undefined,\n insights: parseInsights(record.insights),\n metadata: record\n };\n })\n : [];\n\n const totalCount = (() => {\n if (rawRecord) {\n if (\n typeof rawRecord.totalCount === \"number\" &&\n Number.isFinite(rawRecord.totalCount)\n ) {\n return rawRecord.totalCount;\n }\n if (Array.isArray(rawRecord.supportBundles)) {\n return rawRecord.supportBundles.length;\n }\n }\n\n if (Array.isArray(raw)) {\n return raw.length;\n }\n\n return bundles.length;\n })();\n\n return {\n bundles,\n totalCount,\n raw\n };\n }\n});\n\nexport const downloadSupportBundle = defineServerAction<\n DownloadSupportBundleInput,\n DownloadSupportBundleResult\n>({\n id: \"support/download-bundle\",\n description: \"Gets a signed URL for downloading a support bundle.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"download\"],\n async run({ token, bundleId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle download requires a session token\");\n }\n\n if (!bundleId || typeof bundleId !== \"string\") {\n throw new Error(\"Support bundle download requires a bundle ID\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/${encodeURIComponent(bundleId)}/download?customer_id=${encodeURIComponent(customerId.trim())}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] getting support bundle download URL via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Support bundle download URL request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n const signedUrl = data?.signedUrl;\n\n if (typeof signedUrl !== \"string\" || !signedUrl) {\n throw new Error(\"Support bundle download response missing signedUrl\");\n }\n\n return { signedUrl };\n }\n});\n\nexport const deleteSupportBundle = defineServerAction<\n DeleteSupportBundleInput,\n DeleteSupportBundleResult\n>({\n id: \"support/delete-bundle\",\n description: \"Deletes a support bundle.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"delete\"],\n async run({ token, bundleId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle deletion requires a session token\");\n }\n\n if (!bundleId || typeof bundleId !== \"string\") {\n throw new Error(\"Support bundle deletion requires a bundle ID\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/${encodeURIComponent(bundleId)}?customer_id=${encodeURIComponent(customerId.trim())}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deleting support bundle via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n if (response.status === 404) {\n throw new Error(\"Support bundle not found\");\n }\n throw new Error(\n `Support bundle deletion failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n return { success: true };\n }\n});\n\nexport const uploadSupportBundle = defineServerAction<\n UploadSupportBundleCompleteInput,\n UploadSupportBundleCompleteResult\n>({\n id: \"support/upload-bundle\",\n description: \"Uploads a support bundle to the server.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"upload\"],\n async run({ token, appId, fileContent, contentLength }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle upload requires a session token\");\n }\n\n if (!appId || typeof appId !== \"string\") {\n throw new Error(\"Support bundle upload requires an app ID\");\n }\n\n if (!fileContent || !(fileContent instanceof ArrayBuffer)) {\n throw new Error(\"Support bundle upload requires file content\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/upload/${encodeURIComponent(appId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] uploading support bundle via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(contentLength)\n },\n body: fileContent,\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Support bundle upload failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n\n return {\n bundleId: data?.bundleId ?? data?.bundle_id ?? \"\",\n slug: data?.slug ?? \"\"\n };\n }\n});\n\n/**\n * Helper to get the upload endpoint URL for client-side uploads with progress tracking.\n * Use this when you need progress indication - call this to get the URL, then upload directly from client.\n */\nexport const getSupportBundleUploadUrl = (appId: string): string => {\n return `${getApiOrigin()}/v3/supportbundle/upload/${encodeURIComponent(appId)}`;\n};\n\nexport const listReleases = defineServerAction<\n ListReleasesInput,\n ListReleasesResult\n>({\n id: \"releases/list\",\n description: \"Lists available releases for the authenticated customer.\",\n visibility: \"customer\",\n tags: [\"releases\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"List releases requires a session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/release-history`;\n\n console.log(\"[portal-components] listReleases request\", {\n endpoint\n });\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n const bodyText = await response\n .text()\n .catch((error) => {\n console.warn(\"[portal-components] listReleases read error\", error);\n return null;\n });\n\n console.log(\"[portal-components] listReleases response\", response.status, bodyText);\n\n if (!response.ok) {\n throw new Error(\n `List releases request failed (${response.status} ${response.statusText})`\n );\n }\n\n return {\n status: response.status,\n body: bodyText\n };\n }\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined => {\n if (value && typeof value === \"object\") {\n return value as Record<string, unknown>;\n }\n return undefined;\n};\n\nconst getValue = (\n record: Record<string, unknown> | undefined,\n key: string\n) => (record ? record[key] : undefined);\n\nconst getString = (\n record: Record<string, unknown> | undefined,\n key: string\n): string | undefined => {\n const value = getValue(record, key);\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getBoolean = (\n record: Record<string, unknown> | undefined,\n key: string\n): boolean | undefined => {\n const value = getValue(record, key);\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n if ([\"true\", \"1\", \"yes\"].includes(normalized)) {\n return true;\n }\n if ([\"false\", \"0\", \"no\"].includes(normalized)) {\n return false;\n }\n }\n return undefined;\n};\n\nconst toDisplayValue = (value: unknown): string | null => {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\nconst normalizeStringArray = (value: unknown): string[] | undefined => {\n if (Array.isArray(value)) {\n const normalized = value\n .map((item) =>\n typeof item === \"string\" ? item.trim() : \"\"\n )\n .filter((item) => item.length > 0);\n return normalized.length ? normalized : undefined;\n }\n\n if (typeof value === \"string\") {\n const normalized = value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n return normalized.length ? normalized : undefined;\n }\n\n return undefined;\n};\n\nconst normalizeLicenseFields = (input: unknown): PortalLicenseField[] => {\n if (!input) {\n return [];\n }\n\n if (Array.isArray(input)) {\n return input\n .map((field, index) => {\n if (!field || typeof field !== \"object\") {\n return null;\n }\n const candidate = field as Record<string, unknown>;\n const key =\n typeof candidate.key === \"string\" && candidate.key.trim().length\n ? candidate.key.trim()\n : typeof candidate.name === \"string\" && candidate.name.trim().length\n ? candidate.name.trim()\n : typeof candidate.label === \"string\" && candidate.label.trim().length\n ? candidate.label.trim()\n : `field-${index}`;\n const label =\n typeof candidate.label === \"string\" && candidate.label.trim().length\n ? candidate.label.trim()\n : typeof candidate.name === \"string\" && candidate.name.trim().length\n ? candidate.name.trim()\n : key;\n let value: unknown =\n candidate.value ?? candidate.data ?? candidate.content;\n if (\n (value === undefined || value === null) &&\n typeof candidate.text === \"string\"\n ) {\n value = candidate.text;\n }\n if (\n (value === undefined || value === null) &&\n typeof candidate.defaultValue === \"string\"\n ) {\n value = candidate.defaultValue;\n }\n const isSecret = Boolean(\n candidate.isSecret ?? candidate.secret ?? candidate.masked\n );\n const resolved = toDisplayValue(value);\n return {\n key,\n label,\n value: resolved,\n isSecret\n } as PortalLicenseField;\n })\n .filter((field): field is PortalLicenseField => Boolean(field));\n }\n\n if (typeof input === \"object\") {\n return Object.entries(input as Record<string, unknown>).map(\n ([key, value]) => {\n let resolvedValue: unknown = value;\n let isSecret = false;\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (\"value\" in obj) {\n resolvedValue = obj.value;\n }\n isSecret = Boolean(obj.isSecret ?? obj.secret ?? obj.masked);\n }\n const normalized = toDisplayValue(resolvedValue);\n return {\n key,\n label: key,\n value: normalized,\n isSecret\n };\n }\n );\n }\n\n return [];\n};\n\nconst extractChannelNames = (input: unknown): string[] | undefined => {\n if (!Array.isArray(input)) {\n return undefined;\n }\n const names = input\n .map((item) => {\n if (typeof item === \"string\") {\n return item.trim();\n }\n const record = asRecord(item);\n if (!record) {\n return null;\n }\n return (\n getString(record, \"name\") ??\n getString(record, \"channelName\") ??\n getString(record, \"channel\") ??\n getString(record, \"channelSlug\") ??\n getString(record, \"slug\") ??\n undefined\n );\n })\n .filter((name): name is string => Boolean(name && name.length));\n return names.length ? names : undefined;\n};\n\nconst normalizeEntitlementFields = (\n fieldsInput: unknown,\n valuesInput: unknown\n): PortalLicenseField[] => {\n const valuesMap = new Map<string, string | null>();\n const assignValue = (key: string | undefined, value: unknown) => {\n if (!key) {\n return;\n }\n valuesMap.set(key, toDisplayValue(value));\n };\n\n if (Array.isArray(valuesInput)) {\n valuesInput.forEach((item) => {\n const record = asRecord(item);\n if (!record) {\n if (typeof item === \"string\") {\n assignValue(item, item);\n }\n return;\n }\n const key =\n getString(record, \"name\") ??\n getString(record, \"field\") ??\n getString(record, \"title\") ??\n getString(record, \"label\") ??\n getString(record, \"slug\") ??\n (() => {\n const idValue = getValue(record, \"id\");\n if (typeof idValue === \"string\" || typeof idValue === \"number\") {\n return String(idValue);\n }\n return undefined;\n })();\n const value =\n getValue(record, \"value\") ??\n getValue(record, \"currentValue\") ??\n getValue(record, \"entitlementValue\") ??\n getValue(record, \"content\") ??\n getValue(record, \"data\") ??\n getValue(record, \"defaultVal\") ??\n getValue(record, \"defaultValue\");\n assignValue(key, value);\n });\n } else if (valuesInput && typeof valuesInput === \"object\") {\n Object.entries(valuesInput as Record<string, unknown>).forEach(\n ([key, value]) => assignValue(key, value)\n );\n }\n\n const normalized: PortalLicenseField[] = [];\n\n if (Array.isArray(fieldsInput)) {\n fieldsInput.forEach((item, index) => {\n const record = asRecord(item);\n if (!record) {\n return;\n }\n const baseKey =\n getString(record, \"name\") ??\n getString(record, \"field\") ??\n getString(record, \"slug\") ??\n `entitlement-${index}`;\n const key = `entitlement-${baseKey}`;\n const label =\n getString(record, \"title\") ??\n getString(record, \"label\") ??\n baseKey;\n const defaultValue =\n getString(record, \"defaultVal\") ??\n getString(record, \"default\") ??\n getString(record, \"defaultValue\");\n const value =\n valuesMap.get(baseKey) ??\n valuesMap.get(label) ??\n defaultValue ??\n null;\n const isSecret = Boolean(\n getBoolean(record, \"secret\") ??\n getBoolean(record, \"isSecret\") ??\n getBoolean(record, \"masked\")\n );\n normalized.push({\n key,\n label,\n value,\n isSecret\n });\n });\n }\n\n valuesMap.forEach((value, key) => {\n const normalizedKey = `entitlement-${key}`;\n if (!normalized.some((field) => field.key === normalizedKey)) {\n normalized.push({\n key: normalizedKey,\n label: key,\n value\n });\n }\n });\n\n return normalized;\n};\n\nconst normalizeLicensePayload = (payload: unknown): PortalLicenseDetails => {\n const payloadRecord = asRecord(payload);\n const rootRecord =\n asRecord(getValue(payloadRecord, \"license\")) ??\n asRecord(getValue(payloadRecord, \"data\")) ??\n payloadRecord ??\n ({} as Record<string, unknown>);\n const sourceRecord =\n asRecord(getValue(rootRecord, \"metadata\")) ?? rootRecord;\n\n const customer =\n asRecord(getValue(rootRecord, \"customer\")) ??\n asRecord(getValue(sourceRecord, \"customer\")) ??\n asRecord(getValue(payloadRecord, \"customer\")) ??\n ({} as Record<string, unknown>);\n\n let releaseChannels =\n normalizeStringArray(\n getValue(rootRecord, \"releaseChannels\") ??\n getValue(sourceRecord, \"releaseChannels\") ??\n getValue(sourceRecord, \"channels\") ??\n getValue(rootRecord, \"channels\") ??\n getValue(sourceRecord, \"channel\") ??\n getValue(rootRecord, \"channel\")\n ) ?? undefined;\n\n if (!releaseChannels) {\n releaseChannels =\n extractChannelNames(getValue(rootRecord, \"channels\")) ??\n extractChannelNames(getValue(sourceRecord, \"channels\")) ??\n undefined;\n }\n\n let installMethods =\n normalizeStringArray(\n getValue(rootRecord, \"installMethods\") ??\n getValue(sourceRecord, \"installMethods\") ??\n getValue(sourceRecord, \"install_options\") ??\n getValue(rootRecord, \"install_options\") ??\n getValue(sourceRecord, \"installOptions\")\n ) ?? undefined;\n\n if (!installMethods || installMethods.length === 0) {\n const resolved: string[] = [];\n const flag = (key: string) =>\n getBoolean(rootRecord, key) ?? getBoolean(sourceRecord, key) ?? false;\n\n if (flag(\"isKotsInstallEnabled\")) {\n resolved.push(\"Replicated KOTS\");\n }\n if (flag(\"isHelmInstallEnabled\")) {\n resolved.push(\"Helm\");\n }\n if (flag(\"isHelmAirgapEnabled\")) {\n resolved.push(\"Helm Airgap\");\n }\n if (\n flag(\"isEmbeddedClusterDownloadEnabled\") ||\n flag(\"isEmbeddedClusterMultiNodeEnabled\")\n ) {\n resolved.push(\"Embedded Cluster\");\n }\n if (flag(\"isKurlInstallEnabled\")) {\n resolved.push(\"kURL\");\n }\n if (flag(\"isGitopsSupported\")) {\n resolved.push(\"GitOps\");\n }\n if (resolved.length) {\n installMethods = Array.from(new Set(resolved));\n }\n }\n\n const expiresAtSource =\n getValue(sourceRecord, \"expiresAt\") ??\n getValue(sourceRecord, \"expireAt\") ??\n getValue(sourceRecord, \"expire_at\") ??\n getValue(sourceRecord, \"expiration\") ??\n getValue(sourceRecord, \"expirationDate\") ??\n getValue(sourceRecord, \"expires_on\") ??\n getValue(rootRecord, \"expiresAt\") ??\n getValue(rootRecord, \"expireAt\") ??\n getValue(rootRecord, \"expire_at\") ??\n getValue(rootRecord, \"expiration\");\n\n const expiresAt =\n typeof expiresAtSource === \"string\" && expiresAtSource.trim().length\n ? expiresAtSource\n : expiresAtSource === null\n ? null\n : undefined;\n\n const baseFields = normalizeLicenseFields(\n getValue(rootRecord, \"additionalFields\") ??\n getValue(sourceRecord, \"additionalFields\") ??\n getValue(sourceRecord, \"fields\") ??\n getValue(rootRecord, \"fields\") ??\n getValue(payloadRecord, \"fields\") ??\n getValue(payloadRecord, \"additional_fields\")\n );\n\n const entitlementFields = normalizeEntitlementFields(\n getValue(rootRecord, \"entitlementFields\") ??\n getValue(sourceRecord, \"entitlementFields\"),\n getValue(rootRecord, \"entitlementValues\") ??\n getValue(sourceRecord, \"entitlementValues\")\n );\n\n const fields = [\n ...baseFields,\n ...entitlementFields.filter(\n (field) => !baseFields.some((existing) => existing.key === field.key)\n )\n ];\n\n const statusFromSource =\n getString(sourceRecord, \"status\") ??\n getString(sourceRecord, \"state\");\n const statusLabelFromSource =\n getString(sourceRecord, \"statusLabel\") ??\n getString(sourceRecord, \"stateLabel\");\n const expiredFlag =\n getBoolean(sourceRecord, \"isExpired\") ??\n getBoolean(rootRecord, \"isExpired\");\n const derivedStatus =\n statusFromSource ??\n (typeof expiredFlag === \"boolean\"\n ? expiredFlag\n ? \"expired\"\n : \"active\"\n : undefined);\n const statusLabel =\n statusLabelFromSource ??\n (derivedStatus\n ? derivedStatus.charAt(0).toUpperCase() + derivedStatus.slice(1)\n : undefined);\n\n const licenseType =\n getString(sourceRecord, \"licenseType\") ??\n getString(rootRecord, \"licenseType\");\n\n const status = derivedStatus;\n\n const license: PortalLicenseDetails = {\n id:\n getString(rootRecord, \"id\") ??\n getString(sourceRecord, \"id\") ??\n getString(sourceRecord, \"licenseId\") ??\n getString(customer, \"licenseId\") ??\n undefined,\n status,\n statusLabel,\n environment:\n getString(sourceRecord, \"environment\") ??\n getString(sourceRecord, \"tier\") ??\n licenseType ??\n undefined,\n expiresAt: expiresAt ?? null,\n releaseChannels: releaseChannels ?? [\n getString(rootRecord, \"channelName\") ??\n getString(rootRecord, \"channel\") ??\n undefined\n ].filter((value): value is string => Boolean(value)),\n installMethods,\n installNotes: getString(sourceRecord, \"installNotes\"),\n customerName:\n getString(sourceRecord, \"customerName\") ??\n getString(customer, \"name\") ??\n undefined,\n customerId:\n getString(sourceRecord, \"customerId\") ??\n getString(customer, \"id\") ??\n getString(rootRecord, \"customerId\") ??\n undefined,\n customerOrganization:\n getString(customer, \"organization\") ??\n getString(sourceRecord, \"customerOrganization\") ??\n getString(rootRecord, \"customerOrganization\") ??\n undefined,\n fields\n };\n\n return license;\n};\n\nexport const fetchLicenseDetails = defineServerAction<\n FetchLicenseDetailsInput,\n FetchLicenseDetailsResult\n>({\n id: \"license/fetch-details\",\n description: \"Fetches the authenticated user's enterprise license details.\",\n visibility: \"customer\",\n tags: [\"license\", \"entitlements\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchLicenseDetails requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const license = normalizeLicensePayload(payload);\n\n return {\n license,\n raw: payload ?? null\n };\n }\n});\n\nexport const fetchInstallOptions = defineServerAction<\n FetchInstallOptionsInput,\n FetchInstallOptionsResult\n>({\n id: \"license/fetch-install-options\",\n description: \"Fetches install options based on license entitlements.\",\n visibility: \"customer\",\n tags: [\"license\", \"install\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchInstallOptions requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n \n // Check for embedded cluster (Linux) and Helm install flags\n const getBoolean = (obj: unknown, key: string): boolean => {\n if (obj && typeof obj === \"object\" && key in obj) {\n const val = (obj as Record<string, unknown>)[key];\n return val === true || val === \"true\";\n }\n return false;\n };\n\n const license = payload?.license ?? payload ?? {};\n const showLinux = getBoolean(license, \"isEmbeddedClusterDownloadEnabled\");\n const showHelm = getBoolean(license, \"isHelmInstallEnabled\");\n\n return {\n showLinux,\n showHelm\n };\n }\n});\n\nexport const fetchLicenseSummary = defineServerAction<\n FetchLicenseSummaryInput,\n FetchLicenseSummaryResult\n>({\n id: \"license/fetch-summary\",\n description: \"Fetches license summary for the license card.\",\n visibility: \"customer\",\n tags: [\"license\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchLicenseSummary requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const license = normalizeLicensePayload(payload);\n\n // Extract type and expiration\n const type = license.environment || \"Unknown\";\n const expiresAt = license.expiresAt || null;\n\n return {\n type,\n expiresAt\n };\n }\n});\n\nexport const fetchCustomers = defineServerAction<\n FetchCustomersInput,\n FetchCustomersResult\n>({\n id: \"auth/fetch-customers\",\n description: \"Fetches the list of customers/teams for the authenticated user.\",\n visibility: \"customer\",\n tags: [\"auth\", \"customers\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchCustomers requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/customers`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch customers request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n \n return {\n customers: payload.customers || []\n };\n }\n});\n\nexport const switchCustomer = defineServerAction<\n SwitchCustomerInput,\n SwitchCustomerResult\n>({\n id: \"auth/switch-customer\",\n description: \"Switches the JWT to a different customer/team.\",\n visibility: \"customer\",\n tags: [\"auth\", \"customers\"],\n async run({ token, customerId }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"switchCustomer requires a non-empty token\");\n }\n \n if (typeof customerId !== \"string\" || customerId.trim().length === 0) {\n throw new Error(\"switchCustomer requires a non-empty customerId\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/select-customer`;\n\n const requestBody = { customer_id: customerId };\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify(requestBody),\n signal: context?.signal\n });\n\n console.log('[portal-components] switchCustomer response status:', response.status);\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('[portal-components] switchCustomer error response:', errorText);\n throw new Error(\n `Switch customer request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const payload = await response.json();\n console.log('[portal-components] switchCustomer response payload:', payload);\n \n // API returns 'jwt' field, not 'token'\n const newToken = payload.jwt || payload.token || token;\n console.log('[portal-components] switchCustomer using token field:', payload.jwt ? 'jwt' : (payload.token ? 'token' : 'fallback'));\n \n return {\n token: newToken\n };\n }\n});\n\n// =============================================================================\n// Security Types\n// =============================================================================\n\nexport type SecurityInstallType = \"linux\" | \"helm\";\n\nexport interface SecurityScanSummary {\n critical: Record<string, string>;\n high: Record<string, string>;\n medium: Record<string, string>;\n low: Record<string, string>;\n}\n\nexport interface SecurityScanWrapper {\n input: string;\n digest?: string;\n last_scanned_at?: string;\n result: SecurityScanSummary;\n not_found?: boolean;\n}\n\nexport interface SecurityReleaseImage {\n image: string;\n sha: string;\n size: number;\n platforms: { os: string; architecture: string }[];\n security?: SecurityScanWrapper;\n}\n\nexport interface GetSecurityInfoInput {\n token: string;\n installType: SecurityInstallType;\n channelSequence: number;\n isAirgap?: boolean;\n}\n\nexport interface GetSecurityInfoResult {\n images: SecurityReleaseImage[];\n}\n\nexport interface SecurityInfoDiff {\n oldTags: string[];\n newTags: string[];\n oldVulns?: SecurityScanSummary;\n newVulns?: SecurityScanSummary;\n added?: SecurityScanSummary;\n removed?: SecurityScanSummary;\n}\n\nexport interface GetSecurityInfoDiffInput {\n token: string;\n installType: SecurityInstallType;\n fromChannelSequence: number;\n toChannelSequence: number;\n isAirgap?: boolean;\n}\n\nexport interface GetSecurityInfoDiffResult {\n from_channel_sequence: number;\n to_channel_sequence: number;\n images: Record<string, SecurityInfoDiff>;\n}\n\nexport interface UnifiedSbom {\n sbom: string;\n sbom_source: string;\n}\n\nexport interface SpdxCreationInfo {\n created: string;\n creators: string[];\n}\n\nexport interface SpdxDocument {\n SPDXID: string;\n spdxVersion: string;\n name: string;\n creationInfo?: SpdxCreationInfo;\n packages?: unknown[];\n files?: unknown[];\n}\n\nexport interface GetSecurityInfoSBOMInput {\n token: string;\n installType: SecurityInstallType;\n channelSequence: number;\n isAirgap?: boolean;\n unifiedSbom?: boolean;\n}\n\nexport interface GetSecurityInfoSBOMResult {\n sboms: {\n unified?: UnifiedSbom;\n };\n}\n\n// =============================================================================\n// Security Actions\n// =============================================================================\n\n/**\n * Fetches security scan (CVE) information for a specific release.\n */\nexport const getSecurityInfo = defineServerAction<\n GetSecurityInfoInput,\n GetSecurityInfoResult\n>({\n id: \"security/get-info\",\n description: \"Fetches CVE security scan results for a specific release\",\n visibility: \"customer\",\n tags: [\"security\", \"cve\"],\n async run({ token, installType, channelSequence, isAirgap = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security info request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n channel_sequence: channelSequence.toString(),\n is_airgap: isAirgap.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security info via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Security info request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoResult;\n }\n});\n\n/**\n * Fetches security diff between two releases (fixed/added CVEs).\n */\nexport const getSecurityInfoDiff = defineServerAction<\n GetSecurityInfoDiffInput,\n GetSecurityInfoDiffResult\n>({\n id: \"security/get-info-diff\",\n description: \"Fetches CVE diff between two releases showing fixed and added vulnerabilities\",\n visibility: \"customer\",\n tags: [\"security\", \"cve\", \"diff\"],\n async run({ token, installType, fromChannelSequence, toChannelSequence, isAirgap = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security info diff request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n from_channel_sequence: fromChannelSequence.toString(),\n to_channel_sequence: toChannelSequence.toString(),\n is_airgap: isAirgap.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info-diff?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security info diff via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Security info diff request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoDiffResult;\n }\n});\n\n/**\n * Fetches SBOM (Software Bill of Materials) for a specific release.\n */\nexport const getSecurityInfoSBOM = defineServerAction<\n GetSecurityInfoSBOMInput,\n GetSecurityInfoSBOMResult\n>({\n id: \"security/get-sbom\",\n description: \"Fetches Software Bill of Materials (SBOM) for a specific release\",\n visibility: \"customer\",\n tags: [\"security\", \"sbom\"],\n async run({ token, installType, channelSequence, isAirgap = false, unifiedSbom = true }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security SBOM request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n channel_sequence: channelSequence.toString(),\n is_airgap: isAirgap.toString(),\n unified_sbom: unifiedSbom.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info-sbom?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security SBOM via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n // Handle 204 No Content response\n if (response.status === 204) {\n return { sboms: {} };\n }\n\n if (!response.ok) {\n throw new Error(\n `Security SBOM request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoSBOMResult;\n }\n});\n\n// =============================================================================\n// Dashboard Types\n// =============================================================================\n\nexport interface FetchTeamStatsInput {\n token: string;\n}\n\nexport interface TeamUser {\n id: string;\n email: string;\n name?: string;\n createdAt?: string;\n}\n\nexport interface ServiceAccountSummary {\n id: string;\n accountName: string;\n customerId: string;\n isRevoked: boolean;\n createdAt: string;\n}\n\nexport interface FetchTeamStatsResult {\n userCount: number;\n serviceAccountCount: number;\n}\n\nexport interface FetchDashboardInstancesInput {\n token: string;\n}\n\nexport interface FetchDashboardInstancesResult {\n onlineActiveCount: number;\n airgapCount: number;\n onlineUpdates: number;\n airgapUpdates: number;\n}\n\n// =============================================================================\n// Dashboard Actions\n// =============================================================================\n\n/**\n * Fetches team statistics including user count and service account count.\n * Used by the Team Settings dashboard card.\n */\nexport const fetchTeamStats = defineServerAction<\n FetchTeamStatsInput,\n FetchTeamStatsResult\n>({\n id: \"dashboard/fetch-team-stats\",\n description: \"Fetches user and service account counts for the dashboard\",\n visibility: \"customer\",\n tags: [\"dashboard\", \"team\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Team stats request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const origin = getApiOrigin();\n\n // Fetch users count\n let userCount = 0;\n try {\n const usersUrl = `${origin}/v3/users?exclude_invites=false&customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching team users via %s\", usersUrl);\n }\n\n const usersResponse = await authenticatedFetch(usersUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (usersResponse.ok) {\n const usersData = await usersResponse.json();\n userCount = Array.isArray(usersData.users) ? usersData.users.length : 0;\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching users:\", error);\n }\n\n // Fetch service accounts count\n let serviceAccountCount = 0;\n try {\n const saUrl = `${origin}/v3/service-accounts?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching service accounts via %s\", saUrl);\n }\n\n const saResponse = await authenticatedFetch(saUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (saResponse.ok) {\n const saData = await saResponse.json();\n serviceAccountCount = Array.isArray(saData.serviceAccounts) \n ? saData.serviceAccounts.length \n : 0;\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching service accounts:\", error);\n }\n\n return {\n userCount,\n serviceAccountCount\n };\n }\n});\n\n/**\n * Fetches instance counts and available updates for the dashboard.\n * Used by the Updates dashboard card.\n */\nexport const fetchDashboardInstances = defineServerAction<\n FetchDashboardInstancesInput,\n FetchDashboardInstancesResult\n>({\n id: \"dashboard/fetch-instances\",\n description: \"Fetches instance counts and update availability for the dashboard\",\n visibility: \"customer\",\n tags: [\"dashboard\", \"instances\", \"updates\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Dashboard instances request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const origin = getApiOrigin();\n\n // Fetch instances\n const instancesUrl = `${origin}/v3/instances?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching instances via %s\", instancesUrl);\n }\n\n const instancesResponse = await authenticatedFetch(instancesUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!instancesResponse.ok) {\n throw new Error(\n `Instances request failed (${instancesResponse.status} ${instancesResponse.statusText})`\n );\n }\n\n const instancesData = await instancesResponse.json();\n const allInstances = instancesData.instances || [];\n\n // Split into online and airgap\n const onlineInstances = allInstances.filter((i: { isAirgap?: boolean }) => !i.isAirgap);\n const airgapInstances = allInstances.filter((i: { isAirgap?: boolean }) => i.isAirgap);\n\n // Filter to active online instances (checked in within 24 hours)\n const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;\n const activeOnlineInstances = onlineInstances.filter((instance: { lastCheckin?: string }) => {\n const lastCheckin = instance.lastCheckin \n ? new Date(instance.lastCheckin).getTime() \n : 0;\n return lastCheckin > twentyFourHoursAgo;\n });\n\n const onlineActiveCount = activeOnlineInstances.length;\n const airgapCount = airgapInstances.length;\n\n // Fetch channel releases to calculate updates\n let channelReleases: Array<{ channelId: string; channelSequence: number }> = [];\n try {\n const releasesUrl = `${origin}/v3/channel-releases?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching channel releases via %s\", releasesUrl);\n }\n\n const releasesResponse = await authenticatedFetch(releasesUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (releasesResponse.ok) {\n const releasesData = await releasesResponse.json();\n channelReleases = releasesData.channelReleases || [];\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching channel releases:\", error);\n }\n\n // Calculate updates for active online instances\n const calculateUpdates = (instances: Array<{ channelId?: string; channelSequence?: number }>) => {\n if (!channelReleases.length) return 0;\n \n let numUpdates = 0;\n for (const instance of instances) {\n const instanceSequence = instance.channelSequence ?? 0;\n const matchingReleases = channelReleases.filter(\n (release) => release.channelId === instance.channelId\n );\n for (const release of matchingReleases) {\n if (release.channelSequence > instanceSequence) {\n numUpdates++;\n }\n }\n }\n return numUpdates;\n };\n\n const onlineUpdates = calculateUpdates(activeOnlineInstances);\n const airgapUpdates = calculateUpdates(airgapInstances);\n\n return {\n onlineActiveCount,\n airgapCount,\n onlineUpdates,\n airgapUpdates\n };\n }\n});\n\n// =============================================================================\n// User Settings Types\n// =============================================================================\n\nexport interface FetchCurrentUserInput {\n token: string;\n}\n\nexport interface UserProfile {\n emailAddress: string;\n firstName: string;\n lastName: string;\n}\n\nexport interface FetchCurrentUserResult {\n user: UserProfile;\n}\n\nexport interface UpdateUserInput {\n token: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface UpdateUserResult {\n success: boolean;\n}\n\nexport interface NotificationSetting {\n type: string;\n enabled: boolean;\n}\n\nexport interface FetchNotificationsInput {\n token: string;\n customerId: string;\n}\n\nexport interface FetchNotificationsResult {\n notifications: NotificationSetting[];\n}\n\nexport interface UpdateNotificationsInput {\n token: string;\n customerId: string;\n notifications: NotificationSetting[];\n}\n\nexport interface UpdateNotificationsResult {\n notifications: NotificationSetting[];\n}\n\n// =============================================================================\n// User Settings Actions\n// =============================================================================\n\n/**\n * Fetches the current user's profile information.\n */\nexport const fetchCurrentUser = defineServerAction<\n FetchCurrentUserInput,\n FetchCurrentUserResult\n>({\n id: \"user/fetch-current\",\n description: \"Fetches the current user's profile information\",\n visibility: \"customer\",\n tags: [\"user\", \"profile\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch current user requires a session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/user`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching current user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch current user request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n user: {\n emailAddress: data.emailAddress || \"\",\n firstName: data.firstName || \"\",\n lastName: data.lastName || \"\"\n }\n };\n }\n});\n\n/**\n * Updates the current user's profile information.\n */\nexport const updateUser = defineServerAction<\n UpdateUserInput,\n UpdateUserResult\n>({\n id: \"user/update\",\n description: \"Updates the current user's first and/or last name\",\n visibility: \"customer\",\n tags: [\"user\", \"profile\"],\n async run({ token, firstName, lastName }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update user requires a session token\");\n }\n\n if (!firstName && !lastName) {\n throw new Error(\"At least one of firstName or lastName must be provided\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/user`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating user via %s\", endpoint);\n }\n\n const body: { firstName?: string; lastName?: string } = {};\n if (firstName !== undefined) body.firstName = firstName;\n if (lastName !== undefined) body.lastName = lastName;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify(body),\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Update user request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n return { success: true };\n }\n});\n\n/**\n * Fetches notification preferences for a specific customer/team.\n */\nexport const fetchNotifications = defineServerAction<\n FetchNotificationsInput,\n FetchNotificationsResult\n>({\n id: \"notifications/fetch\",\n description: \"Fetches notification preferences for a specific team\",\n visibility: \"customer\",\n tags: [\"notifications\", \"user\"],\n async run({ token, customerId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch notifications requires a session token\");\n }\n\n if (!customerId || typeof customerId !== \"string\") {\n throw new Error(\"Fetch notifications requires a customerId\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/notifications?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching notifications via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch notifications request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n notifications: data.notifications || []\n };\n }\n});\n\n/**\n * Updates notification preferences for a specific customer/team.\n */\nexport const updateNotifications = defineServerAction<\n UpdateNotificationsInput,\n UpdateNotificationsResult\n>({\n id: \"notifications/update\",\n description: \"Updates notification preferences for a specific team\",\n visibility: \"customer\",\n tags: [\"notifications\", \"user\"],\n async run({ token, customerId, notifications }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update notifications requires a session token\");\n }\n\n if (!customerId || typeof customerId !== \"string\") {\n throw new Error(\"Update notifications requires a customerId\");\n }\n\n if (!Array.isArray(notifications)) {\n throw new Error(\"Update notifications requires a notifications array\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/notifications?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating notifications via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ notifications }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Update notifications request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n \n return {\n notifications: data.notifications || []\n };\n }\n});\n\n// =============================================================================\n// Team Settings Types\n// =============================================================================\n\nexport interface TeamUser {\n emailAddress: string;\n firstAccessedAt?: string;\n lastAccessedAt?: string;\n viewCount?: number;\n pendingInvite?: boolean;\n}\n\nexport interface FetchTeamUsersInput {\n token: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface FetchTeamUsersResult {\n users: TeamUser[];\n total: number;\n}\n\nexport interface InviteUserInput {\n token: string;\n email: string;\n}\n\nexport interface InviteUserResult {\n success: boolean;\n}\n\nexport interface DeleteUserInput {\n token: string;\n email: string;\n}\n\nexport interface DeleteUserResult {\n success: boolean;\n}\n\nexport interface ServiceAccount {\n id: string;\n customerId: string;\n accountName: string;\n emailAddress?: string;\n token: string;\n isRevoked: boolean;\n createdAt: string;\n lastUsedAt?: string;\n tokenRegeneratedAt?: string;\n}\n\nexport interface FetchServiceAccountsInput {\n token: string;\n limit?: number;\n offset?: number;\n includeRevoked?: boolean;\n}\n\nexport interface FetchServiceAccountsResult {\n serviceAccounts: ServiceAccount[];\n total: number;\n}\n\nexport interface RevokeServiceAccountInput {\n token: string;\n accountId: string;\n}\n\nexport interface RevokeServiceAccountResult {\n success: boolean;\n}\n\nexport interface RotateServiceAccountTokenInput {\n token: string;\n accountId: string;\n}\n\nexport interface RotateServiceAccountTokenResult {\n serviceAccount: ServiceAccount;\n helmLoginCommand: string;\n redeployHelm: string[];\n}\n\nexport interface Instance {\n id: string;\n serviceAccountId?: string;\n versionLabel?: string;\n channelId?: string;\n channelSequence?: number;\n lastCheckin?: string;\n isAirgap?: boolean;\n embeddedClusterVersion?: string;\n tags?: Array<{ key: string; value: string }>;\n}\n\nexport interface FetchInstancesInput {\n token: string;\n}\n\nexport interface FetchInstancesResult {\n instances: Instance[];\n}\n\nexport interface SAMLConfig {\n samlAllowed: boolean;\n samlEnabled: boolean;\n entityId: string;\n acsUrl: string;\n hasIdpMetadata: boolean;\n hasIdpCert: boolean;\n}\n\nexport interface FetchSamlConfigInput {\n token: string;\n}\n\nexport interface FetchSamlConfigResult {\n config: SAMLConfig;\n}\n\nexport interface UpdateSamlConfigInput {\n token: string;\n idpMetadataXml: string;\n idpPublicCert: string;\n}\n\nexport interface UpdateSamlConfigResult {\n success: boolean;\n}\n\nexport interface ToggleSamlEnabledInput {\n token: string;\n enabled: boolean;\n}\n\nexport interface ToggleSamlEnabledResult {\n success: boolean;\n samlEnabled: boolean;\n}\n\nexport interface DeprovisionSamlInput {\n token: string;\n}\n\nexport interface DeprovisionSamlResult {\n success: boolean;\n}\n\n// =============================================================================\n// Team Settings Actions\n// =============================================================================\n\n/**\n * Fetches the list of users for a team.\n */\nexport const fetchTeamUsers = defineServerAction<\n FetchTeamUsersInput,\n FetchTeamUsersResult\n>({\n id: \"team/fetch-users\",\n description: \"Fetches paginated list of team users and pending invites\",\n visibility: \"customer\",\n tags: [\"team\", \"users\"],\n async run({ token, limit = 25, offset = 0 }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch team users requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n limit: limit.toString(),\n offset: offset.toString()\n });\n\n const endpoint = `${getApiOrigin()}/v3/users?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching team users via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch team users request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n users: data.users || [],\n total: data.total || 0\n };\n }\n});\n\n/**\n * Invites a user to the team.\n */\nexport const inviteUser = defineServerAction<\n InviteUserInput,\n InviteUserResult\n>({\n id: \"team/invite-user\",\n description: \"Sends an invitation email to join the team\",\n visibility: \"customer\",\n tags: [\"team\", \"users\", \"invite\"],\n async run({ token, email }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Invite user requires a session token\");\n }\n\n if (!email || typeof email !== \"string\") {\n throw new Error(\"Invite user requires an email address\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n email_address: email\n });\n\n const endpoint = `${getApiOrigin()}/v3/invite?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] inviting user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to invite user\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Removes a user from the team.\n */\nexport const deleteUser = defineServerAction<\n DeleteUserInput,\n DeleteUserResult\n>({\n id: \"team/delete-user\",\n description: \"Removes a user from the team\",\n visibility: \"customer\",\n tags: [\"team\", \"users\", \"delete\"],\n async run({ token, email }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Delete user requires a session token\");\n }\n\n if (!email || typeof email !== \"string\") {\n throw new Error(\"Delete user requires an email address\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n email_address: email\n });\n\n const endpoint = `${getApiOrigin()}/v3/user?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deleting user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to delete user\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Fetches the list of service accounts for a team.\n */\nexport const fetchServiceAccounts = defineServerAction<\n FetchServiceAccountsInput,\n FetchServiceAccountsResult\n>({\n id: \"team/fetch-service-accounts\",\n description: \"Fetches paginated list of service accounts\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\"],\n async run({ token, limit = 50, offset = 0, includeRevoked = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch service accounts requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n limit: limit.toString(),\n offset: offset.toString()\n });\n\n // Add filterRevoked parameter - API filters revoked when this param is present\n if (!includeRevoked) {\n params.set(\"filterRevoked\", \"false\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/service-accounts?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching service accounts via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch service accounts request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n serviceAccounts: data.serviceAccounts || [],\n total: data.total || 0\n };\n }\n});\n\n/**\n * Revokes a service account.\n */\nexport const revokeServiceAccount = defineServerAction<\n RevokeServiceAccountInput,\n RevokeServiceAccountResult\n>({\n id: \"team/revoke-service-account\",\n description: \"Revokes a service account (soft delete)\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\", \"revoke\"],\n async run({ token, accountId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Revoke service account requires a session token\");\n }\n\n if (!accountId || typeof accountId !== \"string\") {\n throw new Error(\"Revoke service account requires an account ID\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/service-account/${encodeURIComponent(accountId)}?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] revoking service account via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to revoke service account\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Rotates a service account token.\n */\nexport const rotateServiceAccountToken = defineServerAction<\n RotateServiceAccountTokenInput,\n RotateServiceAccountTokenResult\n>({\n id: \"team/rotate-service-account-token\",\n description: \"Generates a new token for a service account\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\", \"rotate\"],\n async run({ token, accountId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Rotate service account token requires a session token\");\n }\n\n if (!accountId || typeof accountId !== \"string\") {\n throw new Error(\"Rotate service account token requires an account ID\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/service-account/${encodeURIComponent(accountId)}/rotate-token?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] rotating service account token via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to rotate service account token\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n const data = await response.json();\n \n return {\n serviceAccount: data.service_account,\n helmLoginCommand: data.helm_login_cmd || \"\",\n redeployHelm: data.redeploy_helm || []\n };\n }\n});\n\n/**\n * Fetches instances for the customer.\n */\nexport const fetchInstances = defineServerAction<\n FetchInstancesInput,\n FetchInstancesResult\n>({\n id: \"team/fetch-instances\",\n description: \"Fetches instances to determine service account usage\",\n visibility: \"customer\",\n tags: [\"team\", \"instances\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch instances requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/instances?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching instances via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch instances request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n instances: data.instances || []\n };\n }\n});\n\n/**\n * Fetches SAML configuration for the customer.\n */\nexport const fetchSamlConfig = defineServerAction<\n FetchSamlConfigInput,\n FetchSamlConfigResult\n>({\n id: \"team/fetch-saml-config\",\n description: \"Fetches SAML SSO configuration for the team\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch SAML config requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching SAML config via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch SAML config request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n config: {\n samlAllowed: data.samlAllowed || false,\n samlEnabled: data.samlEnabled || false,\n entityId: data.entityId || \"\",\n acsUrl: data.acsUrl || \"\",\n hasIdpMetadata: data.hasIdpMetadata || false,\n hasIdpCert: data.hasIdpCert || false\n }\n };\n }\n});\n\n/**\n * Updates SAML configuration (uploads IdP metadata and certificate).\n */\nexport const updateSamlConfig = defineServerAction<\n UpdateSamlConfigInput,\n UpdateSamlConfigResult\n>({\n id: \"team/update-saml-config\",\n description: \"Uploads IdP metadata and certificate for SAML SSO\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"update\"],\n async run({ token, idpMetadataXml, idpPublicCert }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update SAML config requires a session token\");\n }\n\n if (!idpMetadataXml || !idpPublicCert) {\n throw new Error(\"Both IdP metadata and certificate are required\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating SAML config via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({\n idpMetadataXml,\n idpPublicCert\n }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to update SAML configuration\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Toggles SAML authentication enabled/disabled.\n */\nexport const toggleSamlEnabled = defineServerAction<\n ToggleSamlEnabledInput,\n ToggleSamlEnabledResult\n>({\n id: \"team/toggle-saml-enabled\",\n description: \"Enables or disables SAML authentication\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"toggle\"],\n async run({ token, enabled }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Toggle SAML enabled requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/enable?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] toggling SAML enabled via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ enabled }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to toggle SAML\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n const data = await response.json();\n \n return {\n success: true,\n samlEnabled: data.samlEnabled || enabled\n };\n }\n});\n\n/**\n * Removes SAML configuration (deprovisions SAML).\n */\nexport const deprovisionSaml = defineServerAction<\n DeprovisionSamlInput,\n DeprovisionSamlResult\n>({\n id: \"team/deprovision-saml\",\n description: \"Removes all SAML configuration\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"delete\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Deprovision SAML requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deprovisioning SAML via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to remove SAML configuration\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n// =============================================================================\n// Invite Accept/Refresh Actions\n// =============================================================================\n\nexport interface AcceptInviteInput {\n code: string;\n}\n\nexport interface AcceptInviteResult {\n token: string;\n}\n\nexport interface AcceptInviteError {\n code: \"invalid_code\" | \"expired\" | \"unknown\";\n message: string;\n}\n\n/**\n * Accepts a team invitation using the invite code from email.\n * Returns a JWT token on success that can be used to establish a session.\n */\nexport const acceptInvite = defineServerAction<\n AcceptInviteInput,\n AcceptInviteResult\n>({\n id: \"auth/accept-invite\",\n description: \"Accepts a team invitation and returns a session token\",\n visibility: \"customer\",\n tags: [\"auth\", \"invite\", \"join\"],\n async run({ code }) {\n if (!code || typeof code !== \"string\") {\n const error: AcceptInviteError = {\n code: \"invalid_code\",\n message: \"Invite code is required\"\n };\n throw error;\n }\n\n const endpoint = `${getApiOrigin()}/v3/invite/accept`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] accepting invite via %s\", endpoint);\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ code })\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n const error: AcceptInviteError = {\n code: \"invalid_code\",\n message: \"Invalid or expired invite code. Please check your code and try again.\"\n };\n throw error;\n }\n\n let errorMessage = \"Failed to accept invitation\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n\n const error: AcceptInviteError = {\n code: \"unknown\",\n message: errorMessage\n };\n throw error;\n }\n\n const payload = await response.json();\n const token = payload?.jwt ?? payload?.token;\n\n if (typeof token !== \"string\") {\n throw new Error(\"Invite accepted but no token returned\");\n }\n\n return { token };\n }\n});\n\nexport interface RefreshInviteInput {\n code: string;\n}\n\nexport interface RefreshInviteResult {\n success: boolean;\n}\n\n/**\n * Refreshes an expired invite by generating a new code and resending the email.\n * The original code is used to identify the invite to refresh.\n */\nexport const refreshInvite = defineServerAction<\n RefreshInviteInput,\n RefreshInviteResult\n>({\n id: \"auth/refresh-invite\",\n description: \"Refreshes an expired invite and resends the invitation email\",\n visibility: \"customer\",\n tags: [\"auth\", \"invite\", \"refresh\"],\n async run({ code }) {\n if (!code || typeof code !== \"string\") {\n throw new Error(\"Invite code is required\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/invite/refresh`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] refreshing invite via %s\", endpoint);\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ code })\n });\n\n // The API returns 200 even for non-existent codes to prevent code enumeration\n if (!response.ok) {\n let errorMessage = \"Failed to refresh invitation\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n","import { Buffer } from \"node:buffer\";\nimport type { ReactNode } from \"react\";\nimport Link from \"next/link\";\nimport { fetchCustomBranding } from \"../actions\";\n\nexport interface Customer {\n id: string;\n name: string;\n}\n\nexport interface TopNavLink {\n label: string;\n href?: string;\n icon: ReactNode;\n}\n\nexport interface TopNavProps {\n links?: TopNavLink[];\n hiddenLabels?: string[];\n additionalLinks?: TopNavLink[];\n order?: string[];\n userMenuLabel?: string;\n activeLabel?: string;\n customerName?: string;\n customers?: Customer[];\n currentCustomerId?: string;\n onChangeTeam?: (customerId: string) => Promise<void>;\n userMenuChildren?: ReactNode;\n}\n\nconst defaultHiddenLabels = [\"Download\"];\n\nconst defaultTopNavLinks: TopNavLink[] = [\n {\n label: \"Dashboard\",\n href: \"/\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M4 13h6V3H4z\" />\n <path d=\"M14 21h6V3h-6z\" />\n </svg>\n )\n },\n {\n label: \"Download\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M12 3v12\" />\n <path d=\"m7 11 5 5 5-5\" />\n <path d=\"M5 21h14\" />\n </svg>\n )\n },\n {\n label: \"Install\",\n href: \"/install\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M12 5v14\" />\n <path d=\"M5 12h14\" />\n </svg>\n )\n },\n {\n label: \"Update\",\n href: \"/update\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M4 4v6h6\" />\n <path d=\"M20 20v-6h-6\" />\n <path d=\"M4 10c1.5-4 6-6 10-4m6 4c-1.5 4-6 6-10 4\" />\n </svg>\n )\n },\n {\n label: \"Release History\",\n href: \"/release-history\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M12 8v4l3 2\" />\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n </svg>\n )\n },\n {\n label: \"License\",\n href: \"/license\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <rect width=\"14\" height=\"18\" x=\"5\" y=\"3\" rx=\"2\" />\n <path d=\"M9 7h6\" />\n <path d=\"M9 11h6\" />\n <path d=\"M9 15h6\" />\n </svg>\n )\n },\n {\n label: \"Support\",\n href: \"/support\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <path d=\"M18 16a6 6 0 1 0-12 0v2h12Z\" />\n <circle cx=\"12\" cy=\"7\" r=\"4\" />\n </svg>\n )\n }\n];\n\nconst orderLinks = (links: TopNavLink[], order?: string[]) => {\n if (!order || order.length === 0) {\n return links;\n }\n\n const orderMap = new Map(order.map((label, index) => [label, index]));\n return links\n .map((link, index) => ({\n link,\n originalIndex: index,\n orderIndex: orderMap.has(link.label)\n ? (orderMap.get(link.label) as number)\n : order.length + index\n }))\n .sort((a, b) => {\n if (a.orderIndex === b.orderIndex) {\n return a.originalIndex - b.originalIndex;\n }\n return a.orderIndex - b.orderIndex;\n })\n .map((item) => item.link);\n};\n\n/**\n * TopNav renders the hero navigation bar shown on authenticated dashboards.\n */\nexport const TopNav = async ({\n links,\n hiddenLabels,\n additionalLinks,\n order,\n userMenuLabel,\n activeLabel,\n customerName,\n customers,\n currentCustomerId,\n onChangeTeam,\n userMenuChildren\n}: TopNavProps) => {\n const displayLabel = userMenuLabel || (customerName ? `Team: ${customerName}` : \"Team: Example\");\n let logo: string | undefined;\n let brandTitle: string | undefined;\n let customColor1: string | undefined;\n let customColor2: string | undefined;\n\n const normalizeColor = (color?: string) => {\n if (!color || typeof color !== \"string\") {\n return undefined;\n }\n\n const trimmed = color.trim();\n if (/^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(trimmed)) {\n return trimmed.startsWith(\"#\") ? trimmed : `#${trimmed}`;\n }\n\n return trimmed;\n };\n\n try {\n const branding = await fetchCustomBranding();\n if (branding.brandingData) {\n const decoded = Buffer.from(branding.brandingData, \"base64\").toString(\n \"utf-8\"\n );\n\n try {\n const parsed = JSON.parse(decoded);\n if (parsed?.logo && typeof parsed.logo === \"string\") {\n logo = parsed.logo;\n }\n if (parsed?.title && typeof parsed.title === \"string\") {\n const normalizedTitle = parsed.title.trim();\n if (normalizedTitle) {\n brandTitle = normalizedTitle;\n }\n }\n if (parsed?.customColor1 && typeof parsed.customColor1 === \"string\") {\n customColor1 = normalizeColor(parsed.customColor1);\n }\n if (parsed?.customColor2 && typeof parsed.customColor2 === \"string\") {\n customColor2 = normalizeColor(parsed.customColor2);\n }\n } catch (error) {\n console.debug(\n \"[portal-components] unable to parse branding JSON\",\n error\n );\n }\n } else {\n console.debug(\"[portal-components] branding\", branding);\n }\n } catch (error) {\n console.debug(\"[portal-components] branding fetch failed\", error);\n }\n\n const baseLinks = links ?? defaultTopNavLinks;\n const computedHiddenLabels = hiddenLabels\n ? hiddenLabels\n : links\n ? undefined\n : defaultHiddenLabels;\n const hiddenSet = computedHiddenLabels ? new Set(computedHiddenLabels) : null;\n let resolvedLinks = baseLinks.filter(\n (link) => !hiddenSet?.has(link.label)\n );\n\n if (additionalLinks?.length) {\n resolvedLinks = [...resolvedLinks, ...additionalLinks];\n }\n\n resolvedLinks = orderLinks(resolvedLinks, order);\n\n const gradientStart = customColor1 ?? \"rgb(235, 102, 88)\";\n const gradientEnd = customColor2 ?? customColor1 ?? \"rgb(184, 83, 71)\";\n return (\n <div\n className=\"relative flex h-[165px] w-full items-start justify-center\"\n style={{\n backgroundImage:\n `linear-gradient(to top, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0) 33%), linear-gradient(${gradientStart}, ${gradientEnd})`,\n backgroundRepeat: \"no-repeat\",\n backgroundSize: \"100% 100%\"\n }}\n >\n <div className=\"mx-auto mt-[30px] w-full max-w-[1248px] px-6\">\n <div className=\"flex h-[135px] flex-col justify-between space-y-4 rounded bg-[#ffffffe6] px-6 pt-6 pb-4 shadow-[0_10px_60px_rgba(16,16,16,0.35)]\">\n <div className=\"flex items-center justify-between\">\n {logo || brandTitle ? (\n <div className=\"flex items-center gap-3\">\n {logo ? (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={logo}\n alt=\"Portal logo\"\n className=\"object-contain\"\n style={{\n maxWidth: \"240px\",\n maxHeight: \"48px\"\n }}\n />\n ) : null}\n {brandTitle ? (\n <span className=\"text-lg font-semibold text-gray-900\">\n {brandTitle}\n </span>\n ) : null}\n </div>\n ) : (\n <div />\n )}\n <details className=\"group relative\">\n <summary className=\"flex cursor-pointer items-center gap-2 rounded-lg bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 list-none\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"text-gray-500\"\n >\n <path d=\"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\"></path>\n <circle cx=\"12\" cy=\"7\" r=\"4\"></circle>\n </svg>\n <span>{displayLabel}</span>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"text-gray-500\"\n >\n <polyline points=\"6 9 12 15 18 9\"></polyline>\n </svg>\n </summary>\n <div className=\"absolute right-0 mt-2 w-48 rounded-md border border-gray-200 bg-white py-2 text-sm text-gray-700 shadow-lg z-50\">\n <Link\n href=\"/user-settings\"\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n User settings\n </Link>\n <Link\n href=\"/team-settings\"\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n Team settings\n </Link>\n {userMenuChildren}\n <Link\n href=\"/?expired=1\"\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n Logout\n </Link>\n </div>\n </details>\n </div>\n <div className=\"mt-3 flex flex-wrap gap-3 border-b border-gray-200 pb-2 text-sm font-medium text-gray-500\">\n {resolvedLinks.map(({ label, icon, href }) => {\n const isActive = activeLabel === label;\n const className = `flex items-center gap-2 px-4 py-1 transition text-gray-500 ${\n isActive ? \"underline underline-offset-8 decoration-2\" : \"\"\n }`;\n\n if (href) {\n return (\n <Link key={label} href={href} className={className}>\n <span className={isActive ? \"text-rose-600\" : \"text-gray-500\"}>\n {icon}\n </span>\n <span>{label}</span>\n </Link>\n );\n }\n\n return (\n <button key={label} className={className} type=\"button\">\n <span className={isActive ? \"text-rose-600\" : \"text-gray-500\"}>\n {icon}\n </span>\n <span>{label}</span>\n </button>\n );\n })}\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nexport { defaultTopNavLinks };\n","import { ReactNode } from \"react\";\nimport { TopNav } from \"./top-nav\";\n\ninterface UpdateLayoutProps {\n children: ReactNode;\n}\n\nexport const UpdateLayout = ({ children }: UpdateLayoutProps) => {\n return (\n <div className=\"min-h-screen bg-white\">\n <TopNav activeLabel=\"Updates\" />\n <div className=\"px-6 py-8\">\n <div className=\"mx-auto w-full max-w-[1248px]\">\n {children}\n </div>\n </div>\n </div>\n );\n};\n\nUpdateLayout.displayName = \"UpdateLayout\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/actions/index.ts","../../src/components/top-nav.tsx","../../src/components/update-layout.tsx"],"names":["Buffer","jsxs","jsx"],"mappings":";;;;;;;;;;;;AAiBO,IAAM,eAAe,MAAc;AACxC,EAAA,OAAA,CAAQ,QAAQ,GAAA,CAAI,qBAAA,IAAyB,wBAAA,EAA0B,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC3F,CAAA;AAsaA,IAAM,0BAA0B,YAA6C;AAC3E,EAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,eAAA;AAE5B,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,MAAM,mCAAmC,CAAA;AAAA,EACrD;AAEA,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,YAAA,EAAc,CAAA,6BAAA,EAAgC,kBAAA;AAAA,IAC3D;AAAA,GACD,CAAA,CA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","file":"update-layout.js","sourcesContent":["/**\n * Light-weight type helpers for defining Server Actions that align with the\n * enterprise portal guardrails. The component library does not implement\n * specific actions, but it exports helpers so downstream portals can describe\n * their actions with consistent metadata.\n */\n\nimport { cache } from \"react\";\nimport { authenticatedFetch } from \"../utils/api-client\";\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Gets the base API origin from environment, with trailing slashes removed.\n */\nexport const getApiOrigin = (): string => {\n return (process.env.REPLICATED_APP_ORIGIN || \"https://replicated.app\").replace(/\\/+$/, \"\");\n};\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport type PortalActionVisibility = \"vendor\" | \"customer\";\n\nexport interface PortalActionContext {\n vendorId: string;\n licenseId: string;\n userId: string;\n signal?: AbortSignal;\n}\n\nexport interface PortalServerActionDefinition<Input, Output> {\n id: string;\n description: string;\n visibility: PortalActionVisibility;\n tags: string[];\n run: (input: Input, context?: PortalActionContext) => Promise<Output>;\n}\n\nexport const defineServerAction = <Input, Output>(\n definition: PortalServerActionDefinition<Input, Output>\n) => definition;\n\nexport interface CreateServiceAccountInput {\n token: string;\n name: string;\n}\n\nexport interface ServiceAccountData {\n id: string;\n customerId: string;\n token: string;\n accountName: string;\n isRevoked: boolean;\n createdAt: string;\n emailAddress: string;\n}\n\nexport interface CreateServiceAccountResult {\n service_account: ServiceAccountData;\n token: string;\n}\n\nexport const createServiceAccount = defineServerAction<\n CreateServiceAccountInput,\n CreateServiceAccountResult\n>({\n id: \"service-account/create\",\n description: \"Creates a service account for installing applications\",\n visibility: \"customer\",\n tags: [\"service-account\", \"install\"],\n async run({ token, name }) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Service account creation requires a session token\");\n }\n\n if (!name || typeof name !== \"string\" || !name.trim()) {\n throw new Error(\"Service account name is required\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/service-account`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] creating service account via %s\",\n endpoint\n );\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({ account_name: name.trim() })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Service account creation failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data: CreateServiceAccountResult = await response.json();\n return data;\n }\n});\n\nexport interface InitiateLoginInput {\n email: string;\n}\n\nexport interface InitiateLoginResult {\n status: \"ok\" | \"saml_redirect\";\n requestedAt: string;\n message: string;\n /** If SAML redirect is required, this contains the info needed to redirect */\n saml?: {\n redirectRequired: true;\n customerId: string;\n email: string;\n appSlug: string;\n };\n}\n\n/**\n * Reference server action for initiating the passwordless login flow.\n * Real portals should replace the simulated delay with a call to their auth API.\n */\nexport const initiateLogin = defineServerAction<\n InitiateLoginInput,\n InitiateLoginResult\n>({\n id: \"auth/initiate-login\",\n description:\n \"Begins the passwordless login flow by dispatching a magic link email.\",\n visibility: \"customer\",\n tags: [\"auth\", \"login\", \"session\"],\n async run(input) {\n const endpoint = `${getApiOrigin()}/v3/login/magic-link`;\n const appSlug = process.env.PORTAL_APP_SLUG;\n if (!appSlug) {\n throw new Error(\"PORTAL_APP_SLUG is not configured\");\n }\n const portalOrigin =\n process.env.PORTAL_ORIGIN ?? \"https://enterprise.replicated.com\";\n const redirectUri = `${portalOrigin.replace(/\\/+$/, \"\")}/${appSlug}/login`;\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({\n app_slug: appSlug,\n email_address: input.email,\n redirect_uri: redirectUri\n })\n });\n\n if (!response.ok) {\n throw new Error(\n `Magic link request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n\n // Check if SAML redirect is required\n if (data.saml_redirect_required && data.saml_customer_id) {\n return {\n status: \"saml_redirect\",\n requestedAt: new Date().toISOString(),\n message: \"SAML authentication required\",\n saml: {\n redirectRequired: true,\n customerId: data.saml_customer_id,\n email: input.email,\n appSlug\n }\n };\n }\n\n return {\n status: \"ok\",\n requestedAt: new Date().toISOString(),\n message: `Magic link requested for ${input.email}`\n };\n }\n});\n\nexport interface VerifyMagicLinkInput {\n nonce: string;\n}\n\nexport interface VerifyMagicLinkResult {\n token: string;\n raw: unknown;\n}\n\nexport interface VerifyMagicLinkError {\n code: \"invalid_code\" | \"expired\" | \"unknown\";\n message: string;\n isExpired?: boolean;\n}\n\nexport const verifyMagicLink = defineServerAction<\n VerifyMagicLinkInput,\n VerifyMagicLinkResult\n>({\n id: \"auth/verify-magic-link\",\n description: \"Verifies the 12-digit code provided via email and returns a JWT.\",\n visibility: \"customer\",\n tags: [\"auth\", \"login\", \"verify\"],\n async run({ nonce }) {\n const endpoint = `${getApiOrigin()}/v3/login/magic-link/verify`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] verifying magic link via %s\",\n endpoint\n );\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify({ nonce })\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n // Check if the response indicates an expired link\n try {\n const errorBody = await response.json();\n if (errorBody?.is_expired === true) {\n const error: VerifyMagicLinkError = {\n code: \"expired\",\n message: \"Magic link has expired. A new link has been sent to your email.\",\n isExpired: true\n };\n throw error;\n }\n } catch (parseError) {\n // If we already threw an error, re-throw it\n if ((parseError as VerifyMagicLinkError)?.code === \"expired\") {\n throw parseError;\n }\n // Otherwise fall through to invalid_code\n }\n\n const error: VerifyMagicLinkError = {\n code: \"invalid_code\",\n message: \"Incorrect code, check your email and try again.\"\n };\n throw error;\n }\n const error: VerifyMagicLinkError = {\n code: \"unknown\",\n message: `Magic link verification failed (${response.status} ${response.statusText})`\n };\n throw error;\n }\n\n const payload = await response.json();\n const token = payload?.token ?? payload?.jwt ?? payload?.access_token;\n if (typeof token !== \"string\") {\n throw new Error(\"Magic link verification succeeded but no token returned\");\n }\n\n return { token, raw: payload };\n }\n});\n\nexport interface CustomBrandingResponse {\n brandingData: string;\n documentation: unknown;\n}\n\nexport interface PortalLicenseField {\n key: string;\n label: string;\n value: string | null;\n isSecret?: boolean;\n}\n\nexport interface PortalLicenseDetails {\n id?: string;\n status?: string;\n statusLabel?: string;\n environment?: string;\n expiresAt?: string | null;\n releaseChannels?: string[];\n installMethods?: string[];\n installNotes?: string;\n customerName?: string;\n customerId?: string;\n customerOrganization?: string;\n fields: PortalLicenseField[];\n}\n\nexport interface ListSupportBundlesInput {\n token: string;\n}\n\nexport interface SupportBundleInsight {\n level: string;\n primary: string;\n key?: string;\n detail?: string;\n}\n\nexport interface SupportBundleSummary {\n id: string;\n createdAt?: string;\n status?: string;\n size?: number;\n instanceId?: string;\n insights?: SupportBundleInsight[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface ListSupportBundlesResult {\n bundles: SupportBundleSummary[];\n totalCount: number;\n raw: unknown;\n}\n\nexport interface DownloadSupportBundleInput {\n token: string;\n bundleId: string;\n}\n\nexport interface DownloadSupportBundleResult {\n signedUrl: string;\n}\n\nexport interface DeleteSupportBundleInput {\n token: string;\n bundleId: string;\n}\n\nexport interface DeleteSupportBundleResult {\n success: boolean;\n}\n\nexport interface UploadSupportBundleInput {\n token: string;\n appId: string;\n}\n\nexport interface UploadSupportBundleResult {\n uploadUrl: string;\n appId: string;\n}\n\nexport interface UploadSupportBundleCompleteInput {\n token: string;\n appId: string;\n fileContent: ArrayBuffer;\n contentLength: number;\n}\n\nexport interface UploadSupportBundleCompleteResult {\n bundleId: string;\n slug: string;\n}\n\nexport interface FetchLicenseDetailsInput {\n token: string;\n}\n\nexport interface FetchLicenseDetailsResult {\n license: PortalLicenseDetails;\n raw: unknown;\n}\n\nexport interface FetchInstallOptionsInput {\n token: string;\n}\n\nexport interface FetchInstallOptionsResult {\n showLinux: boolean;\n showHelm: boolean;\n}\n\nexport interface FetchLicenseSummaryInput {\n token: string;\n}\n\nexport interface FetchLicenseSummaryResult {\n type: string;\n expiresAt: string | null;\n}\n\nexport interface FetchCustomersInput {\n token: string;\n}\n\nexport interface Customer {\n id: string;\n name: string;\n licenseId: string;\n licenseType: string;\n expiresAt: string;\n isEnterprisePortalEnabled: boolean;\n}\n\nexport interface FetchCustomersResult {\n customers: Customer[];\n}\n\nexport interface SwitchCustomerInput {\n token: string;\n customerId: string;\n}\n\nexport interface SwitchCustomerResult {\n token: string;\n}\n\nexport interface ListReleasesInput {\n token: string;\n}\n\nexport interface ListReleasesResult {\n status: number;\n body: string | null;\n}\n\n/**\n * Internal implementation of fetchCustomBranding.\n * Wrapped with React's cache() to deduplicate calls within a single request.\n */\nconst fetchCustomBrandingImpl = async (): Promise<CustomBrandingResponse> => {\n const appSlug = process.env.PORTAL_APP_SLUG;\n\n if (!appSlug) {\n throw new Error(\"PORTAL_APP_SLUG is not configured\");\n }\n\n const url = `${getApiOrigin()}/v3/custom-branding?app_slug=${encodeURIComponent(\n appSlug\n )}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\n \"[portal-components] fetching custom branding via %s\",\n url\n );\n }\n\n const response = await fetch(url, {\n headers: {\n accept: \"application/json\"\n }\n });\n\n if (!response.ok) {\n throw new Error(\n `Custom branding request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const brandingData = payload?.branding_data;\n\n if (typeof brandingData !== \"string\") {\n throw new Error(\"Custom branding response missing branding_data string\");\n }\n\n return {\n brandingData,\n documentation: payload?.documentation ?? null\n };\n};\n\n/**\n * Fetches custom branding for the portal.\n * This function is cached per-request to avoid duplicate API calls when called\n * from multiple components (e.g., TopNav and page components).\n */\nexport const fetchCustomBranding = cache(fetchCustomBrandingImpl);\n\nexport const decodeJwtPayload = (token: string): Record<string, unknown> => {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new Error(\"Invalid JWT received\");\n }\n\n const payloadSegment = parts[1];\n if (!payloadSegment) {\n throw new Error(\"JWT payload segment missing\");\n }\n\n const padded = payloadSegment.padEnd(\n payloadSegment.length + ((4 - (payloadSegment.length % 4)) % 4),\n \"=\"\n );\n const decoded = Buffer.from(padded, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as Record<string, unknown>;\n};\n\n/**\n * Extracts customer ID from JWT token. Throws if extraction fails.\n */\nexport const getCustomerIdFromToken = (token: string): string => {\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id || payload?.customerId;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n return customerId.trim();\n};\n\nconst resolveSupportBundlesEndpoint = () => {\n const fallback = `${getApiOrigin()}/v3/supportbundles`;\n const explicit = process.env.SUPPORT_BUNDLES_ENDPOINT;\n\n if (!explicit) {\n return new URL(fallback);\n }\n\n try {\n return new URL(explicit);\n } catch (error) {\n console.warn(\n `[portal-components] invalid SUPPORT_BUNDLES_ENDPOINT, using fallback`,\n error\n );\n return new URL(fallback);\n }\n};\n\nexport const listSupportBundles = defineServerAction<\n ListSupportBundlesInput,\n ListSupportBundlesResult\n>({\n id: \"support/list-bundles\",\n description:\n \"Fetches support bundles associated with the customer found in the portal session JWT.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle listing requires a session token\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const url = resolveSupportBundlesEndpoint();\n url.searchParams.set(\"customer_id\", customerId.trim());\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching support bundles via %s\", url);\n }\n\n const response = await authenticatedFetch(url.toString(), {\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (context?.signal?.aborted) {\n throw new Error(\"Support bundles request was aborted\");\n }\n\n if (!response.ok) {\n throw new Error(\n `Support bundles request failed (${response.status} ${response.statusText})`\n );\n }\n\n const raw = await response.json();\n\n const rawRecord =\n raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : undefined;\n\n const parseInsights = (raw: unknown): SupportBundleInsight[] | undefined => {\n if (!Array.isArray(raw)) return undefined;\n return raw\n .filter((i): i is Record<string, unknown> => i && typeof i === \"object\")\n .map((i) => ({\n level: String(i.level ?? \"\"),\n primary: String(i.primary ?? \"\"),\n key: typeof i.key === \"string\" ? i.key : undefined,\n detail: typeof i.detail === \"string\" ? i.detail : undefined\n }));\n };\n\n const bundles: SupportBundleSummary[] = Array.isArray(\n rawRecord?.supportBundles\n )\n ? (rawRecord?.supportBundles as unknown[]).map((item) => {\n if (!item || typeof item !== \"object\") {\n return {\n id: \"\",\n createdAt: undefined,\n status: undefined,\n size: undefined,\n instanceId: undefined,\n insights: undefined,\n metadata: undefined\n };\n }\n\n const record = item as Record<string, unknown>;\n return {\n id: String(record.id ?? \"\"),\n createdAt:\n typeof record.createdAt === \"string\"\n ? (record.createdAt as string)\n : undefined,\n status:\n typeof record.status === \"string\"\n ? (record.status as string)\n : undefined,\n size:\n typeof record.size === \"number\"\n ? record.size\n : undefined,\n instanceId:\n typeof record.instanceId === \"string\"\n ? record.instanceId\n : undefined,\n insights: parseInsights(record.insights),\n metadata: record\n };\n })\n : Array.isArray(raw)\n ? (raw as unknown[]).map((item) => {\n if (!item || typeof item !== \"object\") {\n return {\n id: \"\",\n createdAt: undefined,\n status: undefined,\n size: undefined,\n instanceId: undefined,\n insights: undefined,\n metadata: undefined\n };\n }\n const record = item as Record<string, unknown>;\n return {\n id: String(record.id ?? \"\"),\n createdAt:\n typeof record.createdAt === \"string\"\n ? (record.createdAt as string)\n : undefined,\n status:\n typeof record.status === \"string\"\n ? (record.status as string)\n : undefined,\n size:\n typeof record.size === \"number\"\n ? record.size\n : undefined,\n instanceId:\n typeof record.instanceId === \"string\"\n ? record.instanceId\n : undefined,\n insights: parseInsights(record.insights),\n metadata: record\n };\n })\n : [];\n\n const totalCount = (() => {\n if (rawRecord) {\n if (\n typeof rawRecord.totalCount === \"number\" &&\n Number.isFinite(rawRecord.totalCount)\n ) {\n return rawRecord.totalCount;\n }\n if (Array.isArray(rawRecord.supportBundles)) {\n return rawRecord.supportBundles.length;\n }\n }\n\n if (Array.isArray(raw)) {\n return raw.length;\n }\n\n return bundles.length;\n })();\n\n return {\n bundles,\n totalCount,\n raw\n };\n }\n});\n\nexport const downloadSupportBundle = defineServerAction<\n DownloadSupportBundleInput,\n DownloadSupportBundleResult\n>({\n id: \"support/download-bundle\",\n description: \"Gets a signed URL for downloading a support bundle.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"download\"],\n async run({ token, bundleId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle download requires a session token\");\n }\n\n if (!bundleId || typeof bundleId !== \"string\") {\n throw new Error(\"Support bundle download requires a bundle ID\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/${encodeURIComponent(bundleId)}/download?customer_id=${encodeURIComponent(customerId.trim())}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] getting support bundle download URL via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Support bundle download URL request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n const signedUrl = data?.signedUrl;\n\n if (typeof signedUrl !== \"string\" || !signedUrl) {\n throw new Error(\"Support bundle download response missing signedUrl\");\n }\n\n return { signedUrl };\n }\n});\n\nexport const deleteSupportBundle = defineServerAction<\n DeleteSupportBundleInput,\n DeleteSupportBundleResult\n>({\n id: \"support/delete-bundle\",\n description: \"Deletes a support bundle.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"delete\"],\n async run({ token, bundleId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle deletion requires a session token\");\n }\n\n if (!bundleId || typeof bundleId !== \"string\") {\n throw new Error(\"Support bundle deletion requires a bundle ID\");\n }\n\n const payload = decodeJwtPayload(token);\n const customerId = payload?.customer_id;\n if (typeof customerId !== \"string\" || !customerId.trim()) {\n throw new Error(\"Unable to determine customer_id from session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/${encodeURIComponent(bundleId)}?customer_id=${encodeURIComponent(customerId.trim())}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deleting support bundle via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n if (response.status === 404) {\n throw new Error(\"Support bundle not found\");\n }\n throw new Error(\n `Support bundle deletion failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n return { success: true };\n }\n});\n\nexport const uploadSupportBundle = defineServerAction<\n UploadSupportBundleCompleteInput,\n UploadSupportBundleCompleteResult\n>({\n id: \"support/upload-bundle\",\n description: \"Uploads a support bundle to the server.\",\n visibility: \"customer\",\n tags: [\"support\", \"bundles\", \"upload\"],\n async run({ token, appId, fileContent, contentLength }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Support bundle upload requires a session token\");\n }\n\n if (!appId || typeof appId !== \"string\") {\n throw new Error(\"Support bundle upload requires an app ID\");\n }\n\n if (!fileContent || !(fileContent instanceof ArrayBuffer)) {\n throw new Error(\"Support bundle upload requires file content\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/supportbundle/upload/${encodeURIComponent(appId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] uploading support bundle via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(contentLength)\n },\n body: fileContent,\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Support bundle upload failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n\n return {\n bundleId: data?.bundleId ?? data?.bundle_id ?? \"\",\n slug: data?.slug ?? \"\"\n };\n }\n});\n\n/**\n * Helper to get the upload endpoint URL for client-side uploads with progress tracking.\n * Use this when you need progress indication - call this to get the URL, then upload directly from client.\n */\nexport const getSupportBundleUploadUrl = (appId: string): string => {\n return `${getApiOrigin()}/v3/supportbundle/upload/${encodeURIComponent(appId)}`;\n};\n\nexport const listReleases = defineServerAction<\n ListReleasesInput,\n ListReleasesResult\n>({\n id: \"releases/list\",\n description: \"Lists available releases for the authenticated customer.\",\n visibility: \"customer\",\n tags: [\"releases\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"List releases requires a session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/release-history`;\n\n console.log(\"[portal-components] listReleases request\", {\n endpoint\n });\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n const bodyText = await response\n .text()\n .catch((error) => {\n console.warn(\"[portal-components] listReleases read error\", error);\n return null;\n });\n\n console.log(\"[portal-components] listReleases response\", response.status, bodyText);\n\n if (!response.ok) {\n throw new Error(\n `List releases request failed (${response.status} ${response.statusText})`\n );\n }\n\n return {\n status: response.status,\n body: bodyText\n };\n }\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined => {\n if (value && typeof value === \"object\") {\n return value as Record<string, unknown>;\n }\n return undefined;\n};\n\nconst getValue = (\n record: Record<string, unknown> | undefined,\n key: string\n) => (record ? record[key] : undefined);\n\nconst getString = (\n record: Record<string, unknown> | undefined,\n key: string\n): string | undefined => {\n const value = getValue(record, key);\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getBoolean = (\n record: Record<string, unknown> | undefined,\n key: string\n): boolean | undefined => {\n const value = getValue(record, key);\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n if ([\"true\", \"1\", \"yes\"].includes(normalized)) {\n return true;\n }\n if ([\"false\", \"0\", \"no\"].includes(normalized)) {\n return false;\n }\n }\n return undefined;\n};\n\nconst toDisplayValue = (value: unknown): string | null => {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\nconst normalizeStringArray = (value: unknown): string[] | undefined => {\n if (Array.isArray(value)) {\n const normalized = value\n .map((item) =>\n typeof item === \"string\" ? item.trim() : \"\"\n )\n .filter((item) => item.length > 0);\n return normalized.length ? normalized : undefined;\n }\n\n if (typeof value === \"string\") {\n const normalized = value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n return normalized.length ? normalized : undefined;\n }\n\n return undefined;\n};\n\nconst normalizeLicenseFields = (input: unknown): PortalLicenseField[] => {\n if (!input) {\n return [];\n }\n\n if (Array.isArray(input)) {\n return input\n .map((field, index) => {\n if (!field || typeof field !== \"object\") {\n return null;\n }\n const candidate = field as Record<string, unknown>;\n const key =\n typeof candidate.key === \"string\" && candidate.key.trim().length\n ? candidate.key.trim()\n : typeof candidate.name === \"string\" && candidate.name.trim().length\n ? candidate.name.trim()\n : typeof candidate.label === \"string\" && candidate.label.trim().length\n ? candidate.label.trim()\n : `field-${index}`;\n const label =\n typeof candidate.label === \"string\" && candidate.label.trim().length\n ? candidate.label.trim()\n : typeof candidate.name === \"string\" && candidate.name.trim().length\n ? candidate.name.trim()\n : key;\n let value: unknown =\n candidate.value ?? candidate.data ?? candidate.content;\n if (\n (value === undefined || value === null) &&\n typeof candidate.text === \"string\"\n ) {\n value = candidate.text;\n }\n if (\n (value === undefined || value === null) &&\n typeof candidate.defaultValue === \"string\"\n ) {\n value = candidate.defaultValue;\n }\n const isSecret = Boolean(\n candidate.isSecret ?? candidate.secret ?? candidate.masked\n );\n const resolved = toDisplayValue(value);\n return {\n key,\n label,\n value: resolved,\n isSecret\n } as PortalLicenseField;\n })\n .filter((field): field is PortalLicenseField => Boolean(field));\n }\n\n if (typeof input === \"object\") {\n return Object.entries(input as Record<string, unknown>).map(\n ([key, value]) => {\n let resolvedValue: unknown = value;\n let isSecret = false;\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (\"value\" in obj) {\n resolvedValue = obj.value;\n }\n isSecret = Boolean(obj.isSecret ?? obj.secret ?? obj.masked);\n }\n const normalized = toDisplayValue(resolvedValue);\n return {\n key,\n label: key,\n value: normalized,\n isSecret\n };\n }\n );\n }\n\n return [];\n};\n\nconst extractChannelNames = (input: unknown): string[] | undefined => {\n if (!Array.isArray(input)) {\n return undefined;\n }\n const names = input\n .map((item) => {\n if (typeof item === \"string\") {\n return item.trim();\n }\n const record = asRecord(item);\n if (!record) {\n return null;\n }\n return (\n getString(record, \"name\") ??\n getString(record, \"channelName\") ??\n getString(record, \"channel\") ??\n getString(record, \"channelSlug\") ??\n getString(record, \"slug\") ??\n undefined\n );\n })\n .filter((name): name is string => Boolean(name && name.length));\n return names.length ? names : undefined;\n};\n\nconst normalizeEntitlementFields = (\n fieldsInput: unknown,\n valuesInput: unknown\n): PortalLicenseField[] => {\n const valuesMap = new Map<string, string | null>();\n const assignValue = (key: string | undefined, value: unknown) => {\n if (!key) {\n return;\n }\n valuesMap.set(key, toDisplayValue(value));\n };\n\n if (Array.isArray(valuesInput)) {\n valuesInput.forEach((item) => {\n const record = asRecord(item);\n if (!record) {\n if (typeof item === \"string\") {\n assignValue(item, item);\n }\n return;\n }\n const key =\n getString(record, \"name\") ??\n getString(record, \"field\") ??\n getString(record, \"title\") ??\n getString(record, \"label\") ??\n getString(record, \"slug\") ??\n (() => {\n const idValue = getValue(record, \"id\");\n if (typeof idValue === \"string\" || typeof idValue === \"number\") {\n return String(idValue);\n }\n return undefined;\n })();\n const value =\n getValue(record, \"value\") ??\n getValue(record, \"currentValue\") ??\n getValue(record, \"entitlementValue\") ??\n getValue(record, \"content\") ??\n getValue(record, \"data\") ??\n getValue(record, \"defaultVal\") ??\n getValue(record, \"defaultValue\");\n assignValue(key, value);\n });\n } else if (valuesInput && typeof valuesInput === \"object\") {\n Object.entries(valuesInput as Record<string, unknown>).forEach(\n ([key, value]) => assignValue(key, value)\n );\n }\n\n const normalized: PortalLicenseField[] = [];\n\n if (Array.isArray(fieldsInput)) {\n fieldsInput.forEach((item, index) => {\n const record = asRecord(item);\n if (!record) {\n return;\n }\n const baseKey =\n getString(record, \"name\") ??\n getString(record, \"field\") ??\n getString(record, \"slug\") ??\n `entitlement-${index}`;\n const key = `entitlement-${baseKey}`;\n const label =\n getString(record, \"title\") ??\n getString(record, \"label\") ??\n baseKey;\n const defaultValue =\n getString(record, \"defaultVal\") ??\n getString(record, \"default\") ??\n getString(record, \"defaultValue\");\n const value =\n valuesMap.get(baseKey) ??\n valuesMap.get(label) ??\n defaultValue ??\n null;\n const isSecret = Boolean(\n getBoolean(record, \"secret\") ??\n getBoolean(record, \"isSecret\") ??\n getBoolean(record, \"masked\")\n );\n normalized.push({\n key,\n label,\n value,\n isSecret\n });\n });\n }\n\n valuesMap.forEach((value, key) => {\n const normalizedKey = `entitlement-${key}`;\n if (!normalized.some((field) => field.key === normalizedKey)) {\n normalized.push({\n key: normalizedKey,\n label: key,\n value\n });\n }\n });\n\n return normalized;\n};\n\nconst normalizeLicensePayload = (payload: unknown): PortalLicenseDetails => {\n const payloadRecord = asRecord(payload);\n const rootRecord =\n asRecord(getValue(payloadRecord, \"license\")) ??\n asRecord(getValue(payloadRecord, \"data\")) ??\n payloadRecord ??\n ({} as Record<string, unknown>);\n const sourceRecord =\n asRecord(getValue(rootRecord, \"metadata\")) ?? rootRecord;\n\n const customer =\n asRecord(getValue(rootRecord, \"customer\")) ??\n asRecord(getValue(sourceRecord, \"customer\")) ??\n asRecord(getValue(payloadRecord, \"customer\")) ??\n ({} as Record<string, unknown>);\n\n let releaseChannels =\n normalizeStringArray(\n getValue(rootRecord, \"releaseChannels\") ??\n getValue(sourceRecord, \"releaseChannels\") ??\n getValue(sourceRecord, \"channels\") ??\n getValue(rootRecord, \"channels\") ??\n getValue(sourceRecord, \"channel\") ??\n getValue(rootRecord, \"channel\")\n ) ?? undefined;\n\n if (!releaseChannels) {\n releaseChannels =\n extractChannelNames(getValue(rootRecord, \"channels\")) ??\n extractChannelNames(getValue(sourceRecord, \"channels\")) ??\n undefined;\n }\n\n let installMethods =\n normalizeStringArray(\n getValue(rootRecord, \"installMethods\") ??\n getValue(sourceRecord, \"installMethods\") ??\n getValue(sourceRecord, \"install_options\") ??\n getValue(rootRecord, \"install_options\") ??\n getValue(sourceRecord, \"installOptions\")\n ) ?? undefined;\n\n if (!installMethods || installMethods.length === 0) {\n const resolved: string[] = [];\n const flag = (key: string) =>\n getBoolean(rootRecord, key) ?? getBoolean(sourceRecord, key) ?? false;\n\n if (flag(\"isKotsInstallEnabled\")) {\n resolved.push(\"Replicated KOTS\");\n }\n if (flag(\"isHelmInstallEnabled\")) {\n resolved.push(\"Helm\");\n }\n if (flag(\"isHelmAirgapEnabled\")) {\n resolved.push(\"Helm Airgap\");\n }\n if (\n flag(\"isEmbeddedClusterDownloadEnabled\") ||\n flag(\"isEmbeddedClusterMultiNodeEnabled\")\n ) {\n resolved.push(\"Embedded Cluster\");\n }\n if (flag(\"isKurlInstallEnabled\")) {\n resolved.push(\"kURL\");\n }\n if (flag(\"isGitopsSupported\")) {\n resolved.push(\"GitOps\");\n }\n if (resolved.length) {\n installMethods = Array.from(new Set(resolved));\n }\n }\n\n const expiresAtSource =\n getValue(sourceRecord, \"expiresAt\") ??\n getValue(sourceRecord, \"expireAt\") ??\n getValue(sourceRecord, \"expire_at\") ??\n getValue(sourceRecord, \"expiration\") ??\n getValue(sourceRecord, \"expirationDate\") ??\n getValue(sourceRecord, \"expires_on\") ??\n getValue(rootRecord, \"expiresAt\") ??\n getValue(rootRecord, \"expireAt\") ??\n getValue(rootRecord, \"expire_at\") ??\n getValue(rootRecord, \"expiration\");\n\n const expiresAt =\n typeof expiresAtSource === \"string\" && expiresAtSource.trim().length\n ? expiresAtSource\n : expiresAtSource === null\n ? null\n : undefined;\n\n const baseFields = normalizeLicenseFields(\n getValue(rootRecord, \"additionalFields\") ??\n getValue(sourceRecord, \"additionalFields\") ??\n getValue(sourceRecord, \"fields\") ??\n getValue(rootRecord, \"fields\") ??\n getValue(payloadRecord, \"fields\") ??\n getValue(payloadRecord, \"additional_fields\")\n );\n\n const entitlementFields = normalizeEntitlementFields(\n getValue(rootRecord, \"entitlementFields\") ??\n getValue(sourceRecord, \"entitlementFields\"),\n getValue(rootRecord, \"entitlementValues\") ??\n getValue(sourceRecord, \"entitlementValues\")\n );\n\n const fields = [\n ...baseFields,\n ...entitlementFields.filter(\n (field) => !baseFields.some((existing) => existing.key === field.key)\n )\n ];\n\n const statusFromSource =\n getString(sourceRecord, \"status\") ??\n getString(sourceRecord, \"state\");\n const statusLabelFromSource =\n getString(sourceRecord, \"statusLabel\") ??\n getString(sourceRecord, \"stateLabel\");\n const expiredFlag =\n getBoolean(sourceRecord, \"isExpired\") ??\n getBoolean(rootRecord, \"isExpired\");\n const derivedStatus =\n statusFromSource ??\n (typeof expiredFlag === \"boolean\"\n ? expiredFlag\n ? \"expired\"\n : \"active\"\n : undefined);\n const statusLabel =\n statusLabelFromSource ??\n (derivedStatus\n ? derivedStatus.charAt(0).toUpperCase() + derivedStatus.slice(1)\n : undefined);\n\n const licenseType =\n getString(sourceRecord, \"licenseType\") ??\n getString(rootRecord, \"licenseType\");\n\n const status = derivedStatus;\n\n const license: PortalLicenseDetails = {\n id:\n getString(rootRecord, \"id\") ??\n getString(sourceRecord, \"id\") ??\n getString(sourceRecord, \"licenseId\") ??\n getString(customer, \"licenseId\") ??\n undefined,\n status,\n statusLabel,\n environment:\n getString(sourceRecord, \"environment\") ??\n getString(sourceRecord, \"tier\") ??\n licenseType ??\n undefined,\n expiresAt: expiresAt ?? null,\n releaseChannels: releaseChannels ?? [\n getString(rootRecord, \"channelName\") ??\n getString(rootRecord, \"channel\") ??\n undefined\n ].filter((value): value is string => Boolean(value)),\n installMethods,\n installNotes: getString(sourceRecord, \"installNotes\"),\n customerName:\n getString(sourceRecord, \"customerName\") ??\n getString(customer, \"name\") ??\n undefined,\n customerId:\n getString(sourceRecord, \"customerId\") ??\n getString(customer, \"id\") ??\n getString(rootRecord, \"customerId\") ??\n undefined,\n customerOrganization:\n getString(customer, \"organization\") ??\n getString(sourceRecord, \"customerOrganization\") ??\n getString(rootRecord, \"customerOrganization\") ??\n undefined,\n fields\n };\n\n return license;\n};\n\nexport const fetchLicenseDetails = defineServerAction<\n FetchLicenseDetailsInput,\n FetchLicenseDetailsResult\n>({\n id: \"license/fetch-details\",\n description: \"Fetches the authenticated user's enterprise license details.\",\n visibility: \"customer\",\n tags: [\"license\", \"entitlements\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchLicenseDetails requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const license = normalizeLicensePayload(payload);\n\n return {\n license,\n raw: payload ?? null\n };\n }\n});\n\nexport const fetchInstallOptions = defineServerAction<\n FetchInstallOptionsInput,\n FetchInstallOptionsResult\n>({\n id: \"license/fetch-install-options\",\n description: \"Fetches install options based on license entitlements.\",\n visibility: \"customer\",\n tags: [\"license\", \"install\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchInstallOptions requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n \n // Check for embedded cluster (Linux) and Helm install flags\n const getBoolean = (obj: unknown, key: string): boolean => {\n if (obj && typeof obj === \"object\" && key in obj) {\n const val = (obj as Record<string, unknown>)[key];\n return val === true || val === \"true\";\n }\n return false;\n };\n\n const license = payload?.license ?? payload ?? {};\n const showLinux = getBoolean(license, \"isEmbeddedClusterDownloadEnabled\");\n const showHelm = getBoolean(license, \"isHelmInstallEnabled\");\n\n return {\n showLinux,\n showHelm\n };\n }\n});\n\nexport const fetchLicenseSummary = defineServerAction<\n FetchLicenseSummaryInput,\n FetchLicenseSummaryResult\n>({\n id: \"license/fetch-summary\",\n description: \"Fetches license summary for the license card.\",\n visibility: \"customer\",\n tags: [\"license\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchLicenseSummary requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/license`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `License request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n const license = normalizeLicensePayload(payload);\n\n // Extract type and expiration\n const type = license.environment || \"Unknown\";\n const expiresAt = license.expiresAt || null;\n\n return {\n type,\n expiresAt\n };\n }\n});\n\nexport const fetchCustomers = defineServerAction<\n FetchCustomersInput,\n FetchCustomersResult\n>({\n id: \"auth/fetch-customers\",\n description: \"Fetches the list of customers/teams for the authenticated user.\",\n visibility: \"customer\",\n tags: [\"auth\", \"customers\"],\n async run({ token }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"fetchCustomers requires a non-empty token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/customers`;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: {\n accept: \"application/json\"\n },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch customers request failed (${response.status} ${response.statusText})`\n );\n }\n\n const payload = await response.json();\n \n return {\n customers: payload.customers || []\n };\n }\n});\n\nexport const switchCustomer = defineServerAction<\n SwitchCustomerInput,\n SwitchCustomerResult\n>({\n id: \"auth/switch-customer\",\n description: \"Switches the JWT to a different customer/team.\",\n visibility: \"customer\",\n tags: [\"auth\", \"customers\"],\n async run({ token, customerId }, context) {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new Error(\"switchCustomer requires a non-empty token\");\n }\n \n if (typeof customerId !== \"string\" || customerId.trim().length === 0) {\n throw new Error(\"switchCustomer requires a non-empty customerId\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/select-customer`;\n\n const requestBody = { customer_id: customerId };\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify(requestBody),\n signal: context?.signal\n });\n\n console.log('[portal-components] switchCustomer response status:', response.status);\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('[portal-components] switchCustomer error response:', errorText);\n throw new Error(\n `Switch customer request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const payload = await response.json();\n console.log('[portal-components] switchCustomer response payload:', payload);\n \n // API returns 'jwt' field, not 'token'\n const newToken = payload.jwt || payload.token || token;\n console.log('[portal-components] switchCustomer using token field:', payload.jwt ? 'jwt' : (payload.token ? 'token' : 'fallback'));\n \n return {\n token: newToken\n };\n }\n});\n\n// =============================================================================\n// Security Types\n// =============================================================================\n\nexport type SecurityInstallType = \"linux\" | \"helm\";\n\nexport interface SecurityScanSummary {\n critical: Record<string, string>;\n high: Record<string, string>;\n medium: Record<string, string>;\n low: Record<string, string>;\n}\n\nexport interface SecurityScanWrapper {\n input: string;\n digest?: string;\n last_scanned_at?: string;\n result: SecurityScanSummary;\n not_found?: boolean;\n}\n\nexport interface SecurityReleaseImage {\n image: string;\n sha: string;\n size: number;\n platforms: { os: string; architecture: string }[];\n security?: SecurityScanWrapper;\n}\n\nexport interface GetSecurityInfoInput {\n token: string;\n installType: SecurityInstallType;\n channelSequence: number;\n isAirgap?: boolean;\n}\n\nexport interface GetSecurityInfoResult {\n images: SecurityReleaseImage[];\n}\n\nexport interface SecurityInfoDiff {\n oldTags: string[];\n newTags: string[];\n oldVulns?: SecurityScanSummary;\n newVulns?: SecurityScanSummary;\n added?: SecurityScanSummary;\n removed?: SecurityScanSummary;\n}\n\nexport interface GetSecurityInfoDiffInput {\n token: string;\n installType: SecurityInstallType;\n fromChannelSequence: number;\n toChannelSequence: number;\n isAirgap?: boolean;\n}\n\nexport interface GetSecurityInfoDiffResult {\n from_channel_sequence: number;\n to_channel_sequence: number;\n images: Record<string, SecurityInfoDiff>;\n}\n\nexport interface UnifiedSbom {\n sbom: string;\n sbom_source: string;\n}\n\nexport interface SpdxCreationInfo {\n created: string;\n creators: string[];\n}\n\nexport interface SpdxDocument {\n SPDXID: string;\n spdxVersion: string;\n name: string;\n creationInfo?: SpdxCreationInfo;\n packages?: unknown[];\n files?: unknown[];\n}\n\nexport interface GetSecurityInfoSBOMInput {\n token: string;\n installType: SecurityInstallType;\n channelSequence: number;\n isAirgap?: boolean;\n unifiedSbom?: boolean;\n}\n\nexport interface GetSecurityInfoSBOMResult {\n sboms: {\n unified?: UnifiedSbom;\n };\n}\n\n// =============================================================================\n// Security Actions\n// =============================================================================\n\n/**\n * Fetches security scan (CVE) information for a specific release.\n */\nexport const getSecurityInfo = defineServerAction<\n GetSecurityInfoInput,\n GetSecurityInfoResult\n>({\n id: \"security/get-info\",\n description: \"Fetches CVE security scan results for a specific release\",\n visibility: \"customer\",\n tags: [\"security\", \"cve\"],\n async run({ token, installType, channelSequence, isAirgap = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security info request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n channel_sequence: channelSequence.toString(),\n is_airgap: isAirgap.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security info via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Security info request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoResult;\n }\n});\n\n/**\n * Fetches security diff between two releases (fixed/added CVEs).\n */\nexport const getSecurityInfoDiff = defineServerAction<\n GetSecurityInfoDiffInput,\n GetSecurityInfoDiffResult\n>({\n id: \"security/get-info-diff\",\n description: \"Fetches CVE diff between two releases showing fixed and added vulnerabilities\",\n visibility: \"customer\",\n tags: [\"security\", \"cve\", \"diff\"],\n async run({ token, installType, fromChannelSequence, toChannelSequence, isAirgap = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security info diff request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n from_channel_sequence: fromChannelSequence.toString(),\n to_channel_sequence: toChannelSequence.toString(),\n is_airgap: isAirgap.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info-diff?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security info diff via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Security info diff request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoDiffResult;\n }\n});\n\n/**\n * Fetches SBOM (Software Bill of Materials) for a specific release.\n */\nexport const getSecurityInfoSBOM = defineServerAction<\n GetSecurityInfoSBOMInput,\n GetSecurityInfoSBOMResult\n>({\n id: \"security/get-sbom\",\n description: \"Fetches Software Bill of Materials (SBOM) for a specific release\",\n visibility: \"customer\",\n tags: [\"security\", \"sbom\"],\n async run({ token, installType, channelSequence, isAirgap = false, unifiedSbom = true }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Security SBOM request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n\n const params = new URLSearchParams({\n customer_id: customerId,\n install_type: installType,\n channel_sequence: channelSequence.toString(),\n is_airgap: isAirgap.toString(),\n unified_sbom: unifiedSbom.toString()\n });\n\n const url = `${getApiOrigin()}/v3/security-info-sbom?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching security SBOM via %s\", url);\n }\n\n const response = await authenticatedFetch(url, {\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n // Handle 204 No Content response\n if (response.status === 204) {\n return { sboms: {} };\n }\n\n if (!response.ok) {\n throw new Error(\n `Security SBOM request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n return data as GetSecurityInfoSBOMResult;\n }\n});\n\n// =============================================================================\n// Dashboard Types\n// =============================================================================\n\nexport interface FetchTeamStatsInput {\n token: string;\n}\n\nexport interface TeamUser {\n id: string;\n email: string;\n name?: string;\n createdAt?: string;\n}\n\nexport interface ServiceAccountSummary {\n id: string;\n accountName: string;\n customerId: string;\n isRevoked: boolean;\n createdAt: string;\n}\n\nexport interface FetchTeamStatsResult {\n userCount: number;\n serviceAccountCount: number;\n}\n\nexport interface FetchDashboardInstancesInput {\n token: string;\n}\n\nexport interface FetchDashboardInstancesResult {\n onlineActiveCount: number;\n airgapCount: number;\n onlineUpdates: number;\n airgapUpdates: number;\n}\n\n// =============================================================================\n// Dashboard Actions\n// =============================================================================\n\n/**\n * Fetches team statistics including user count and service account count.\n * Used by the Team Settings dashboard card.\n */\nexport const fetchTeamStats = defineServerAction<\n FetchTeamStatsInput,\n FetchTeamStatsResult\n>({\n id: \"dashboard/fetch-team-stats\",\n description: \"Fetches user and service account counts for the dashboard\",\n visibility: \"customer\",\n tags: [\"dashboard\", \"team\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Team stats request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const origin = getApiOrigin();\n\n // Fetch users count\n let userCount = 0;\n try {\n const usersUrl = `${origin}/v3/users?exclude_invites=false&customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching team users via %s\", usersUrl);\n }\n\n const usersResponse = await authenticatedFetch(usersUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (usersResponse.ok) {\n const usersData = await usersResponse.json();\n userCount = Array.isArray(usersData.users) ? usersData.users.length : 0;\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching users:\", error);\n }\n\n // Fetch service accounts count\n let serviceAccountCount = 0;\n try {\n const saUrl = `${origin}/v3/service-accounts?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching service accounts via %s\", saUrl);\n }\n\n const saResponse = await authenticatedFetch(saUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (saResponse.ok) {\n const saData = await saResponse.json();\n serviceAccountCount = Array.isArray(saData.serviceAccounts) \n ? saData.serviceAccounts.length \n : 0;\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching service accounts:\", error);\n }\n\n return {\n userCount,\n serviceAccountCount\n };\n }\n});\n\n/**\n * Fetches instance counts and available updates for the dashboard.\n * Used by the Updates dashboard card.\n */\nexport const fetchDashboardInstances = defineServerAction<\n FetchDashboardInstancesInput,\n FetchDashboardInstancesResult\n>({\n id: \"dashboard/fetch-instances\",\n description: \"Fetches instance counts and update availability for the dashboard\",\n visibility: \"customer\",\n tags: [\"dashboard\", \"instances\", \"updates\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Dashboard instances request requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const origin = getApiOrigin();\n\n // Fetch instances\n const instancesUrl = `${origin}/v3/instances?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching instances via %s\", instancesUrl);\n }\n\n const instancesResponse = await authenticatedFetch(instancesUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!instancesResponse.ok) {\n throw new Error(\n `Instances request failed (${instancesResponse.status} ${instancesResponse.statusText})`\n );\n }\n\n const instancesData = await instancesResponse.json();\n const allInstances = instancesData.instances || [];\n\n // Split into online and airgap\n const onlineInstances = allInstances.filter((i: { isAirgap?: boolean }) => !i.isAirgap);\n const airgapInstances = allInstances.filter((i: { isAirgap?: boolean }) => i.isAirgap);\n\n // Filter to active online instances (checked in within 24 hours)\n const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;\n const activeOnlineInstances = onlineInstances.filter((instance: { lastCheckin?: string }) => {\n const lastCheckin = instance.lastCheckin \n ? new Date(instance.lastCheckin).getTime() \n : 0;\n return lastCheckin > twentyFourHoursAgo;\n });\n\n const onlineActiveCount = activeOnlineInstances.length;\n const airgapCount = airgapInstances.length;\n\n // Fetch channel releases to calculate updates\n let channelReleases: Array<{ channelId: string; channelSequence: number }> = [];\n try {\n const releasesUrl = `${origin}/v3/channel-releases?customer_id=${encodeURIComponent(customerId)}`;\n \n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching channel releases via %s\", releasesUrl);\n }\n\n const releasesResponse = await authenticatedFetch(releasesUrl, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (releasesResponse.ok) {\n const releasesData = await releasesResponse.json();\n channelReleases = releasesData.channelReleases || [];\n }\n } catch (error) {\n console.error(\"[portal-components] Error fetching channel releases:\", error);\n }\n\n // Calculate updates for active online instances\n const calculateUpdates = (instances: Array<{ channelId?: string; channelSequence?: number }>) => {\n if (!channelReleases.length) return 0;\n \n let numUpdates = 0;\n for (const instance of instances) {\n const instanceSequence = instance.channelSequence ?? 0;\n const matchingReleases = channelReleases.filter(\n (release) => release.channelId === instance.channelId\n );\n for (const release of matchingReleases) {\n if (release.channelSequence > instanceSequence) {\n numUpdates++;\n }\n }\n }\n return numUpdates;\n };\n\n const onlineUpdates = calculateUpdates(activeOnlineInstances);\n const airgapUpdates = calculateUpdates(airgapInstances);\n\n return {\n onlineActiveCount,\n airgapCount,\n onlineUpdates,\n airgapUpdates\n };\n }\n});\n\n// =============================================================================\n// User Settings Types\n// =============================================================================\n\nexport interface FetchCurrentUserInput {\n token: string;\n}\n\nexport interface UserProfile {\n emailAddress: string;\n firstName: string;\n lastName: string;\n}\n\nexport interface FetchCurrentUserResult {\n user: UserProfile;\n}\n\nexport interface UpdateUserInput {\n token: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface UpdateUserResult {\n success: boolean;\n}\n\nexport interface NotificationSetting {\n type: string;\n enabled: boolean;\n}\n\nexport interface FetchNotificationsInput {\n token: string;\n customerId: string;\n}\n\nexport interface FetchNotificationsResult {\n notifications: NotificationSetting[];\n}\n\nexport interface UpdateNotificationsInput {\n token: string;\n customerId: string;\n notifications: NotificationSetting[];\n}\n\nexport interface UpdateNotificationsResult {\n notifications: NotificationSetting[];\n}\n\n// =============================================================================\n// User Settings Actions\n// =============================================================================\n\n/**\n * Fetches the current user's profile information.\n */\nexport const fetchCurrentUser = defineServerAction<\n FetchCurrentUserInput,\n FetchCurrentUserResult\n>({\n id: \"user/fetch-current\",\n description: \"Fetches the current user's profile information\",\n visibility: \"customer\",\n tags: [\"user\", \"profile\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch current user requires a session token\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/user`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching current user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch current user request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n user: {\n emailAddress: data.emailAddress || \"\",\n firstName: data.firstName || \"\",\n lastName: data.lastName || \"\"\n }\n };\n }\n});\n\n/**\n * Updates the current user's profile information.\n */\nexport const updateUser = defineServerAction<\n UpdateUserInput,\n UpdateUserResult\n>({\n id: \"user/update\",\n description: \"Updates the current user's first and/or last name\",\n visibility: \"customer\",\n tags: [\"user\", \"profile\"],\n async run({ token, firstName, lastName }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update user requires a session token\");\n }\n\n if (!firstName && !lastName) {\n throw new Error(\"At least one of firstName or lastName must be provided\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/user`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating user via %s\", endpoint);\n }\n\n const body: { firstName?: string; lastName?: string } = {};\n if (firstName !== undefined) body.firstName = firstName;\n if (lastName !== undefined) body.lastName = lastName;\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify(body),\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Update user request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n return { success: true };\n }\n});\n\n/**\n * Fetches notification preferences for a specific customer/team.\n */\nexport const fetchNotifications = defineServerAction<\n FetchNotificationsInput,\n FetchNotificationsResult\n>({\n id: \"notifications/fetch\",\n description: \"Fetches notification preferences for a specific team\",\n visibility: \"customer\",\n tags: [\"notifications\", \"user\"],\n async run({ token, customerId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch notifications requires a session token\");\n }\n\n if (!customerId || typeof customerId !== \"string\") {\n throw new Error(\"Fetch notifications requires a customerId\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/notifications?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching notifications via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch notifications request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n notifications: data.notifications || []\n };\n }\n});\n\n/**\n * Updates notification preferences for a specific customer/team.\n */\nexport const updateNotifications = defineServerAction<\n UpdateNotificationsInput,\n UpdateNotificationsResult\n>({\n id: \"notifications/update\",\n description: \"Updates notification preferences for a specific team\",\n visibility: \"customer\",\n tags: [\"notifications\", \"user\"],\n async run({ token, customerId, notifications }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update notifications requires a session token\");\n }\n\n if (!customerId || typeof customerId !== \"string\") {\n throw new Error(\"Update notifications requires a customerId\");\n }\n\n if (!Array.isArray(notifications)) {\n throw new Error(\"Update notifications requires a notifications array\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/notifications?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating notifications via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ notifications }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"\");\n throw new Error(\n `Update notifications request failed (${response.status} ${response.statusText}): ${errorText}`\n );\n }\n\n const data = await response.json();\n \n return {\n notifications: data.notifications || []\n };\n }\n});\n\n// =============================================================================\n// Team Settings Types\n// =============================================================================\n\nexport interface TeamUser {\n emailAddress: string;\n firstAccessedAt?: string;\n lastAccessedAt?: string;\n viewCount?: number;\n pendingInvite?: boolean;\n}\n\nexport interface FetchTeamUsersInput {\n token: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface FetchTeamUsersResult {\n users: TeamUser[];\n total: number;\n}\n\nexport interface InviteUserInput {\n token: string;\n email: string;\n}\n\nexport interface InviteUserResult {\n success: boolean;\n}\n\nexport interface DeleteUserInput {\n token: string;\n email: string;\n}\n\nexport interface DeleteUserResult {\n success: boolean;\n}\n\nexport interface ServiceAccount {\n id: string;\n customerId: string;\n accountName: string;\n emailAddress?: string;\n token: string;\n isRevoked: boolean;\n createdAt: string;\n lastUsedAt?: string;\n tokenRegeneratedAt?: string;\n}\n\nexport interface FetchServiceAccountsInput {\n token: string;\n limit?: number;\n offset?: number;\n includeRevoked?: boolean;\n}\n\nexport interface FetchServiceAccountsResult {\n serviceAccounts: ServiceAccount[];\n total: number;\n}\n\nexport interface RevokeServiceAccountInput {\n token: string;\n accountId: string;\n}\n\nexport interface RevokeServiceAccountResult {\n success: boolean;\n}\n\nexport interface RotateServiceAccountTokenInput {\n token: string;\n accountId: string;\n}\n\nexport interface RotateServiceAccountTokenResult {\n serviceAccount: ServiceAccount;\n helmLoginCommand: string;\n redeployHelm: string[];\n}\n\nexport interface Instance {\n id: string;\n serviceAccountId?: string;\n versionLabel?: string;\n channelId?: string;\n channelSequence?: number;\n lastCheckin?: string;\n isAirgap?: boolean;\n embeddedClusterVersion?: string;\n tags?: Array<{ key: string; value: string }>;\n}\n\nexport interface FetchInstancesInput {\n token: string;\n}\n\nexport interface FetchInstancesResult {\n instances: Instance[];\n}\n\nexport interface SAMLConfig {\n samlAllowed: boolean;\n samlEnabled: boolean;\n entityId: string;\n acsUrl: string;\n hasIdpMetadata: boolean;\n hasIdpCert: boolean;\n}\n\nexport interface FetchSamlConfigInput {\n token: string;\n}\n\nexport interface FetchSamlConfigResult {\n config: SAMLConfig;\n}\n\nexport interface UpdateSamlConfigInput {\n token: string;\n idpMetadataXml: string;\n idpPublicCert: string;\n}\n\nexport interface UpdateSamlConfigResult {\n success: boolean;\n}\n\nexport interface ToggleSamlEnabledInput {\n token: string;\n enabled: boolean;\n}\n\nexport interface ToggleSamlEnabledResult {\n success: boolean;\n samlEnabled: boolean;\n}\n\nexport interface DeprovisionSamlInput {\n token: string;\n}\n\nexport interface DeprovisionSamlResult {\n success: boolean;\n}\n\n// =============================================================================\n// Team Settings Actions\n// =============================================================================\n\n/**\n * Fetches the list of users for a team.\n */\nexport const fetchTeamUsers = defineServerAction<\n FetchTeamUsersInput,\n FetchTeamUsersResult\n>({\n id: \"team/fetch-users\",\n description: \"Fetches paginated list of team users and pending invites\",\n visibility: \"customer\",\n tags: [\"team\", \"users\"],\n async run({ token, limit = 25, offset = 0 }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch team users requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n limit: limit.toString(),\n offset: offset.toString()\n });\n\n const endpoint = `${getApiOrigin()}/v3/users?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching team users via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch team users request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n users: data.users || [],\n total: data.total || 0\n };\n }\n});\n\n/**\n * Invites a user to the team.\n */\nexport const inviteUser = defineServerAction<\n InviteUserInput,\n InviteUserResult\n>({\n id: \"team/invite-user\",\n description: \"Sends an invitation email to join the team\",\n visibility: \"customer\",\n tags: [\"team\", \"users\", \"invite\"],\n async run({ token, email }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Invite user requires a session token\");\n }\n\n if (!email || typeof email !== \"string\") {\n throw new Error(\"Invite user requires an email address\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n email_address: email\n });\n\n const endpoint = `${getApiOrigin()}/v3/invite?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] inviting user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to invite user\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Removes a user from the team.\n */\nexport const deleteUser = defineServerAction<\n DeleteUserInput,\n DeleteUserResult\n>({\n id: \"team/delete-user\",\n description: \"Removes a user from the team\",\n visibility: \"customer\",\n tags: [\"team\", \"users\", \"delete\"],\n async run({ token, email }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Delete user requires a session token\");\n }\n\n if (!email || typeof email !== \"string\") {\n throw new Error(\"Delete user requires an email address\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n email_address: email\n });\n\n const endpoint = `${getApiOrigin()}/v3/user?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deleting user via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to delete user\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Fetches the list of service accounts for a team.\n */\nexport const fetchServiceAccounts = defineServerAction<\n FetchServiceAccountsInput,\n FetchServiceAccountsResult\n>({\n id: \"team/fetch-service-accounts\",\n description: \"Fetches paginated list of service accounts\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\"],\n async run({ token, limit = 50, offset = 0, includeRevoked = false }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch service accounts requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const params = new URLSearchParams({\n customer_id: customerId,\n limit: limit.toString(),\n offset: offset.toString()\n });\n\n // Add filterRevoked parameter - API filters revoked when this param is present\n if (!includeRevoked) {\n params.set(\"filterRevoked\", \"false\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/service-accounts?${params.toString()}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching service accounts via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch service accounts request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n serviceAccounts: data.serviceAccounts || [],\n total: data.total || 0\n };\n }\n});\n\n/**\n * Revokes a service account.\n */\nexport const revokeServiceAccount = defineServerAction<\n RevokeServiceAccountInput,\n RevokeServiceAccountResult\n>({\n id: \"team/revoke-service-account\",\n description: \"Revokes a service account (soft delete)\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\", \"revoke\"],\n async run({ token, accountId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Revoke service account requires a session token\");\n }\n\n if (!accountId || typeof accountId !== \"string\") {\n throw new Error(\"Revoke service account requires an account ID\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/service-account/${encodeURIComponent(accountId)}?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] revoking service account via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to revoke service account\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Rotates a service account token.\n */\nexport const rotateServiceAccountToken = defineServerAction<\n RotateServiceAccountTokenInput,\n RotateServiceAccountTokenResult\n>({\n id: \"team/rotate-service-account-token\",\n description: \"Generates a new token for a service account\",\n visibility: \"customer\",\n tags: [\"team\", \"service-accounts\", \"rotate\"],\n async run({ token, accountId }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Rotate service account token requires a session token\");\n }\n\n if (!accountId || typeof accountId !== \"string\") {\n throw new Error(\"Rotate service account token requires an account ID\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/service-account/${encodeURIComponent(accountId)}/rotate-token?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] rotating service account token via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"POST\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to rotate service account token\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n const data = await response.json();\n \n return {\n serviceAccount: data.service_account,\n helmLoginCommand: data.helm_login_cmd || \"\",\n redeployHelm: data.redeploy_helm || []\n };\n }\n});\n\n/**\n * Fetches instances for the customer.\n */\nexport const fetchInstances = defineServerAction<\n FetchInstancesInput,\n FetchInstancesResult\n>({\n id: \"team/fetch-instances\",\n description: \"Fetches instances to determine service account usage\",\n visibility: \"customer\",\n tags: [\"team\", \"instances\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch instances requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/instances?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching instances via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch instances request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n instances: data.instances || []\n };\n }\n});\n\n/**\n * Fetches SAML configuration for the customer.\n */\nexport const fetchSamlConfig = defineServerAction<\n FetchSamlConfigInput,\n FetchSamlConfigResult\n>({\n id: \"team/fetch-saml-config\",\n description: \"Fetches SAML SSO configuration for the team\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Fetch SAML config requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] fetching SAML config via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"GET\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n throw new Error(\n `Fetch SAML config request failed (${response.status} ${response.statusText})`\n );\n }\n\n const data = await response.json();\n \n return {\n config: {\n samlAllowed: data.samlAllowed || false,\n samlEnabled: data.samlEnabled || false,\n entityId: data.entityId || \"\",\n acsUrl: data.acsUrl || \"\",\n hasIdpMetadata: data.hasIdpMetadata || false,\n hasIdpCert: data.hasIdpCert || false\n }\n };\n }\n});\n\n/**\n * Updates SAML configuration (uploads IdP metadata and certificate).\n */\nexport const updateSamlConfig = defineServerAction<\n UpdateSamlConfigInput,\n UpdateSamlConfigResult\n>({\n id: \"team/update-saml-config\",\n description: \"Uploads IdP metadata and certificate for SAML SSO\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"update\"],\n async run({ token, idpMetadataXml, idpPublicCert }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Update SAML config requires a session token\");\n }\n\n if (!idpMetadataXml || !idpPublicCert) {\n throw new Error(\"Both IdP metadata and certificate are required\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] updating SAML config via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({\n idpMetadataXml,\n idpPublicCert\n }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to update SAML configuration\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n/**\n * Toggles SAML authentication enabled/disabled.\n */\nexport const toggleSamlEnabled = defineServerAction<\n ToggleSamlEnabledInput,\n ToggleSamlEnabledResult\n>({\n id: \"team/toggle-saml-enabled\",\n description: \"Enables or disables SAML authentication\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"toggle\"],\n async run({ token, enabled }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Toggle SAML enabled requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/enable?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] toggling SAML enabled via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"PUT\",\n token,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ enabled }),\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to toggle SAML\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n const data = await response.json();\n \n return {\n success: true,\n samlEnabled: data.samlEnabled || enabled\n };\n }\n});\n\n/**\n * Removes SAML configuration (deprovisions SAML).\n */\nexport const deprovisionSaml = defineServerAction<\n DeprovisionSamlInput,\n DeprovisionSamlResult\n>({\n id: \"team/deprovision-saml\",\n description: \"Removes all SAML configuration\",\n visibility: \"customer\",\n tags: [\"team\", \"saml\", \"delete\"],\n async run({ token }, context) {\n if (!token || typeof token !== \"string\") {\n throw new Error(\"Deprovision SAML requires a session token\");\n }\n\n const customerId = getCustomerIdFromToken(token);\n const endpoint = `${getApiOrigin()}/v3/customer/saml/config?customer_id=${encodeURIComponent(customerId)}`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] deprovisioning SAML via %s\", endpoint);\n }\n\n const response = await authenticatedFetch(endpoint, {\n method: \"DELETE\",\n token,\n headers: { accept: \"application/json\" },\n signal: context?.signal\n });\n\n if (!response.ok) {\n let errorMessage = \"Failed to remove SAML configuration\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n\n// =============================================================================\n// Invite Accept/Refresh Actions\n// =============================================================================\n\nexport interface AcceptInviteInput {\n code: string;\n}\n\nexport interface AcceptInviteResult {\n token: string;\n}\n\nexport interface AcceptInviteError {\n code: \"invalid_code\" | \"expired\" | \"unknown\";\n message: string;\n}\n\n/**\n * Accepts a team invitation using the invite code from email.\n * Returns a JWT token on success that can be used to establish a session.\n */\nexport const acceptInvite = defineServerAction<\n AcceptInviteInput,\n AcceptInviteResult\n>({\n id: \"auth/accept-invite\",\n description: \"Accepts a team invitation and returns a session token\",\n visibility: \"customer\",\n tags: [\"auth\", \"invite\", \"join\"],\n async run({ code }) {\n if (!code || typeof code !== \"string\") {\n const error: AcceptInviteError = {\n code: \"invalid_code\",\n message: \"Invite code is required\"\n };\n throw error;\n }\n\n const endpoint = `${getApiOrigin()}/v3/invite/accept`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] accepting invite via %s\", endpoint);\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ code })\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n const error: AcceptInviteError = {\n code: \"invalid_code\",\n message: \"Invalid or expired invite code. Please check your code and try again.\"\n };\n throw error;\n }\n\n let errorMessage = \"Failed to accept invitation\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n\n const error: AcceptInviteError = {\n code: \"unknown\",\n message: errorMessage\n };\n throw error;\n }\n\n const payload = await response.json();\n const token = payload?.jwt ?? payload?.token;\n\n if (typeof token !== \"string\") {\n throw new Error(\"Invite accepted but no token returned\");\n }\n\n return { token };\n }\n});\n\nexport interface RefreshInviteInput {\n code: string;\n}\n\nexport interface RefreshInviteResult {\n success: boolean;\n}\n\n/**\n * Refreshes an expired invite by generating a new code and resending the email.\n * The original code is used to identify the invite to refresh.\n */\nexport const refreshInvite = defineServerAction<\n RefreshInviteInput,\n RefreshInviteResult\n>({\n id: \"auth/refresh-invite\",\n description: \"Refreshes an expired invite and resends the invitation email\",\n visibility: \"customer\",\n tags: [\"auth\", \"invite\", \"refresh\"],\n async run({ code }) {\n if (!code || typeof code !== \"string\") {\n throw new Error(\"Invite code is required\");\n }\n\n const endpoint = `${getApiOrigin()}/v3/invite/refresh`;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.debug(\"[portal-components] refreshing invite via %s\", endpoint);\n }\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n },\n body: JSON.stringify({ code })\n });\n\n // The API returns 200 even for non-existent codes to prevent code enumeration\n if (!response.ok) {\n let errorMessage = \"Failed to refresh invitation\";\n try {\n const data = await response.json();\n errorMessage = data.message || data.error || errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n\n return { success: true };\n }\n});\n","import { Buffer } from \"node:buffer\";\nimport type { ReactNode } from \"react\";\nimport Link from \"next/link\";\nimport { fetchCustomBranding } from \"../actions\";\n\nexport interface Customer {\n id: string;\n name: string;\n}\n\nexport interface TopNavLink {\n label: string;\n href?: string;\n icon: ReactNode;\n}\n\nexport interface TopNavProps {\n links?: TopNavLink[];\n hiddenLabels?: string[];\n additionalLinks?: TopNavLink[];\n order?: string[];\n userMenuLabel?: string;\n activeLabel?: string;\n customerName?: string;\n customers?: Customer[];\n currentCustomerId?: string;\n onChangeTeam?: (customerId: string) => Promise<void>;\n userMenuChildren?: ReactNode;\n}\n\nconst defaultHiddenLabels = [\"Download\"];\n\nconst defaultTopNavLinks: TopNavLink[] = [\n {\n label: \"Dashboard\",\n href: \"/\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <rect width=\"7\" height=\"9\" x=\"3\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"5\" x=\"14\" y=\"3\" rx=\"1\" />\n <rect width=\"7\" height=\"9\" x=\"14\" y=\"12\" rx=\"1\" />\n <rect width=\"7\" height=\"5\" x=\"3\" y=\"16\" rx=\"1\" />\n </svg>\n )\n },\n {\n label: \"Download\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" x2=\"12\" y1=\"15\" y2=\"3\" />\n </svg>\n )\n },\n {\n label: \"Install\",\n href: \"/install\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" x2=\"12\" y1=\"15\" y2=\"3\" />\n </svg>\n )\n },\n {\n label: \"Update\",\n href: \"/update\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8\" />\n <path d=\"M21 3v5h-5\" />\n </svg>\n )\n },\n {\n label: \"Security\",\n href: \"/security\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z\" />\n </svg>\n )\n },\n {\n label: \"Release History\",\n href: \"/release-history\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n <path d=\"M10 9H8\" />\n <path d=\"M16 13H8\" />\n <path d=\"M16 17H8\" />\n </svg>\n )\n },\n {\n label: \"License\",\n href: \"/license\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4\" />\n <path d=\"m21 2-9.6 9.6\" />\n <circle cx=\"7.5\" cy=\"15.5\" r=\"5.5\" />\n </svg>\n )\n },\n {\n label: \"Support\",\n href: \"/support\",\n icon: (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n className=\"h-4 w-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m4.93 4.93 4.24 4.24\" />\n <path d=\"m14.83 9.17 4.24-4.24\" />\n <path d=\"m14.83 14.83 4.24 4.24\" />\n <path d=\"m9.17 14.83-4.24 4.24\" />\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n </svg>\n )\n }\n];\n\nconst orderLinks = (links: TopNavLink[], order?: string[]) => {\n if (!order || order.length === 0) {\n return links;\n }\n\n const orderMap = new Map(order.map((label, index) => [label, index]));\n return links\n .map((link, index) => ({\n link,\n originalIndex: index,\n orderIndex: orderMap.has(link.label)\n ? (orderMap.get(link.label) as number)\n : order.length + index\n }))\n .sort((a, b) => {\n if (a.orderIndex === b.orderIndex) {\n return a.originalIndex - b.originalIndex;\n }\n return a.orderIndex - b.orderIndex;\n })\n .map((item) => item.link);\n};\n\n/**\n * TopNav renders the hero navigation bar shown on authenticated dashboards.\n */\nexport const TopNav = async ({\n links,\n hiddenLabels,\n additionalLinks,\n order,\n userMenuLabel,\n activeLabel,\n customerName,\n customers,\n currentCustomerId,\n onChangeTeam,\n userMenuChildren\n}: TopNavProps) => {\n const displayLabel = userMenuLabel || (customerName ? `Team: ${customerName}` : \"Team: Example\");\n let logo: string | undefined;\n let brandTitle: string | undefined;\n let customColor1: string | undefined;\n let customColor2: string | undefined;\n\n const normalizeColor = (color?: string) => {\n if (!color || typeof color !== \"string\") {\n return undefined;\n }\n\n const trimmed = color.trim();\n if (/^#?[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(trimmed)) {\n return trimmed.startsWith(\"#\") ? trimmed : `#${trimmed}`;\n }\n\n return trimmed;\n };\n\n try {\n const branding = await fetchCustomBranding();\n if (branding.brandingData) {\n const decoded = Buffer.from(branding.brandingData, \"base64\").toString(\n \"utf-8\"\n );\n\n try {\n const parsed = JSON.parse(decoded);\n if (parsed?.logo && typeof parsed.logo === \"string\") {\n logo = parsed.logo;\n }\n if (parsed?.title && typeof parsed.title === \"string\") {\n const normalizedTitle = parsed.title.trim();\n if (normalizedTitle) {\n brandTitle = normalizedTitle;\n }\n }\n if (parsed?.customColor1 && typeof parsed.customColor1 === \"string\") {\n customColor1 = normalizeColor(parsed.customColor1);\n }\n if (parsed?.customColor2 && typeof parsed.customColor2 === \"string\") {\n customColor2 = normalizeColor(parsed.customColor2);\n }\n } catch (error) {\n console.debug(\n \"[portal-components] unable to parse branding JSON\",\n error\n );\n }\n } else {\n console.debug(\"[portal-components] branding\", branding);\n }\n } catch (error) {\n console.debug(\"[portal-components] branding fetch failed\", error);\n }\n\n const baseLinks = links ?? defaultTopNavLinks;\n const computedHiddenLabels = hiddenLabels\n ? hiddenLabels\n : links\n ? undefined\n : defaultHiddenLabels;\n const hiddenSet = computedHiddenLabels ? new Set(computedHiddenLabels) : null;\n let resolvedLinks = baseLinks.filter(\n (link) => !hiddenSet?.has(link.label)\n );\n\n if (additionalLinks?.length) {\n resolvedLinks = [...resolvedLinks, ...additionalLinks];\n }\n\n resolvedLinks = orderLinks(resolvedLinks, order);\n\n const gradientStart = customColor1 ?? \"rgb(235, 102, 88)\";\n const gradientEnd = customColor2 ?? customColor1 ?? \"rgb(184, 83, 71)\";\n return (\n <div\n className=\"relative flex h-[280px] w-full items-start justify-center\"\n style={{\n backgroundImage:\n `linear-gradient(to top, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0) 33%), linear-gradient(${gradientStart}, ${gradientEnd})`,\n backgroundRepeat: \"no-repeat\",\n backgroundSize: \"100% 100%\"\n }}\n >\n <div className=\"mx-auto mt-[30px] w-full max-w-[1248px] px-6\">\n <div className=\"flex h-[135px] flex-col justify-between space-y-4 rounded bg-[#ffffffe6] px-6 pt-6 pb-4 shadow-[0_10px_60px_rgba(16,16,16,0.35)]\">\n <div className=\"flex items-center justify-between\">\n {logo || brandTitle ? (\n <div className=\"flex items-center gap-3\">\n {logo ? (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={logo}\n alt=\"Portal logo\"\n className=\"object-contain\"\n style={{\n maxWidth: \"240px\",\n maxHeight: \"48px\"\n }}\n />\n ) : null}\n {brandTitle ? (\n <span className=\"text-lg font-semibold text-gray-900\">\n {brandTitle}\n </span>\n ) : null}\n </div>\n ) : (\n <div />\n )}\n <details className=\"group relative\">\n <summary className=\"flex cursor-pointer items-center gap-2 text-sm font-medium text-gray-600 hover:text-gray-900 list-none\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"text-gray-500\"\n >\n <path d=\"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\"></path>\n <circle cx=\"12\" cy=\"7\" r=\"4\"></circle>\n </svg>\n <span>{displayLabel}</span>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"text-gray-500\"\n >\n <polyline points=\"6 9 12 15 18 9\"></polyline>\n </svg>\n </summary>\n <div className=\"absolute right-0 mt-2 w-48 rounded-md border border-gray-200 bg-white py-2 text-sm text-gray-700 shadow-lg z-50\">\n <Link\n href=\"/user-settings\"\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n User settings\n </Link>\n <Link\n href=\"/team-settings\"\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n Team settings\n </Link>\n {userMenuChildren}\n {/* Use regular anchor tag for logout to force hard navigation,\n which is more reliable in proxied/iframe scenarios */}\n <a\n href={`${process.env.NEXT_PUBLIC_BASE_PATH || \"\"}/?expired=1`}\n className=\"block w-full px-4 py-2 text-left hover:bg-gray-100\"\n >\n Logout\n </a>\n </div>\n </details>\n </div>\n <div className=\"mt-3 flex flex-wrap gap-3 border-b border-gray-200 pb-2 text-sm font-medium text-gray-500\">\n {resolvedLinks.map(({ label, icon, href }) => {\n const isActive = activeLabel === label;\n const className = `flex items-center gap-2 px-4 py-1 transition text-gray-500 ${\n isActive ? \"underline underline-offset-8 decoration-2\" : \"\"\n }`;\n\n if (href) {\n return (\n <Link key={label} href={href} className={className}>\n <span className={isActive ? \"text-gray-900\" : \"text-gray-500\"}>\n {icon}\n </span>\n <span>{label}</span>\n </Link>\n );\n }\n\n return (\n <button key={label} className={className} type=\"button\">\n <span className={isActive ? \"text-gray-900\" : \"text-gray-500\"}>\n {icon}\n </span>\n <span>{label}</span>\n </button>\n );\n })}\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nexport { defaultTopNavLinks };\n","import { ReactNode } from \"react\";\nimport { TopNav } from \"./top-nav\";\n\ninterface UpdateLayoutProps {\n children: ReactNode;\n}\n\nexport const UpdateLayout = ({ children }: UpdateLayoutProps) => {\n return (\n <div className=\"min-h-screen bg-white\">\n <TopNav activeLabel=\"Updates\" />\n <div className=\"px-6 py-8\">\n <div className=\"mx-auto w-full max-w-[1248px]\">\n {children}\n </div>\n </div>\n </div>\n );\n};\n\nUpdateLayout.displayName = \"UpdateLayout\";\n"]}
|