forked from redhat-developer/rhdh-e2e-test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin-metadata.ts
More file actions
766 lines (658 loc) · 26 KB
/
Copy pathplugin-metadata.ts
File metadata and controls
766 lines (658 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import fs from "fs-extra";
import path from "path";
import yaml from "js-yaml";
import { glob } from "zx";
import { deepMerge } from "./merge-yamls.js";
const OCI_REGISTRY_PREFIX =
"oci://ghcr.io/redhat-developer/rhdh-plugin-export-overlays";
// ── Types ─────────────────────────────────────────────────────────────────────
export interface PluginMetadata {
packagePath: string;
pluginConfig: Record<string, unknown>;
packageName: string;
sourceFile: string;
role?: string;
}
interface PackageCRD {
spec?: {
packageName?: string;
dynamicArtifact?: string;
backstage?: {
role?: string;
};
appConfigExamples?: Array<{
title?: string;
content?: Record<string, unknown>;
}>;
};
}
export interface PluginEntry {
package: string;
disabled?: boolean;
pluginConfig?: Record<string, unknown>;
[key: string]: unknown;
}
export interface DynamicPluginsConfig {
plugins?: PluginEntry[];
includes?: string[];
[key: string]: unknown;
}
// ── Detection ─────────────────────────────────────────────────────────────────
/**
* Detects if we're running in a nightly/periodic job context.
* Controls the entire nightly vs PR routing in deployment:
* - Nightly: uses metadata OCI refs (latest published versions), skips metadata injection
* - PR/local: uses metadata + OCI URL replacement
*
* Returns true when:
* - JOB_NAME contains "periodic-" (OpenShift CI nightly/periodic jobs), OR
* - E2E_NIGHTLY_MODE is set (manual override for local testing)
*/
export function isNightlyJob(): boolean {
// PR check takes precedence over nightly mode
if (process.env.GIT_PR_NUMBER) {
return false;
}
if (
process.env.E2E_NIGHTLY_MODE === "true" ||
process.env.E2E_NIGHTLY_MODE === "1"
) {
console.log("[PluginMetadata] Nightly mode (E2E_NIGHTLY_MODE is set)");
return true;
}
const jobName = process.env.JOB_NAME || "";
if (jobName.includes("periodic-")) {
console.log("[PluginMetadata] Nightly mode (periodic job detected)");
return true;
}
return false;
}
// ── Default Packages (DPDY) ──────────────────────────────────────────────────
const DEFAULT_PACKAGES_BASE_URL =
"https://raw.githubusercontent.com/redhat-developer/rhdh-plugin-export-overlays/refs/heads";
// release-1.10 still hosts default.packages.yaml in the rhdh repo (pre-migration)
const LEGACY_DEFAULT_PACKAGES_BASE_URL =
"https://raw.githubusercontent.com/redhat-developer/rhdh/refs/heads";
const DEFAULT_DPDY_OCI_REGISTRY = "registry.access.redhat.com/rhdh";
interface DefaultPackagesYaml {
packages?: {
enabled?: Array<{ package: string }>;
disabled?: Array<{ package: string }>;
};
}
/**
* Fetches the list of packages from default.packages.yaml (source for the
* dynamic-plugins.default.yaml — DPDY — in the catalog index image shipped
* with RHDH). Used in nightly mode to determine which plugins support
* {{inherit}} tag resolution vs which need full OCI refs from metadata.
*
* Branch is determined by RELEASE_BRANCH_NAME (set by OpenShift CI),
* defaulting to "main" for local development. For release-1.10 the file
* lives in the rhdh repo; all other branches use rhdh-plugin-export-overlays.
*/
export async function fetchDefaultPackages(): Promise<Set<string>> {
const branch = process.env.RELEASE_BRANCH_NAME;
if (!branch) {
if (process.env.CI) {
throw new Error(
"[PluginMetadata] RELEASE_BRANCH_NAME is required in CI to fetch default.packages.yaml",
);
}
console.log(
"[PluginMetadata] RELEASE_BRANCH_NAME not set — defaulting to 'main' (local dev)",
);
}
const resolvedBranch = branch || "main";
const baseUrl =
resolvedBranch === "release-1.10"
? LEGACY_DEFAULT_PACKAGES_BASE_URL
: DEFAULT_PACKAGES_BASE_URL;
const url = `${baseUrl}/${resolvedBranch}/default.packages.yaml`;
console.log(
`[PluginMetadata] Fetching default packages from ${url} (branch: ${resolvedBranch})...`,
);
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`[PluginMetadata] Failed to fetch default.packages.yaml: ${response.status} ${response.statusText}\n` +
` URL: ${url}\n` +
` Branch: ${resolvedBranch} (from RELEASE_BRANCH_NAME)`,
);
}
const content = await response.text();
const parsed = yaml.load(content) as DefaultPackagesYaml;
const packages = new Set<string>();
for (const list of [parsed?.packages?.enabled, parsed?.packages?.disabled]) {
for (const entry of list || []) {
if (entry.package) packages.add(entry.package);
}
}
console.log(
`[PluginMetadata] Found ${packages.size} packages in default.packages.yaml (branch: ${resolvedBranch})`,
);
return packages;
}
/**
* Resolves the OCI registry for a plugin's {{inherit}} ref in nightly mode.
*
* Resolution priority:
* 1. NIGHTLY_DPDY_OCI_REGISTRY_MAP — JSON object mapping registry → array of package names
* 2. NIGHTLY_DPDY_OCI_REGISTRY — blanket override for all plugins using {{inherit}}
* 3. Default: registry.access.redhat.com/rhdh
*/
export function getDpdyRegistry(packageName: string): string {
const map = process.env.NIGHTLY_DPDY_OCI_REGISTRY_MAP;
if (map) {
const parsed = JSON.parse(map) as Record<string, string[]>;
for (const [registry, packages] of Object.entries(parsed)) {
if (packages.includes(packageName)) return registry;
}
}
if (process.env.NIGHTLY_DPDY_OCI_REGISTRY) {
return process.env.NIGHTLY_DPDY_OCI_REGISTRY;
}
return DEFAULT_DPDY_OCI_REGISTRY;
}
// ── Utilities ─────────────────────────────────────────────────────────────────
/**
* Extracts the plugin name from a package path or OCI reference.
* Strips the `-dynamic` suffix so local paths and OCI refs for the same
* logical plugin produce the same key.
*
* Handles various formats:
* - Local path: ./dynamic-plugins/dist/backstage-community-plugin-tech-radar-dynamic
* - OCI with alias: oci://quay.io/rhdh/plugin@sha256:...!backstage-community-plugin-tech-radar
* - OCI without alias: oci://quay.io/rhdh/backstage-community-plugin-tech-radar:tag
*/
export function extractPluginName(packageRef: string): string {
const ref = packageRef.includes("!") ? packageRef.split("!")[0] : packageRef;
const match = ref.match(/\/([^/:@]+)(?:[:@].*)?$/);
return (match?.[1] || packageRef).replace(/-dynamic$/, "");
}
/**
* Derives the displayName from a packageName.
* @backstage-community/plugin-tech-radar → backstage-community-plugin-tech-radar
*/
function toDisplayName(packageName: string): string {
return packageName.replace(/^@/, "").replace(/\//g, "-");
}
// Append the __coverage suffix to an OCI image tag, before the optional
// !<extractPath> — the instrumented variant the overlay's release publish
// builds. The tag group is greedy up to the first `!`, so the suffix always
// lands at the end of the tag.
function toCoverageImageRef(ref: string): string {
return ref.replace(/(:[^!]+)/, "$1__coverage");
}
// ── Metadata Loading ──────────────────────────────────────────────────────────
export const DEFAULT_METADATA_PATH = "../metadata";
export function getMetadataDirectory(
metadataPath: string = DEFAULT_METADATA_PATH,
): string | null {
const resolvedPath = path.resolve(metadataPath);
if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory()) {
console.log(`[PluginMetadata] Using metadata directory: ${resolvedPath}`);
return resolvedPath;
}
console.log(`[PluginMetadata] Metadata directory not found: ${resolvedPath}`);
return null;
}
export async function parseMetadataFile(
filePath: string,
): Promise<PluginMetadata> {
const content = await fs.readFile(filePath, "utf8");
const parsed = yaml.load(content) as PackageCRD;
const packagePath = parsed?.spec?.dynamicArtifact;
const packageName = parsed?.spec?.packageName;
const pluginConfig = parsed?.spec?.appConfigExamples?.[0]?.content;
const role = parsed?.spec?.backstage?.role;
if (!packagePath) {
throw new Error(
`[PluginMetadata] Missing required field spec.dynamicArtifact in ${filePath}`,
);
}
if (!packageName) {
throw new Error(
`[PluginMetadata] Missing required field spec.packageName in ${filePath}`,
);
}
return {
packagePath,
pluginConfig: pluginConfig || {},
packageName,
sourceFile: filePath,
role,
};
}
export async function parseAllMetadataFiles(
metadataDir: string,
): Promise<Map<string, PluginMetadata>> {
const pattern = path.join(metadataDir, "*.yaml");
const files = await glob(pattern);
console.log(
`[PluginMetadata] Found ${files.length} metadata files in ${metadataDir}`,
);
const metadataMap = new Map<string, PluginMetadata>();
for (const file of files) {
const metadata = await parseMetadataFile(file);
const pluginName = extractPluginName(metadata.packagePath);
metadataMap.set(pluginName, metadata);
console.log(
`[PluginMetadata] Mapped plugin: ${pluginName} <- ${metadata.packagePath}`,
);
}
console.log(
`[PluginMetadata] Successfully parsed ${metadataMap.size} plugin metadata entries`,
);
return metadataMap;
}
/**
* Loads and validates metadata from the workspace metadata directory.
* @throws Error if metadata directory not found or no valid metadata files
*/
async function loadMetadata(
metadataPath: string,
): Promise<[string, Map<string, PluginMetadata>]> {
const metadataDir = getMetadataDirectory(metadataPath);
if (!metadataDir) {
throw new Error(
`[PluginMetadata] Metadata directory not found at: ${path.resolve(metadataPath)}`,
);
}
const metadataMap = await parseAllMetadataFiles(metadataDir);
if (metadataMap.size === 0) {
throw new Error(
`[PluginMetadata] No valid metadata files found in ${metadataDir}`,
);
}
return [metadataDir, metadataMap];
}
/**
* Tries to load metadata, returns empty map if not available.
* Used by processPluginsForDeployment where metadata is optional.
*/
async function tryLoadMetadata(
metadataPath: string,
): Promise<Map<string, PluginMetadata>> {
const metadataDir = getMetadataDirectory(metadataPath);
if (!metadataDir) return new Map();
return await parseAllMetadataFiles(metadataDir);
}
// ── PR: Fetch OCI URLs ───────────────────────────────────────────────────────
/**
* Fetches plugin versions from source repo and builds OCI URL map.
* Only called when GIT_PR_NUMBER is set.
*/
async function getOCIUrlsForPR(
workspacePath: string,
prNumber: string,
): Promise<Map<string, string>> {
const ociUrls = new Map<string, string>();
const sourceJsonPath = path.join(workspacePath, "source.json");
const pluginsListPath = path.join(workspacePath, "plugins-list.yaml");
if (!fs.existsSync(sourceJsonPath)) {
throw new Error(
`[PluginMetadata] PR build requires source.json but not found at: ${sourceJsonPath}`,
);
}
if (!fs.existsSync(pluginsListPath)) {
throw new Error(
`[PluginMetadata] PR build requires plugins-list.yaml but not found at: ${pluginsListPath}`,
);
}
const sourceJson = JSON.parse(await fs.readFile(sourceJsonPath, "utf-8"));
const { repo, "repo-ref": ref, "repo-flat": repoFlat } = sourceJson;
if (!repo) {
throw new Error(
`[PluginMetadata] source.json is missing required 'repo' field: ${sourceJsonPath}`,
);
}
if (!ref) {
throw new Error(
`[PluginMetadata] source.json is missing required 'repo-ref' field: ${sourceJsonPath}`,
);
}
const match = repo.match(/github\.com\/(.+?)(?:\.git)?$/);
if (!match) {
throw new Error(
`[PluginMetadata] Failed to parse GitHub repo from source.json: ${repo}`,
);
}
const ownerRepo = match[1];
const pluginsListContent = await fs.readFile(pluginsListPath, "utf-8");
const pluginsListData = yaml.load(pluginsListContent) as Record<
string,
unknown
> | null;
if (!pluginsListData || typeof pluginsListData !== "object") {
throw new Error(
`[PluginMetadata] plugins-list.yaml is empty or invalid: ${pluginsListPath}`,
);
}
const pluginPaths = Object.keys(pluginsListData);
const workspaceName = path.basename(workspacePath);
console.log(
`[PluginMetadata] Fetching versions for ${pluginPaths.length} plugins from source...`,
);
for (const pluginPath of pluginPaths) {
const pkgJsonPath = repoFlat
? `${pluginPath}/package.json`
: `workspaces/${workspaceName}/${pluginPath}/package.json`;
const rawUrl = `https://raw.githubusercontent.com/${ownerRepo}/${ref}/${pkgJsonPath}`;
const res = await fetch(rawUrl);
if (!res.ok) {
throw new Error(
`[PluginMetadata] Failed to fetch package.json for ${pluginPath}: ${res.status} ${res.statusText}\n` +
` URL: ${rawUrl}`,
);
}
const pkgJson = (await res.json()) as { name?: string; version?: string };
if (!pkgJson.name) {
throw new Error(
`[PluginMetadata] package.json is missing 'name' field for ${pluginPath}\n` +
` URL: ${rawUrl}`,
);
}
if (!pkgJson.version) {
throw new Error(
`[PluginMetadata] package.json is missing 'version' field for ${pluginPath}\n` +
` URL: ${rawUrl}`,
);
}
const { name, version } = pkgJson;
const displayName = toDisplayName(name);
// TODO(RHDHBUGS-2530): Remove !alias suffix once Konflux builds include
// io.backstage.dynamic-packages annotation.
const ociUrl = `${OCI_REGISTRY_PREFIX}/${displayName}:pr_${prNumber}__${version}!${displayName}`;
ociUrls.set(displayName, ociUrl);
console.log(`[PluginMetadata] ${displayName} -> ${ociUrl}`);
}
return ociUrls;
}
// ── Core: Unified Plugin Processing ──────────────────────────────────────────
/**
* Resolves plugin package references to their target OCI URLs where applicable.
*
* Resolution priority for each plugin:
* 1. PR OCI URL — if GIT_PR_NUMBER set and a PR image was published for this plugin
* 2. Metadata OCI ref — uses dynamicArtifact from metadata (latest published version)
* 3. Unchanged — local paths, npm packages, or other formats kept as-is
*/
/**
* Returns a stable merge key for a plugin entry so OCI and local path for the same
* logical plugin match when merging dynamic-plugins configs. Strips a trailing
* "-dynamic" so e.g. backstage-community-plugin-catalog-backend-module-keycloak-dynamic
* and ...-keycloak (from OCI) map to the same key.
*/
export function getNormalizedPluginMergeKey(entry: {
package?: string;
}): string {
const pkg = entry?.package;
if (pkg === undefined || pkg === "") {
return "";
}
return extractPluginName(pkg);
}
async function resolvePluginPackages(
plugins: PluginEntry[],
metadataMap: Map<string, PluginMetadata>,
metadataPath: string,
dpdyPackages: Set<string> | null = null,
): Promise<PluginEntry[]> {
const workspaceRoot = path.resolve(metadataPath, "..");
// Build PR OCI URLs if applicable
const prNumber = process.env.GIT_PR_NUMBER;
let prOciUrls: Map<string, string> | null = null;
if (prNumber) {
console.log(
`[PluginMetadata] PR build detected (PR #${prNumber}), fetching OCI URLs...`,
);
prOciUrls = await getOCIUrlsForPR(workspaceRoot, prNumber);
}
// A dedicated coverage run swaps rolled-out frontend plugins to their
// instrumented __coverage image so the browser exposes window.__coverage__.
//
// This is gated on E2E_NIGHTLY_COVERAGE (an explicit opt-in), NOT on the
// ambient E2E_COLLECT_COVERAGE: the functional nightly runs with coverage
// collection on by default but deploys RELEASED images, and the __coverage
// variant is built non-fatally by the overlay release publish — so swapping
// there could point at a tag that doesn't exist and break the deployment.
// Requiring the explicit opt-in keeps the functional nightly's resolution
// identical to today; only a coverage-dedicated run (which ensures the
// images exist) sets the flag. The coverage-anchors/ check further restricts
// the swap to rolled-out workspaces.
const coverageSwap =
process.env.E2E_NIGHTLY_COVERAGE === "true" &&
fs.existsSync(path.join(workspaceRoot, "coverage-anchors"));
return plugins.map((plugin) => {
const pkg = plugin.package;
const pluginName = extractPluginName(pkg);
const metadata = metadataMap.get(pluginName);
// 1. With metadata: resolve to PR OCI URL, {{inherit}}, or metadata's dynamicArtifact
if (metadata?.packageName) {
const displayName = toDisplayName(metadata.packageName);
// PR: use PR-specific OCI URL if this plugin is part of the PR build
if (prOciUrls) {
const prUrl = prOciUrls.get(displayName);
if (prUrl) {
const usesCoverage =
process.env.E2E_COLLECT_COVERAGE === "true" &&
metadata.role === "frontend-plugin";
const resolved = usesCoverage ? toCoverageImageRef(prUrl) : prUrl;
console.log(`[PluginMetadata] PR: ${pkg} → ${resolved}`);
return { ...plugin, package: resolved };
}
}
// Nightly: if the plugin is in default.packages.yaml and its metadata
// spec.dynamicArtifact is an OCI ref, use {{inherit}} — RHDH resolves
// both the OCI tag and default config from its built-in DPDY.
// Registry: getDpdyRegistry() (env var overrides > default RHEC).
if (
dpdyPackages?.has(metadata.packageName) &&
metadata.packagePath.startsWith("oci://")
) {
// In a coverage run, a {{inherit}} ref would deploy the Konflux catalog
// image (registry.access.redhat.com/rhdh), which we can't instrument.
// Bypass it and deploy the overlay's instrumented __coverage build from
// ghcr (metadata.packagePath) — same plugin source, just built by us, so
// the run can collect coverage. The functional nightly (no coverage
// opt-in) still uses {{inherit}}, i.e. the shipped Konflux build.
if (coverageSwap && metadata.role === "frontend-plugin") {
const resolved = toCoverageImageRef(metadata.packagePath);
console.log(`[PluginMetadata] DPDY coverage: ${pkg} → ${resolved}`);
return { ...plugin, package: resolved };
}
const registry = getDpdyRegistry(metadata.packageName);
const inheritRef = `oci://${registry}/${displayName}:{{inherit}}`;
console.log(`[PluginMetadata] DPDY inherit: ${pkg} → ${inheritRef}`);
return { ...plugin, package: inheritRef };
}
// OCI: use metadata's dynamicArtifact directly (not in default.packages.yaml, or not nightly).
// For a rolled-out frontend plugin in a coverage run, swap to the
// instrumented __coverage image so the nightly can collect coverage.
if (metadata.packagePath.startsWith("oci://")) {
const resolved =
coverageSwap && metadata.role === "frontend-plugin"
? toCoverageImageRef(metadata.packagePath)
: metadata.packagePath;
console.log(`[PluginMetadata] ${pkg} → ${resolved}`);
return { ...plugin, package: resolved };
}
// Wrapper (local path): metadata is the source of truth.
// The user config may have a stale OCI ref from a previous version.
if (pkg !== metadata.packagePath) {
console.log(`[PluginMetadata] ${pkg} → ${metadata.packagePath}`);
}
return { ...plugin, package: metadata.packagePath };
}
// 2. No metadata — keep as-is (cross-workspace, npm packages, etc.)
return plugin;
});
}
/**
* Injects plugin configurations from metadata into a dynamic plugins config.
* Metadata config serves as the base, user-provided pluginConfig overrides it.
*/
function injectMetadataConfig(
dynamicPluginsConfig: DynamicPluginsConfig,
metadataMap: Map<string, PluginMetadata>,
): DynamicPluginsConfig {
if (!dynamicPluginsConfig.plugins) {
return dynamicPluginsConfig;
}
const augmentedPlugins = dynamicPluginsConfig.plugins.map((plugin) => {
const pluginName = extractPluginName(plugin.package);
const metadata = metadataMap.get(pluginName);
if (!metadata) {
console.log(
`[PluginMetadata] No metadata found for: ${pluginName} (from ${plugin.package})`,
);
return plugin;
}
console.log(
`[PluginMetadata] Injecting config for: ${pluginName} (from ${plugin.package})`,
);
const mergedPluginConfig = deepMerge(
metadata.pluginConfig,
plugin.pluginConfig || {},
);
return {
...plugin,
pluginConfig: mergedPluginConfig,
};
});
return {
...dynamicPluginsConfig,
plugins: augmentedPlugins,
};
}
// ── Public API ────────────────────────────────────────────────────────────────
/**
* Generates dynamic-plugins configuration for wrapper plugins
* that need to be disabled. Each plugin entry contains:
* - package: ./dynamic-plugins/dist/$plugin-name
* - disabled: true
*
* @param plugins list of wrapper plugin names
* @returns Dynamic plugins configuration that disables listed wrapper plugins
*/
export function disablePluginWrappers(plugins: string[]): DynamicPluginsConfig {
const pluginConfig: DynamicPluginsConfig = {
plugins: [],
};
for (const plugin of plugins) {
pluginConfig.plugins!.push({
package: `./dynamic-plugins/dist/${plugin}`,
disabled: true,
});
}
return pluginConfig;
}
/**
* Auto-generates plugin entries from workspace metadata files.
* Creates raw entries with local paths and disabled: false.
* Does NOT include pluginConfig — that's handled by processPluginsForDeployment.
*
* @param metadataPath Optional custom path to metadata directory
* @returns Plugin entries discovered from metadata
*/
export async function generatePluginsFromMetadata(
metadataPath: string = DEFAULT_METADATA_PATH,
): Promise<DynamicPluginsConfig> {
console.log(
"[PluginMetadata] Auto-generating plugin entries from metadata...",
);
const [, metadataMap] = await loadMetadata(metadataPath);
const plugins: PluginEntry[] = [];
for (const [pluginName, metadata] of metadataMap) {
console.log(
`[PluginMetadata] Adding plugin: ${pluginName} (${metadata.packagePath})`,
);
plugins.push({
package: metadata.packagePath,
disabled: false,
});
}
console.log(
`[PluginMetadata] Generated ${plugins.length} plugin entries from metadata`,
);
return { plugins };
}
function selectMetadataForInjection(
metadataMap: Map<string, PluginMetadata>,
nightly: boolean,
dpdyPackages: Set<string> | null,
): Map<string, PluginMetadata> | null {
if (
!process.env.CI &&
process.env.RHDH_SKIP_PLUGIN_METADATA_INJECTION === "true"
)
return null;
if (metadataMap.size === 0) return null;
if (!nightly) return metadataMap;
if (!dpdyPackages) return null;
// Nightly: only inject config for plugins NOT in default.packages.yaml whose
// metadata is OCI. DPDY plugins get both config and OCI tag via {{inherit}}.
return new Map(
[...metadataMap].filter(
([, m]) =>
!dpdyPackages.has(m.packageName) && m.packagePath.startsWith("oci://"),
),
);
}
/**
* Processes a dynamic plugins configuration for deployment.
* Single entry point for both PR and nightly flows.
*
* Operations (in order):
* 1. Inject appConfigExamples from metadata:
* - PR/local: all plugins with metadata (unless RHDH_SKIP_PLUGIN_METADATA_INJECTION)
* - Nightly: only plugins NOT in default.packages.yaml with OCI metadata
* (plugins in default.packages.yaml get both config and OCI tag via {{inherit}})
* 2. Resolve all packages:
* - PR with GIT_PR_NUMBER: workspace plugins → pr_ OCI tags
* - Nightly DPDY + OCI: {{inherit}} tag with configurable registry
* (NIGHTLY_DPDY_OCI_REGISTRY_MAP > NIGHTLY_DPDY_OCI_REGISTRY > registry.access.redhat.com/rhdh)
* - Nightly (not in default.packages.yaml) / local: metadata's dynamicArtifact as-is
*
* @param config The merged dynamic plugins configuration
* @param metadataPath Optional custom path to metadata directory
* @param dpdyPackages Optional pre-loaded DPDY package set (for testing; fetched automatically if omitted in nightly)
* @returns Processed configuration ready for deployment
*/
export async function processPluginsForDeployment(
config: DynamicPluginsConfig,
metadataPath: string = DEFAULT_METADATA_PATH,
dpdyPackages?: Set<string>,
): Promise<DynamicPluginsConfig> {
if (!config.plugins) return config;
const nightly = isNightlyJob();
const [metadataMap, resolvedDpdyPackages] = await Promise.all([
tryLoadMetadata(metadataPath),
nightly ? (dpdyPackages ?? fetchDefaultPackages()) : Promise.resolve(null),
]);
let result = { ...config };
// Inject appConfigExamples from metadata
const metadataToInject = selectMetadataForInjection(
metadataMap,
nightly,
resolvedDpdyPackages,
);
if (metadataToInject && metadataToInject.size > 0) {
console.log(
`[PluginMetadata] Injecting metadata configs for ${metadataToInject.size} plugin(s)...`,
);
result = injectMetadataConfig(result, metadataToInject);
}
// Resolve all packages to OCI references
console.log("[PluginMetadata] Resolving plugin packages...");
result = {
...result,
plugins: await resolvePluginPackages(
result.plugins!,
metadataMap,
metadataPath,
resolvedDpdyPackages,
),
};
return result;
}