|
| 1 | +import { TKindWithVersion } from 'localTypes/search' |
| 2 | + |
| 3 | +type ApiVersion = string // "group/version" or "v1" for core |
| 4 | + |
| 5 | +// Parse "apps/v1" -> { group: "apps", version: "v1" } |
| 6 | +// Parse "v1" -> { group: "", version: "v1" } (core) |
| 7 | +const parseApiVersion = (apiVersion: ApiVersion) => { |
| 8 | + const parts = apiVersion.trim().split('/') |
| 9 | + return parts.length === 1 ? { group: '', version: parts[0] } : { group: parts[0], version: parts[1] } |
| 10 | +} |
| 11 | + |
| 12 | +/** |
| 13 | + * Build a lookup function: given (kind, apiVersion?) return the plural resource. |
| 14 | + * - apiVersion can be "group/version" or just "v1" for core. |
| 15 | + * - If apiVersion is omitted, we return the plural for the preferred version of that kind. |
| 16 | + * - Returns undefined if not uniquely determined. |
| 17 | + */ |
| 18 | +export const pluralByKind = |
| 19 | + (entries: readonly TKindWithVersion[]) => |
| 20 | + (kind: string, apiVersion?: ApiVersion): string | undefined => { |
| 21 | + const norm = (s: string) => s.trim() |
| 22 | + const kindNorm = norm(kind) |
| 23 | + |
| 24 | + // If apiVersion is provided, use it; otherwise we’ll consider all versions and prefer `preferred:true`. |
| 25 | + const gv = apiVersion ? parseApiVersion(apiVersion) : undefined |
| 26 | + |
| 27 | + const candidates = entries.filter(e => norm(e.kind) === kindNorm) |
| 28 | + |
| 29 | + if (candidates.length === 0) return undefined |
| 30 | + |
| 31 | + const filtered = gv |
| 32 | + ? candidates.filter(e => norm(e.group) === norm(gv.group) && e.version.version === gv.version) |
| 33 | + : candidates |
| 34 | + |
| 35 | + if (filtered.length === 0) return undefined |
| 36 | + |
| 37 | + // If version wasn’t specified, prefer entries where the version is marked preferred. |
| 38 | + const preferredFirst = gv |
| 39 | + ? filtered |
| 40 | + : [...filtered.filter(e => e.version.preferred), ...filtered.filter(e => !e.version.preferred)] |
| 41 | + |
| 42 | + // Collect plural resource names |
| 43 | + const resources = preferredFirst.map(e => e.version.resource).filter(Boolean) |
| 44 | + const uniq = Array.from(new Set(resources)) |
| 45 | + |
| 46 | + // If we didn’t specify a version and multiple distinct resources remain, |
| 47 | + // try to collapse by taking the first (preferred) only. |
| 48 | + if (!gv && uniq.length > 1) { |
| 49 | + const first = preferredFirst[0]?.version.resource |
| 50 | + return first ?? undefined |
| 51 | + } |
| 52 | + |
| 53 | + return uniq.length === 1 ? uniq[0] : undefined |
| 54 | + } |
0 commit comments