@di-framework/cli-plugin-platform 6.1.2 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +154 -12
  2. package/dist/args.d.ts +8 -0
  3. package/dist/args.js +73 -28
  4. package/dist/assets/http-adapter.js +4 -1
  5. package/dist/assets/platform/README.md +68 -19
  6. package/dist/assets/platform/index.ts.tmpl +1 -1
  7. package/dist/assets/platform/tsconfig.json +2 -2
  8. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  9. package/dist/build.d.ts +27 -4
  10. package/dist/build.js +159 -18
  11. package/dist/bundle.d.ts +85 -0
  12. package/dist/bundle.js +608 -0
  13. package/dist/command.js +85 -3
  14. package/dist/console/catalog.js +2 -1
  15. package/dist/console/cluster.d.ts +4 -2
  16. package/dist/console/cluster.js +38 -40
  17. package/dist/control/auth.js +14 -2
  18. package/dist/controller/client.d.ts +47 -0
  19. package/dist/controller/client.js +157 -0
  20. package/dist/controller/commands.d.ts +48 -0
  21. package/dist/controller/commands.js +584 -0
  22. package/dist/controller/credentials.d.ts +63 -0
  23. package/dist/controller/credentials.js +156 -0
  24. package/dist/controller/index.d.ts +6 -0
  25. package/dist/controller/index.js +6 -0
  26. package/dist/controller/oidc.d.ts +54 -0
  27. package/dist/controller/oidc.js +121 -0
  28. package/dist/controller/registry.d.ts +15 -0
  29. package/dist/controller/registry.js +47 -0
  30. package/dist/controller/schema.d.ts +157 -0
  31. package/dist/controller/schema.js +1 -0
  32. package/dist/controller/sse.d.ts +12 -0
  33. package/dist/controller/sse.js +61 -0
  34. package/dist/controller/trust.d.ts +14 -0
  35. package/dist/controller/trust.js +39 -0
  36. package/dist/deploy.d.ts +14 -7
  37. package/dist/deploy.js +96 -5
  38. package/dist/deps.d.ts +4 -0
  39. package/dist/destroy.js +26 -2
  40. package/dist/environment-names.d.ts +6 -0
  41. package/dist/environment-names.js +10 -0
  42. package/dist/index.d.ts +5 -3
  43. package/dist/index.js +5 -3
  44. package/dist/manifest.d.ts +45 -1
  45. package/dist/manifest.js +197 -4
  46. package/dist/pglite-encryption.d.ts +79 -0
  47. package/dist/pglite-encryption.js +196 -0
  48. package/dist/pglite.d.ts +61 -4
  49. package/dist/pglite.js +124 -40
  50. package/dist/project.d.ts +7 -0
  51. package/dist/project.js +35 -0
  52. package/dist/publish.d.ts +7 -1
  53. package/dist/publish.js +33 -1
  54. package/dist/service.d.ts +34 -0
  55. package/dist/service.js +156 -145
  56. package/dist/target.d.ts +7 -1
  57. package/dist/target.js +19 -0
  58. package/dist/workload.d.ts +50 -12
  59. package/dist/workload.js +239 -44
  60. package/package.json +1 -1
package/dist/bundle.js ADDED
@@ -0,0 +1,608 @@
1
+ import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { discoverActors } from './actors.js';
5
+ import { discoverBindings } from './bindings.js';
6
+ import { buildComponent, canonicalBuildDigest, requirementsForProject, } from './build.js';
7
+ import { discoverScheduledJobs } from './cron.js';
8
+ import { DEFAULT_DEPS } from './deps.js';
9
+ import { resolveApplication } from './discovery.js';
10
+ import { findDeployManifest, interpolateEnv, optionalDeployEnvironment, parseDeployManifest, parseManifestBindings, parseManifestSecrets, } from './manifest.js';
11
+ import { loadProject } from './project.js';
12
+ import { ociReference, projectRelativePath } from './publish.js';
13
+ import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
14
+ import { materializeRegistry, registryReferenceHost, registryUsesPlainHttp, } from './registry.js';
15
+ import { invalidUsage, toolFailed } from './support.js';
16
+ import { isControllerBackedTarget, resolveConnection, resolveTarget, } from './target.js';
17
+ import { parseToml } from './toml.js';
18
+ import { deploymentResourceName, renderWorkloadManifest } from './workload.js';
19
+ export { canonicalBuildDigest };
20
+ export const PASSTHROUGH_LABEL_PREFIX = 'app.di-framework.dev/';
21
+ export function parseBuildArgs(args) {
22
+ if (args.length === 0)
23
+ return {};
24
+ const result = {};
25
+ let i = 0;
26
+ while (i < args.length) {
27
+ const arg = args[i];
28
+ if (arg === '--bundle' || arg.startsWith('--bundle=')) {
29
+ const value = arg === '--bundle' ? args[++i] : arg.slice('--bundle='.length);
30
+ if (!value || value.startsWith('-'))
31
+ invalidUsage('Missing value for --bundle', arg);
32
+ result.bundle = value;
33
+ i += 1;
34
+ continue;
35
+ }
36
+ if (arg === '--env' || arg.startsWith('--env=')) {
37
+ const value = arg === '--env' ? args[++i] : arg.slice('--env='.length);
38
+ if (value !== 'prod' && value !== 'staging') {
39
+ invalidUsage('Invalid --env value; expected "prod" or "staging"', arg);
40
+ }
41
+ result.env = value;
42
+ i += 1;
43
+ continue;
44
+ }
45
+ if (arg === '--target' || arg.startsWith('--target=')) {
46
+ const value = arg === '--target' ? args[++i] : arg.slice('--target='.length);
47
+ if (!value || value.startsWith('-'))
48
+ invalidUsage('Missing value for --target', arg);
49
+ result.target = value;
50
+ i += 1;
51
+ continue;
52
+ }
53
+ if (arg === '--registry' || arg.startsWith('--registry=')) {
54
+ const value = arg === '--registry' ? args[++i] : arg.slice('--registry='.length);
55
+ if (!value || value.startsWith('-'))
56
+ invalidUsage('Missing value for --registry', arg);
57
+ result.registry = value;
58
+ i += 1;
59
+ continue;
60
+ }
61
+ if (arg === '--tag' || arg.startsWith('--tag=')) {
62
+ const value = arg === '--tag' ? args[++i] : arg.slice('--tag='.length);
63
+ if (!value || value.startsWith('-'))
64
+ invalidUsage('Missing value for --tag', arg);
65
+ result.tag = value;
66
+ i += 1;
67
+ continue;
68
+ }
69
+ if (arg.startsWith('-')) {
70
+ invalidUsage(`Unknown option: ${arg}`, arg);
71
+ }
72
+ if (result.name !== undefined) {
73
+ invalidUsage(`Unexpected argument: ${arg}`, arg);
74
+ }
75
+ result.name = arg;
76
+ i += 1;
77
+ }
78
+ if (result.bundle === undefined) {
79
+ const first = args[0];
80
+ invalidUsage(`platform build does not accept arguments without --bundle: ${first}`, first);
81
+ }
82
+ return result;
83
+ }
84
+ function loadBundleManifestConfig(startDirectory, env, hasExplicitRegistryOrPublish) {
85
+ const path = findDeployManifest(startDirectory);
86
+ if (path === undefined)
87
+ return {};
88
+ const source = readFileSync(path, 'utf8');
89
+ if (hasExplicitRegistryOrPublish) {
90
+ const raw = interpolateEnv(parseToml(source), env, path);
91
+ if (raw.targets === undefined) {
92
+ return {
93
+ env: optionalDeployEnvironment(raw.env, 'env', path),
94
+ bindings: parseManifestBindings(raw.bindings, 'bindings', path),
95
+ secrets: parseManifestSecrets(raw.secrets, 'secrets', path),
96
+ };
97
+ }
98
+ }
99
+ const manifest = parseDeployManifest(path, source, env);
100
+ return {
101
+ manifest,
102
+ env: manifest.env,
103
+ bindings: manifest.bindings,
104
+ secrets: manifest.secrets,
105
+ };
106
+ }
107
+ export function normalizeSha256Digest(digest) {
108
+ return digest.startsWith('sha256:') ? digest : `sha256:${digest}`;
109
+ }
110
+ export function pinImageToDigest(reference, digest) {
111
+ const normalizedDigest = normalizeSha256Digest(digest);
112
+ const atIndex = reference.indexOf('@');
113
+ const withoutDigest = atIndex >= 0 ? reference.slice(0, atIndex) : reference;
114
+ const lastSlash = withoutDigest.lastIndexOf('/');
115
+ const lastColon = withoutDigest.lastIndexOf(':');
116
+ const repository = lastColon > lastSlash ? withoutDigest.slice(0, lastColon) : withoutDigest;
117
+ return `${repository}@${normalizedDigest}`;
118
+ }
119
+ function parseManifestDescriptorDigest(stdout) {
120
+ let parsed = null;
121
+ try {
122
+ parsed = JSON.parse(stdout);
123
+ }
124
+ catch {
125
+ // handled below
126
+ }
127
+ const digest = typeof parsed === 'object' && parsed !== null ? parsed.digest : undefined;
128
+ if (typeof digest !== 'string' || !/^sha256:[0-9a-f]{64}$/i.test(digest)) {
129
+ throw new Error(`Failed to resolve OCI manifest digest from oras descriptor: ${stdout.trim()}`);
130
+ }
131
+ return digest.toLowerCase();
132
+ }
133
+ async function publishWithBundleOptions(context) {
134
+ const { project, connection, build, io, deps, tag, credentials } = context;
135
+ const repository = credentials?.repository ?? project.witName;
136
+ const resolvedTag = tag ?? `sha256-${build.deploymentDigest}`;
137
+ const pushReference = `${registryReferenceHost(connection.registry.push)}/${repository}:${resolvedTag}`;
138
+ const pullReference = `${registryReferenceHost(connection.registry.pull)}/${repository}:${resolvedTag}`;
139
+ const configPath = resolve(project.projectRoot, '.di-framework', 'oci-config.json');
140
+ const componentPath = projectRelativePath(project.projectRoot, project.outputPath);
141
+ const projectConfigPath = projectRelativePath(project.projectRoot, configPath);
142
+ const transportArgs = registryUsesPlainHttp(connection.registry) ? ['--plain-http'] : [];
143
+ let tempAuthDir;
144
+ let authArgs = [];
145
+ if (credentials?.registryConfigPath) {
146
+ authArgs = ['--registry-config', credentials.registryConfigPath];
147
+ }
148
+ else if (credentials?.username || credentials?.token) {
149
+ tempAuthDir = mkdtempSync(join(tmpdir(), 'di-framework-oras-'));
150
+ const tempConfigPath = join(tempAuthDir, 'config.json');
151
+ const authEntry = {};
152
+ if (credentials.username) {
153
+ authEntry.auth = Buffer.from(`${credentials.username}:${credentials.password ?? ''}`).toString('base64');
154
+ }
155
+ if (credentials.token) {
156
+ authEntry.identitytoken = credentials.token;
157
+ }
158
+ const refHost = registryReferenceHost(connection.registry.push);
159
+ const serverHost = refHost.replace(/\/.*$/, '');
160
+ const config = {
161
+ auths: {
162
+ [serverHost]: authEntry,
163
+ [refHost]: authEntry,
164
+ },
165
+ };
166
+ const fd = openSync(tempConfigPath, 'wx', 0o600);
167
+ try {
168
+ writeFileSync(fd, `${JSON.stringify(config)}\n`, 'utf8');
169
+ }
170
+ finally {
171
+ closeSync(fd);
172
+ }
173
+ authArgs = ['--registry-config', tempConfigPath];
174
+ }
175
+ try {
176
+ io.stdout.write(`Publishing ${componentPath} as ${pushReference}...\n`);
177
+ if (!tag) {
178
+ const existing = await deps.runCaptured('oras', ['manifest', 'fetch', ...transportArgs, ...authArgs, '--descriptor', pushReference], { cwd: project.projectRoot });
179
+ if (existing.exitCode === 0) {
180
+ io.stdout.write(`OCI tag ${pushReference} already exists; keeping it immutable.\n`);
181
+ const existingDigest = parseManifestDescriptorDigest(existing.stdout);
182
+ return {
183
+ artifactDigest: existingDigest,
184
+ digest: build.deploymentDigest,
185
+ pullReference,
186
+ pushReference,
187
+ reference: pushReference,
188
+ };
189
+ }
190
+ }
191
+ const pushed = await deps.runner('oras', [
192
+ 'push',
193
+ ...transportArgs,
194
+ ...authArgs,
195
+ '--config',
196
+ `${projectConfigPath}:application/vnd.wasm.config.v0+json`,
197
+ pushReference,
198
+ `${componentPath}:application/wasm`,
199
+ ], { cwd: project.projectRoot });
200
+ if (pushed.exitCode !== 0) {
201
+ throw toolFailed('oras push', pushed.exitCode);
202
+ }
203
+ const descriptor = await deps.runCaptured('oras', ['manifest', 'fetch', ...transportArgs, ...authArgs, '--descriptor', pushReference], { cwd: project.projectRoot });
204
+ if (descriptor.exitCode !== 0) {
205
+ throw toolFailed('oras manifest fetch', descriptor.exitCode);
206
+ }
207
+ const manifestDigest = parseManifestDescriptorDigest(descriptor.stdout);
208
+ return {
209
+ artifactDigest: manifestDigest,
210
+ digest: build.deploymentDigest,
211
+ pullReference,
212
+ pushReference,
213
+ reference: pushReference,
214
+ };
215
+ }
216
+ finally {
217
+ if (tempAuthDir !== undefined) {
218
+ rmSync(tempAuthDir, { recursive: true, force: true });
219
+ }
220
+ }
221
+ }
222
+ function filterPassthroughMap(source, extra) {
223
+ const merged = {};
224
+ if (typeof source === 'object' && source !== null && !Array.isArray(source)) {
225
+ for (const [key, value] of Object.entries(source)) {
226
+ if (key.startsWith(PASSTHROUGH_LABEL_PREFIX) && typeof value === 'string') {
227
+ merged[key] = value;
228
+ }
229
+ }
230
+ }
231
+ if (extra !== undefined) {
232
+ for (const [key, value] of Object.entries(extra)) {
233
+ if (key.startsWith(PASSTHROUGH_LABEL_PREFIX)) {
234
+ merged[key] = value;
235
+ }
236
+ }
237
+ }
238
+ return Object.keys(merged).length > 0 ? merged : undefined;
239
+ }
240
+ function sanitizeGuestSpec(guest, pinnedImage) {
241
+ const result = {
242
+ ...guest,
243
+ image: pinnedImage,
244
+ };
245
+ const local = result.localResources;
246
+ if (typeof local === 'object' && local !== null && !Array.isArray(local)) {
247
+ const nextLocal = { ...local };
248
+ delete nextLocal.volumeMounts;
249
+ delete nextLocal.allowedIpNameLookups;
250
+ const envObj = nextLocal.environment;
251
+ if (typeof envObj === 'object' && envObj !== null && !Array.isArray(envObj)) {
252
+ const nextEnv = { ...envObj };
253
+ delete nextEnv.configFrom;
254
+ delete nextEnv.secretFrom;
255
+ if (Object.keys(nextEnv).length > 0) {
256
+ nextLocal.environment = nextEnv;
257
+ }
258
+ else {
259
+ delete nextLocal.environment;
260
+ }
261
+ }
262
+ if (Object.keys(nextLocal).length > 0) {
263
+ result.localResources = nextLocal;
264
+ }
265
+ else {
266
+ delete result.localResources;
267
+ }
268
+ }
269
+ return result;
270
+ }
271
+ export function sanitizeWorkloadForBundle(workload, options) {
272
+ const { service, env, component, publicIngress = true } = options;
273
+ const workloadName = `${service}-${env}`;
274
+ const pinnedImage = pinImageToDigest(component.reference, component.digest);
275
+ const rawMeta = typeof workload.metadata === 'object' && workload.metadata !== null
276
+ ? workload.metadata
277
+ : {};
278
+ const labels = filterPassthroughMap(rawMeta.labels, options.labels);
279
+ const annotations = filterPassthroughMap(rawMeta.annotations, options.annotations);
280
+ const metadata = {
281
+ name: workloadName,
282
+ ...(labels ? { labels } : {}),
283
+ ...(annotations ? { annotations } : {}),
284
+ };
285
+ const rawSpec = (workload.spec ?? {});
286
+ const rawTemplate = (rawSpec.template ?? {});
287
+ const rawTemplateSpec = (rawTemplate.spec ?? {});
288
+ const nextTemplateSpec = { ...rawTemplateSpec };
289
+ delete nextTemplateSpec.hostSelector;
290
+ delete nextTemplateSpec.environment;
291
+ delete nextTemplateSpec.hostId;
292
+ delete nextTemplateSpec.kubernetes;
293
+ delete nextTemplateSpec.volumes;
294
+ const rawComponents = Array.isArray(nextTemplateSpec.components)
295
+ ? nextTemplateSpec.components
296
+ : [];
297
+ const rawService = typeof nextTemplateSpec.service === 'object' && nextTemplateSpec.service !== null
298
+ ? nextTemplateSpec.service
299
+ : undefined;
300
+ if (rawComponents.length > 0) {
301
+ nextTemplateSpec.components = rawComponents.map((comp) => sanitizeGuestSpec(comp, pinnedImage));
302
+ if (rawService !== undefined) {
303
+ nextTemplateSpec.service = sanitizeGuestSpec(rawService, pinnedImage);
304
+ }
305
+ }
306
+ else if (rawService !== undefined) {
307
+ nextTemplateSpec.components = [
308
+ sanitizeGuestSpec({ name: service, ...rawService }, pinnedImage),
309
+ ];
310
+ delete nextTemplateSpec.service;
311
+ }
312
+ if (Array.isArray(nextTemplateSpec.hostInterfaces)) {
313
+ nextTemplateSpec.hostInterfaces = nextTemplateSpec.hostInterfaces.map((entry) => {
314
+ const copy = { ...entry };
315
+ delete copy.configFrom;
316
+ delete copy.secretFrom;
317
+ if (copy.namespace === 'wasi' && copy.package === 'http') {
318
+ const rawConfig = typeof copy.config === 'object' && copy.config !== null && !Array.isArray(copy.config)
319
+ ? { ...copy.config }
320
+ : {};
321
+ const isClusterLocal = typeof rawConfig.host === 'string' && rawConfig.host.endsWith('.svc.cluster.local');
322
+ if (!publicIngress || isClusterLocal) {
323
+ delete rawConfig.host;
324
+ if (Object.keys(rawConfig).length > 0) {
325
+ copy.config = rawConfig;
326
+ }
327
+ else {
328
+ delete copy.config;
329
+ }
330
+ }
331
+ else {
332
+ copy.config = { ...rawConfig, host: workloadName };
333
+ }
334
+ }
335
+ return copy;
336
+ });
337
+ }
338
+ return {
339
+ apiVersion: workload.apiVersion ?? 'runtime.wasmcloud.dev/v1alpha1',
340
+ kind: workload.kind ?? 'WorkloadDeployment',
341
+ metadata,
342
+ spec: {
343
+ ...rawSpec,
344
+ template: {
345
+ ...rawTemplate,
346
+ spec: nextTemplateSpec,
347
+ },
348
+ },
349
+ };
350
+ }
351
+ function splitYamlKeyValue(text) {
352
+ let inQuotes = false;
353
+ for (let i = 0; i < text.length; i++) {
354
+ const ch = text[i];
355
+ if (ch === '"' && text[i - 1] !== '\\')
356
+ inQuotes = !inQuotes;
357
+ else if (ch === ':' && !inQuotes) {
358
+ const rawKey = text.slice(0, i).trim();
359
+ const key = rawKey.startsWith('"') ? JSON.parse(rawKey) : rawKey;
360
+ return { key, value: text.slice(i + 1).trim() };
361
+ }
362
+ }
363
+ return { key: text.trim(), value: '' };
364
+ }
365
+ function parseYamlScalar(raw) {
366
+ if (raw.startsWith('"') || raw.startsWith('[')) {
367
+ return JSON.parse(raw);
368
+ }
369
+ if (/^\d+$/.test(raw))
370
+ return Number.parseInt(raw, 10);
371
+ return raw;
372
+ }
373
+ function parseYamlBlock(lines, startIndex, blockIndent) {
374
+ if (lines[startIndex]?.text.startsWith('- ')) {
375
+ const items = [];
376
+ let index = startIndex;
377
+ while (index < lines.length && lines[index].indent === blockIndent) {
378
+ const line = lines[index];
379
+ if (!line.text.startsWith('- '))
380
+ break;
381
+ const itemText = line.text.slice(2).trim();
382
+ const { key, value } = splitYamlKeyValue(itemText);
383
+ if (value === '' && !itemText.endsWith(':')) {
384
+ items.push(parseYamlScalar(itemText));
385
+ index++;
386
+ continue;
387
+ }
388
+ const itemMap = {};
389
+ if (value !== '') {
390
+ itemMap[key] = parseYamlScalar(value);
391
+ index++;
392
+ }
393
+ else {
394
+ const nextIndent = lines[index + 1].indent;
395
+ const [nested, nextIdx] = parseYamlBlock(lines, index + 1, nextIndent);
396
+ itemMap[key] = nested;
397
+ index = nextIdx;
398
+ }
399
+ if (index < lines.length && lines[index].indent > blockIndent) {
400
+ const [restMap, nextIdx] = parseYamlMap(lines, index, lines[index].indent);
401
+ Object.assign(itemMap, restMap);
402
+ index = nextIdx;
403
+ }
404
+ items.push(itemMap);
405
+ }
406
+ return [items, index];
407
+ }
408
+ return parseYamlMap(lines, startIndex, blockIndent);
409
+ }
410
+ function parseYamlMap(lines, startIndex, mapIndent) {
411
+ const result = {};
412
+ let index = startIndex;
413
+ while (index < lines.length && lines[index].indent === mapIndent) {
414
+ const line = lines[index];
415
+ if (line.text.startsWith('- '))
416
+ break;
417
+ const { key, value } = splitYamlKeyValue(line.text);
418
+ if (value !== '') {
419
+ result[key] = parseYamlScalar(value);
420
+ index++;
421
+ }
422
+ else {
423
+ const childIndent = lines[index + 1].indent;
424
+ const [nested, nextIdx] = parseYamlBlock(lines, index + 1, childIndent);
425
+ result[key] = nested;
426
+ index = nextIdx;
427
+ }
428
+ }
429
+ return [result, index];
430
+ }
431
+ export function parseWorkloadDeploymentYaml(manifestYaml) {
432
+ const documents = manifestYaml
433
+ .split(/\n---\n/)
434
+ .map((doc) => doc.trim())
435
+ .filter((doc) => doc.length > 0);
436
+ const workloadSection = documents.find((doc) => doc.includes('kind: WorkloadDeployment')) ?? documents[0] ?? '';
437
+ const lines = workloadSection
438
+ .split(/\r?\n/)
439
+ .filter((raw) => raw.trim().length > 0)
440
+ .map((raw) => {
441
+ const trimmed = raw.trimStart();
442
+ return { indent: raw.length - trimmed.length, text: trimmed };
443
+ });
444
+ const [parsed] = parseYamlMap(lines, 0, 0);
445
+ return parsed;
446
+ }
447
+ const KIND_TO_CAPABILITY = {
448
+ Postgres: 'postgres',
449
+ KeyValue: 'keyvalue',
450
+ Blobstore: 'blobstore',
451
+ Messaging: 'messaging',
452
+ OutgoingHttp: 'egress',
453
+ };
454
+ function collectDeployBindings(manifestBindings, targetBindings, discoveredBindings, optionBindings) {
455
+ const byName = new Map();
456
+ for (const record of discoveredBindings) {
457
+ if (record.serviceName === undefined)
458
+ continue;
459
+ const capability = KIND_TO_CAPABILITY[record.kind];
460
+ if (capability === undefined)
461
+ continue;
462
+ byName.set(record.name, {
463
+ name: record.name,
464
+ capability,
465
+ serviceName: record.serviceName,
466
+ ...(record.config && Object.keys(record.config).length > 0 ? { config: record.config } : {}),
467
+ });
468
+ }
469
+ for (const source of [manifestBindings, targetBindings, optionBindings]) {
470
+ if (source === undefined)
471
+ continue;
472
+ for (const binding of source) {
473
+ byName.set(binding.name, {
474
+ name: binding.name,
475
+ capability: binding.capability,
476
+ serviceName: binding.serviceName,
477
+ ...(binding.config && Object.keys(binding.config).length > 0
478
+ ? { config: { ...binding.config } }
479
+ : {}),
480
+ });
481
+ }
482
+ }
483
+ return [...byName.values()];
484
+ }
485
+ function collectDeploySecrets(manifestSecrets, targetSecrets, optionSecrets) {
486
+ const seen = new Set();
487
+ for (const list of [manifestSecrets, targetSecrets, optionSecrets]) {
488
+ if (list === undefined)
489
+ continue;
490
+ for (const secret of list) {
491
+ seen.add(secret);
492
+ }
493
+ }
494
+ return [...seen];
495
+ }
496
+ async function resolveBundleTargetAndConnection(options, manifest, project, resolvedCredentials, hasExplicitRegistryOrPublish, deps) {
497
+ let target;
498
+ let connection;
499
+ const shouldResolveTarget = Boolean(options.target ?? manifest?.defaultTarget ?? !hasExplicitRegistryOrPublish);
500
+ if (manifest !== undefined && shouldResolveTarget) {
501
+ target = resolveTarget(manifest, options.target);
502
+ if (!isControllerBackedTarget(target)) {
503
+ connection = await resolveConnection(target, manifest.workspaceRoot, manifest.path, deps);
504
+ }
505
+ }
506
+ const registryOverride = options.registry ?? resolvedCredentials?.registry;
507
+ const effectiveConnection = connection !== undefined
508
+ ? {
509
+ ...connection,
510
+ hostgroup: connection.hostgroup ?? `tenant-${project.witName}`,
511
+ ...(registryOverride !== undefined
512
+ ? { registry: materializeRegistry(registryOverride) }
513
+ : {}),
514
+ }
515
+ : {
516
+ target: options.target ?? 'bundle',
517
+ kubeconfig: '',
518
+ namespace: `di-tenant-${project.witName}`,
519
+ hostgroup: `tenant-${project.witName}`,
520
+ registry: materializeRegistry(registryOverride ?? 'localhost:5000'),
521
+ };
522
+ return { target, effectiveConnection };
523
+ }
524
+ function toComponentReference(published) {
525
+ if ('pullReference' in published && 'artifactDigest' in published) {
526
+ return {
527
+ reference: published.pullReference,
528
+ digest: normalizeSha256Digest(published.artifactDigest),
529
+ };
530
+ }
531
+ return {
532
+ reference: published.reference,
533
+ digest: normalizeSha256Digest(published.digest),
534
+ };
535
+ }
536
+ export async function buildDeployBundle(options = {}, io, deps = DEFAULT_DEPS) {
537
+ const startDir = options.project?.projectRoot ?? deps.cwd();
538
+ const hasExplicitRegistryOrPublish = Boolean(options.registry !== undefined ||
539
+ options.publish !== undefined ||
540
+ options.credentials !== undefined);
541
+ const manifestConfig = loadBundleManifestConfig(startDir, deps.env, hasExplicitRegistryOrPublish);
542
+ const manifest = manifestConfig.manifest;
543
+ const project = options.project ??
544
+ (manifest !== undefined && options.name !== undefined
545
+ ? resolveApplication(deps.cwd(), options.name, manifest.workspaceRoot, manifest.discovery)
546
+ : loadProject(deps.cwd()));
547
+ const resolvedCredentials = typeof options.credentials === 'function' ? await options.credentials() : options.credentials;
548
+ const { target, effectiveConnection } = await resolveBundleTargetAndConnection(options, manifest, project, resolvedCredentials, hasExplicitRegistryOrPublish, deps);
549
+ const env = options.env ?? target?.env ?? manifestConfig.env ?? 'prod';
550
+ if (env !== 'prod' && env !== 'staging') {
551
+ invalidUsage('Invalid --env value; expected "prod" or "staging"', String(env));
552
+ }
553
+ const service = deploymentResourceName(project);
554
+ const build = await buildComponent(project, io, deps, {
555
+ deploy: true,
556
+ guestLogging: project.logs !== false,
557
+ });
558
+ const publishContext = {
559
+ project,
560
+ connection: effectiveConnection,
561
+ build,
562
+ io,
563
+ deps,
564
+ tag: options.tag,
565
+ credentials: resolvedCredentials,
566
+ };
567
+ const published = options.publish
568
+ ? await options.publish(publishContext)
569
+ : await publishWithBundleOptions(publishContext);
570
+ const component = toComponentReference(published);
571
+ const requirements = requirementsForProject(project, deps);
572
+ const discoveredBindings = discoverBindings(project, deps);
573
+ const actors = discoverActors(project);
574
+ const cronJobs = discoverScheduledJobs(project.projectRoot);
575
+ const queueHandlers = discoverQueueHandlers(project);
576
+ const isWorker = isQueueWorkerProject(project, queueHandlers);
577
+ const publicIngress = project.ingress !== false && !isWorker;
578
+ const manifestYaml = renderWorkloadManifest(project, effectiveConnection, ociReference(effectiveConnection.registry.pull, project.witName, build.deploymentDigest), requirements, discoveredBindings, {
579
+ hasActors: actors.length > 0,
580
+ hasPersistentStorage: project.persistentStorage === true,
581
+ }, cronJobs, queueHandlers);
582
+ const parsedWorkload = parseWorkloadDeploymentYaml(manifestYaml);
583
+ const workload = sanitizeWorkloadForBundle(parsedWorkload, {
584
+ service,
585
+ env,
586
+ component,
587
+ publicIngress,
588
+ labels: options.labels,
589
+ annotations: options.annotations,
590
+ });
591
+ const bindings = collectDeployBindings(manifestConfig.bindings, target?.bindings, discoveredBindings, options.bindings);
592
+ const secrets = collectDeploySecrets(manifestConfig.secrets, target?.secrets, options.secrets);
593
+ const bundle = {
594
+ env,
595
+ service,
596
+ component,
597
+ workload,
598
+ bindings,
599
+ secrets,
600
+ };
601
+ if (options.outputPath !== undefined) {
602
+ const absoluteOut = resolve(deps.cwd(), options.outputPath);
603
+ mkdirSync(dirname(absoluteOut), { recursive: true });
604
+ writeFileSync(absoluteOut, `${JSON.stringify(bundle, null, 2)}\n`);
605
+ io.stdout.write(`Wrote DeployBundle for ${service} (${env}) to ${options.outputPath}\n`);
606
+ }
607
+ return bundle;
608
+ }