@solid-stack/builder 2.0.2 → 2.1.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 (93) hide show
  1. package/README.md +581 -50
  2. package/dist/bin.js +1160 -610
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  6. package/dist/commands/service/commands/export/handler.d.ts.map +1 -1
  7. package/dist/core/composeCleanup.d.ts.map +1 -1
  8. package/dist/core/composition/assertComposeLifecycleAcyclic.d.ts +7 -0
  9. package/dist/core/composition/assertComposeLifecycleAcyclic.d.ts.map +1 -0
  10. package/dist/core/composition/compileServiceComposition.d.ts +2 -0
  11. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  12. package/dist/core/composition/composeBuildResources.d.ts +6 -0
  13. package/dist/core/composition/composeBuildResources.d.ts.map +1 -0
  14. package/dist/core/composition/composeDependsOn.d.ts +3 -0
  15. package/dist/core/composition/composeDependsOn.d.ts.map +1 -0
  16. package/dist/core/composition/composeEnvironment.d.ts +2 -2
  17. package/dist/core/composition/composeEnvironment.d.ts.map +1 -1
  18. package/dist/core/composition/composeHealthcheck.d.ts +3 -0
  19. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -0
  20. package/dist/core/composition/composePaths.d.ts.map +1 -1
  21. package/dist/core/composition/generatedNames.d.ts +9 -0
  22. package/dist/core/composition/generatedNames.d.ts.map +1 -0
  23. package/dist/core/composition/mergeAppOverride.d.ts +3 -0
  24. package/dist/core/composition/mergeAppOverride.d.ts.map +1 -0
  25. package/dist/core/composition/namespaceDependencyCompose.d.ts +3 -0
  26. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  27. package/dist/core/composition/namespaceResourceDefinition.d.ts +3 -0
  28. package/dist/core/composition/namespaceResourceDefinition.d.ts.map +1 -0
  29. package/dist/core/composition/selectAppEnvironmentEntries.d.ts +3 -0
  30. package/dist/core/composition/selectAppEnvironmentEntries.d.ts.map +1 -0
  31. package/dist/core/composition/types.d.ts +22 -5
  32. package/dist/core/composition/types.d.ts.map +1 -1
  33. package/dist/core/composition/validateComposeResourceReferences.d.ts +7 -0
  34. package/dist/core/composition/validateComposeResourceReferences.d.ts.map +1 -0
  35. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  36. package/dist/core/composition/validateOverrideCompose.d.ts +3 -0
  37. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  38. package/dist/core/config/builderEnvironment.d.ts +12 -0
  39. package/dist/core/config/builderEnvironment.d.ts.map +1 -0
  40. package/dist/core/config/endpointProperties.d.ts +5 -2
  41. package/dist/core/config/endpointProperties.d.ts.map +1 -1
  42. package/dist/core/config/hostPorts.d.ts +5 -1
  43. package/dist/core/config/hostPorts.d.ts.map +1 -1
  44. package/dist/core/config/pathSafety.d.ts.map +1 -1
  45. package/dist/core/config/references.d.ts +9 -3
  46. package/dist/core/config/references.d.ts.map +1 -1
  47. package/dist/core/config/resolveBuildStage.d.ts.map +1 -1
  48. package/dist/core/config/resolveMeshStage.d.ts.map +1 -1
  49. package/dist/core/config/stageMerge.d.ts +2 -0
  50. package/dist/core/config/stageMerge.d.ts.map +1 -1
  51. package/dist/core/config/types.d.ts +7 -2
  52. package/dist/core/config/types.d.ts.map +1 -1
  53. package/dist/core/mesh/checkers/checkMesh.d.ts +1 -0
  54. package/dist/core/mesh/checkers/checkMesh.d.ts.map +1 -1
  55. package/dist/core/mesh/checkers/checkMeshServices.d.ts +4 -1
  56. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  57. package/dist/core/mesh/meshSchema.d.ts +13 -1
  58. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  59. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  60. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  61. package/dist/core/mesh/runners/runMeshServiceTests.d.ts +3 -0
  62. package/dist/core/mesh/runners/runMeshServiceTests.d.ts.map +1 -0
  63. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  64. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  65. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  66. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  67. package/dist/core/mesh/v2/compileMeshTester.d.ts +2 -1
  68. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  69. package/dist/core/mesh/v2/meshReferences.d.ts +5 -3
  70. package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -1
  71. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts +4 -0
  72. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts.map +1 -0
  73. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +22 -0
  74. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +1 -0
  75. package/dist/core/runWithCleanup.d.ts +3 -0
  76. package/dist/core/runWithCleanup.d.ts.map +1 -0
  77. package/dist/core/runners/runDev.d.ts.map +1 -1
  78. package/dist/core/runners/runProd.d.ts.map +1 -1
  79. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  80. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  81. package/dist/core/teardownCompose.d.ts.map +1 -1
  82. package/dist/errors/PortConflictError.d.ts +1 -1
  83. package/dist/errors/PortConflictError.d.ts.map +1 -1
  84. package/dist/index.js +1159 -609
  85. package/dist/index.js.map +1 -1
  86. package/dist/templates/policy/dockerfile/dockerfile.rego +13 -13
  87. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -1
  88. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  89. package/dist/utils/composePublishedPort.d.ts +3 -0
  90. package/dist/utils/composePublishedPort.d.ts.map +1 -0
  91. package/package.json +1 -1
  92. package/schemas/mesh-schema.json +311 -20
  93. package/templates/policy/dockerfile/dockerfile.rego +13 -13
package/dist/bin.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Argument } from 'commander';
3
- import pc22 from 'picocolors';
4
- import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, unlinkSync, renameSync, realpathSync, lstatSync, readlinkSync } from 'fs';
3
+ import pc14 from 'picocolors';
4
+ import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, unlinkSync, realpathSync, lstatSync, readlinkSync, renameSync } from 'fs';
5
5
  import path from 'path';
6
6
  import { z } from 'zod';
7
7
  import { spawnSync, spawn } from 'child_process';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { parseAllDocuments, parse, stringify } from 'yaml';
10
- import crypto from 'crypto';
10
+ import crypto, { createHash } from 'crypto';
11
+ import net, { isIP } from 'net';
11
12
  import os from 'os';
12
- import net from 'net';
13
13
  import { createInterface } from 'readline/promises';
14
14
  import { createRequire } from 'module';
15
15
 
@@ -137,8 +137,12 @@ var getBuildJson = (projectDir = process.cwd()) => {
137
137
  }
138
138
  return result.data;
139
139
  };
140
+ function isAbsoluteManagedPath(value) {
141
+ return path.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value) || /^\/\//.test(value);
142
+ }
140
143
  function resolveInsideProject(projectDir, relativePath, context) {
141
144
  if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
145
+ if (isAbsoluteManagedPath(relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Builder-managed path must be relative to its project root" });
142
146
  const resolved = path.resolve(projectDir, relativePath);
143
147
  if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
144
148
  return resolved;
@@ -168,7 +172,7 @@ function runStep(executable, args, projectDir, ctx) {
168
172
  if (stderr) process.stderr.write(stderr);
169
173
  if (result.error || result.status !== 0) {
170
174
  console.error("\n" + "=".repeat(60));
171
- console.error(pc22.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
175
+ console.error(pc14.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
172
176
  console.error("=".repeat(60));
173
177
  console.error(`Failed Step : ${ctx.stepName}`);
174
178
  if (ctx.targetFile) {
@@ -195,7 +199,7 @@ function checkDockerfile(buildJson, projectDir) {
195
199
  const dockerfileRel = buildJson.dockerfile || "Dockerfile";
196
200
  const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
197
201
  const content = readFileSync(dockerfilePath, "utf-8");
198
- console.log(pc22.cyan(`
202
+ console.log(pc14.cyan(`
199
203
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
200
204
  runStep(
201
205
  "docker",
@@ -265,7 +269,7 @@ function checkDockerfileContract(build, projectDir) {
265
269
  const relative = build.dockerfile ?? "Dockerfile";
266
270
  resolveApplicationDockerfile(root, relative);
267
271
  const policyDir = getDockerfilePolicyDir();
268
- console.log(pc22.cyan(`
272
+ console.log(pc14.cyan(`
269
273
  \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
270
274
  runStep("docker", ["run", "--rm", "--network", "none", "--mount", `type=bind,src=${root},dst=/project,readonly`, "--mount", `type=bind,src=${policyDir},dst=/builder-policy,readonly`, "-w", "/project", CONFTEST_IMAGE, "test", relative, "-p", "/builder-policy"], root, { stepName: "Dockerfile Contract", targetFile: relative });
271
275
  }
@@ -320,13 +324,41 @@ function getDeclaredYamlFiles(build, projectDir) {
320
324
  function checkYamlFiles(build, projectDir) {
321
325
  const root = resolveProjectDir(projectDir);
322
326
  const files = getDeclaredYamlFiles(build, root);
323
- if (files.length) console.log(pc22.cyan(`
327
+ if (files.length) console.log(pc14.cyan(`
324
328
  \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
325
329
  for (const file of files) {
326
330
  const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
327
331
  loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
328
332
  }
329
333
  }
334
+ var GeneratedComposeNameAllocator = class {
335
+ occupied;
336
+ allocated = /* @__PURE__ */ new Map();
337
+ constructor(initialNames = []) {
338
+ this.occupied = new Set(initialNames);
339
+ }
340
+ allocate(identity, hint) {
341
+ const existing = this.allocated.get(identity);
342
+ if (existing) return existing;
343
+ const hash = createHash("sha256").update(identity).digest("hex");
344
+ const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
345
+ for (const candidate of [
346
+ safeHint,
347
+ ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
348
+ ]) {
349
+ if (this.occupied.has(candidate)) continue;
350
+ this.occupied.add(candidate);
351
+ this.allocated.set(identity, candidate);
352
+ return candidate;
353
+ }
354
+ throw new Error(`Unable to allocate unique Compose name for ${identity}`);
355
+ }
356
+ assertUnique() {
357
+ if (new Set(this.allocated.values()).size !== this.allocated.size) {
358
+ throw new Error("Internal generated Compose name collision");
359
+ }
360
+ }
361
+ };
330
362
 
331
363
  // src/core/composition/composeNetworks.ts
332
364
  function normalizeNetworks(value) {
@@ -334,13 +366,24 @@ function normalizeNetworks(value) {
334
366
  return value && typeof value === "object" ? { ...value } : {};
335
367
  }
336
368
 
369
+ // src/core/composition/selectAppEnvironmentEntries.ts
370
+ function selectAppEnvironmentEntries(layers, laterKeys = /* @__PURE__ */ new Set()) {
371
+ const winners = /* @__PURE__ */ new Map();
372
+ for (const layer of layers) {
373
+ for (const key of Object.keys(layer.values)) winners.set(key, layer);
374
+ }
375
+ for (const key of laterKeys) winners.delete(key);
376
+ return winners;
377
+ }
378
+
337
379
  // src/core/config/endpointProperties.ts
338
380
  function resolveEndpointProperty(endpoint, property, context) {
381
+ const reference = context.referencedObject ?? endpoint.logicalPath;
339
382
  const published = () => {
340
- if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
383
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires effective publication` });
341
384
  };
342
385
  const scheme = () => {
343
- if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
386
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires an endpoint scheme` });
344
387
  return endpoint.scheme;
345
388
  };
346
389
  switch (property) {
@@ -395,6 +438,18 @@ function assertAcyclicGraph(graph, context) {
395
438
  }
396
439
 
397
440
  // src/core/config/stageMerge.ts
441
+ function stageOverlayChain(stage) {
442
+ switch (stage) {
443
+ case "dev":
444
+ return ["dev"];
445
+ case "prod":
446
+ return ["prod"];
447
+ case "test":
448
+ return ["test"];
449
+ case "e2e":
450
+ return ["prod", "e2e"];
451
+ }
452
+ }
398
453
  function unionStable(base = [], overlay = []) {
399
454
  return [.../* @__PURE__ */ new Set([...base, ...overlay])];
400
455
  }
@@ -404,32 +459,40 @@ function mergeStringMap(base, overlay) {
404
459
 
405
460
  // src/core/config/resolveBuildStage.ts
406
461
  function resolveBuildStage(build, stage, sourceFile) {
407
- const overlay = build[stage] ?? {};
462
+ const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
463
+ const appEnv = { ...build.app.env ?? {} };
408
464
  const appEndpoints = structuredClone(build.app.endpoints ?? {});
409
- for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
410
465
  const dependencies = {};
411
466
  for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
412
- for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
413
- const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
414
- prior.compose = patch.compose ?? prior.compose;
415
- prior.env = mergeStringMap(prior.env, patch.env);
416
- for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
417
- prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
418
- dependencies[name] = prior;
419
- }
420
- const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
467
+ const layers = [{ stage: "base", appEnv: { ...build.app.env ?? {} } }];
468
+ for (const overlayStage of stageOverlayChain(stage)) {
469
+ const overlay = build[overlayStage];
470
+ if (!overlay) continue;
471
+ Object.assign(appEnv, overlay.app?.env ?? {});
472
+ for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
473
+ for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
474
+ const inherited = dependencies[name];
475
+ if (inherited && patch.compose !== void 0) throw context(`${overlayStage}.dependencies.${name}.compose`, patch.compose, "A stage cannot replace the Compose implementation of an inherited dependency", `dependencies.${name}`);
476
+ const next = inherited ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
477
+ if (!inherited && patch.compose !== void 0) next.compose = patch.compose;
478
+ next.env = mergeStringMap(next.env, patch.env);
479
+ for (const [endpointName, endpointPatch] of Object.entries(patch.endpoints ?? {})) next.endpoints[endpointName] = { ...next.endpoints[endpointName] ?? {}, ...endpointPatch };
480
+ next.dependsOn = unionStable(next.dependsOn, patch.dependsOn);
481
+ dependencies[name] = next;
482
+ }
483
+ layers.push({ stage: overlayStage, appEnv: { ...overlay.app?.env ?? {} }, ...overlay["override-compose"] ? { overrideCompose: overlay["override-compose"] } : {} });
484
+ }
485
+ const effective = { ...build, app: { env: appEnv, endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, layers };
421
486
  delete effective.dev;
422
487
  delete effective.prod;
423
488
  delete effective.test;
424
489
  delete effective.e2e;
425
- const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
426
490
  for (const [name, ep] of Object.entries(appEndpoints)) if (!Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`app.endpoints.${name}.port`, ep.port, "Effective endpoint requires a port in 1..65535");
427
491
  assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
428
492
  const graph = /* @__PURE__ */ new Map();
429
493
  for (const [name, dep] of Object.entries(dependencies)) {
430
494
  if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
431
- const endpoints = Object.entries(dep.endpoints);
432
- for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
495
+ for (const [epName, ep] of Object.entries(dep.endpoints)) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
433
496
  assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
434
497
  const node = `dependencies.${name}`;
435
498
  graph.set(node, /* @__PURE__ */ new Set());
@@ -453,29 +516,42 @@ var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
453
516
  var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
454
517
  var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
455
518
  var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
456
- function parse2(raw, scope, sourcePath) {
457
- let m;
458
- if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
459
- if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
460
- if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
461
- if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
462
- throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
463
- }
464
- function valid(ref, sourcePath) {
465
- if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
519
+ function parse2(raw, scope, context) {
520
+ let match;
521
+ if (scope === "build" && (match = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: match[1], property: match[2] }, context);
522
+ if (scope === "build" && (match = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: match[1], endpoint: match[2], property: match[3] }, context);
523
+ if (scope === "mesh" && (match = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "app", endpoint: match[2], property: match[3] }, context);
524
+ if (scope === "mesh" && (match = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: match[1], target: "dependency", dependency: match[2], endpoint: match[3], property: match[4] }, context);
525
+ throw new ConfigError({ ...context, referencedObject: raw, value: raw, reason: `Invalid ${scope} endpoint reference` });
526
+ }
527
+ function valid(ref, context) {
528
+ if (!ENDPOINT_PROPERTIES.includes(ref.property)) {
529
+ throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.property, reason: "Unknown endpoint property" });
530
+ }
466
531
  return ref;
467
532
  }
468
- function collectBuilderReferences(value, scope, sourcePath) {
469
- const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
470
- for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
471
- return refs2;
533
+ function collectBuilderReferences(value, scope, context) {
534
+ const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0");
535
+ const refs = [];
536
+ for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs.push(parse2(match[1], scope, context));
537
+ return refs;
472
538
  }
473
- function interpolateBuilderReferences(value, scope, resolve) {
539
+ function interpolateBuilderReferences(value, scope, resolve, context) {
474
540
  const sentinel = "\0DOLLAR\0";
475
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
476
- }
477
- function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
478
- for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
541
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
542
+ const ref = parse2(body, scope, context);
543
+ return resolve(ref, context);
544
+ }).replaceAll(sentinel, "$");
545
+ }
546
+ function assertTesterReferencesArePublic(env, scope, baseContext) {
547
+ for (const [key, value] of Object.entries(env)) {
548
+ const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
549
+ for (const ref of collectBuilderReferences(value, scope, context)) {
550
+ if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) {
551
+ throw new ConfigError({ ...context, referencedObject: ref.raw, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
552
+ }
553
+ }
554
+ }
479
555
  }
480
556
 
481
557
  // src/errors/PortConflictError.ts
@@ -483,8 +559,8 @@ var PortConflictError = class extends ConfigError {
483
559
  port;
484
560
  firstOwner;
485
561
  secondOwner;
486
- constructor(port, firstOwner, secondOwner, stage) {
487
- super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
562
+ constructor(port, firstOwner, secondOwner, stage, sourceFile = "Builder effective composition", composition) {
563
+ super({ sourceFile, configPath: secondOwner, value: port, stage, ...composition ? { composition } : {}, referencedObject: firstOwner, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
488
564
  this.name = "PortConflictError";
489
565
  this.port = port;
490
566
  this.firstOwner = firstOwner;
@@ -498,11 +574,11 @@ function isHostPortAvailableSync(port) {
498
574
  const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
499
575
  return result.status === 0;
500
576
  }
501
- function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
577
+ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false, context) {
502
578
  const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
503
579
  for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
504
580
  const owner = reserved.get(intent.requested);
505
- if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
581
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage, context?.sourceFile, context?.composition);
506
582
  reserved.set(intent.requested, intent.logicalPath);
507
583
  allocated.set(intent.logicalPath, intent.requested);
508
584
  }
@@ -510,7 +586,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
510
586
  let placeholder = 6e4;
511
587
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
512
588
  while (reserved.has(placeholder)) placeholder--;
513
- if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
589
+ if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No validation placeholder port is available" });
514
590
  reserved.set(placeholder, intent.logicalPath);
515
591
  allocated.set(intent.logicalPath, placeholder--);
516
592
  }
@@ -534,7 +610,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
534
610
  const scan = [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
535
611
  selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
536
612
  }
537
- if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
613
+ if (selected === void 0) throw new ConfigError({ sourceFile: context?.sourceFile ?? "Builder effective composition", ...context?.composition ? { composition: context.composition } : {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No available host port could be allocated" });
538
614
  reserved.set(selected, intent.logicalPath);
539
615
  allocated.set(intent.logicalPath, selected);
540
616
  nextCache[intent.logicalPath] = selected;
@@ -547,6 +623,26 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
547
623
  }
548
624
  return allocated;
549
625
  }
626
+ var EXEC_MODE_KEY = "EXEC_MODE";
627
+ var INFRA_MODE_KEY = "INFRA_MODE";
628
+ var PORT_KEY = "PORT";
629
+ function assertNoBuilderOwnedEnvKeys(env, keys, context) {
630
+ for (const key of keys) {
631
+ if (!(key in env)) continue;
632
+ throw new ConfigError({ sourceFile: context.sourceFile, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: env[key], reason: `User-controlled environment cannot set Builder-owned key "${key}"` });
633
+ }
634
+ }
635
+ function assertDotenvDoesNotDefineKeys(filePath, keys, context) {
636
+ if (!fs.existsSync(filePath)) return;
637
+ const forbidden = new Set(keys), lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
638
+ for (let index = 0; index < lines.length; index += 1) {
639
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(lines[index]);
640
+ if (!match) continue;
641
+ const key = match[1];
642
+ if (!forbidden.has(key)) continue;
643
+ throw new ConfigError({ sourceFile: filePath, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: `line ${index + 1}`, reason: `Environment file cannot set Builder-owned key "${key}"` });
644
+ }
645
+ }
550
646
  function normalizeProjectName(name, projectDir) {
551
647
  let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
552
648
  if (!normalized || !/^[a-z0-9]/.test(normalized)) {
@@ -640,14 +736,33 @@ function volumeShort(v, base, out) {
640
736
  if (mount?.type !== "bind" || !mount.source || /^(?:[\\/]|~|[a-z]:)/i.test(mount.source)) return v;
641
737
  return rewriteVolumeSource(v, rebase(mount.source, base, out));
642
738
  }
739
+ function isRemoteBuildContext(value) {
740
+ return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value) || /^[^/@\s]+@[^:\s]+:.+/.test(value);
741
+ }
742
+ function rebaseAdditionalContext(value, base, out) {
743
+ if (value.startsWith("service:") || isRemoteBuildContext(value)) return value;
744
+ return rebase(value, base, out);
745
+ }
746
+ function rebaseAdditionalContexts(value, base, out) {
747
+ if (Array.isArray(value)) return value.map((entry) => {
748
+ if (typeof entry !== "string") return entry;
749
+ const separator = entry.indexOf("=");
750
+ if (separator < 0) return entry;
751
+ return `${entry.slice(0, separator)}=${rebaseAdditionalContext(entry.slice(separator + 1), base, out)}`;
752
+ });
753
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, context]) => [name, typeof context === "string" ? rebaseAdditionalContext(context, base, out) : context]));
754
+ return value;
755
+ }
643
756
  function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
644
757
  const doc = structuredClone(document), base = path.dirname(composeFilePath), out = path.resolve(outputProjectDir);
645
758
  for (const svc of Object.values(doc.services ?? {})) {
646
- if (typeof svc.build === "string") svc.build = rebase(svc.build, base, out);
647
- else if (svc.build && typeof svc.build === "object") {
759
+ if (typeof svc.build === "string") {
760
+ if (!isRemoteBuildContext(svc.build)) svc.build = rebase(svc.build, base, out);
761
+ } else if (svc.build && typeof svc.build === "object") {
648
762
  const b = svc.build;
649
763
  const context = typeof b.context === "string" ? b.context : ".";
650
- b.context = rebase(context, base, out);
764
+ if (!isRemoteBuildContext(context)) b.context = rebase(context, base, out);
765
+ if (b.additional_contexts !== void 0) b.additional_contexts = rebaseAdditionalContexts(b.additional_contexts, base, out);
651
766
  }
652
767
  if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
653
768
  else if (Array.isArray(svc.env_file)) svc.env_file = svc.env_file.map((v) => typeof v === "string" ? rebase(v, base, out) : v && typeof v === "object" && typeof v.path === "string" ? { ...v, path: rebase(v.path, base, out) } : v);
@@ -712,7 +827,7 @@ function normalizeComposeEnvironment(value, context) {
712
827
  if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
713
828
  const at = item.indexOf("=");
714
829
  if (at < 0) {
715
- result[item] = process.env[item] ?? "";
830
+ result[item] = null;
716
831
  continue;
717
832
  }
718
833
  result[item.slice(0, at)] = item.slice(at + 1);
@@ -721,7 +836,10 @@ function normalizeComposeEnvironment(value, context) {
721
836
  }
722
837
  if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
723
838
  for (const [key, val] of Object.entries(value)) {
724
- if (val === null || val === void 0) continue;
839
+ if (val === null || val === void 0) {
840
+ result[key] = null;
841
+ continue;
842
+ }
725
843
  if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
726
844
  result[key] = String(val);
727
845
  }
@@ -731,16 +849,81 @@ function mergeComposeEnvironment(service, overlay) {
731
849
  service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
732
850
  }
733
851
 
852
+ // src/core/composition/composeBuildResources.ts
853
+ function buildObject(service) {
854
+ return service.build && typeof service.build === "object" && !Array.isArray(service.build) ? service.build : void 0;
855
+ }
856
+ function rewriteBuildSecretReferences(service, names) {
857
+ const build = buildObject(service);
858
+ if (!build || !Array.isArray(build.secrets)) return;
859
+ build.secrets = build.secrets.map((entry) => {
860
+ if (typeof entry === "string") return names.get(entry) ?? entry;
861
+ if (entry && typeof entry === "object" && typeof entry.source === "string") {
862
+ return { ...entry, source: names.get(entry.source) ?? entry.source };
863
+ }
864
+ return entry;
865
+ });
866
+ }
867
+ function collectBuildSecretReferences(service) {
868
+ const build = buildObject(service);
869
+ if (!build || !Array.isArray(build.secrets)) return [];
870
+ return build.secrets.flatMap((entry) => {
871
+ if (typeof entry === "string") return [entry];
872
+ return entry && typeof entry === "object" && typeof entry.source === "string" ? [entry.source] : [];
873
+ });
874
+ }
875
+ function assertNoServiceBuildContexts(service, configPath, sourceFile) {
876
+ const contexts = buildObject(service)?.additional_contexts;
877
+ const values = Array.isArray(contexts) ? contexts.map((entry) => typeof entry === "string" ? entry.slice(entry.indexOf("=") + 1) : entry) : contexts && typeof contexts === "object" ? Object.values(contexts) : [];
878
+ if (values.some((value) => typeof value === "string" && value.startsWith("service:"))) {
879
+ throw new ConfigError({
880
+ sourceFile,
881
+ configPath: `${configPath}.build.additional_contexts`,
882
+ reason: "Compose service-reference additional_contexts are unsupported"
883
+ });
884
+ }
885
+ }
886
+
887
+ // src/core/composition/namespaceResourceDefinition.ts
888
+ function namespaceResourceDefinition(originalKey, definition) {
889
+ if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
890
+ return definition;
891
+ }
892
+ const result = structuredClone(definition);
893
+ if (result.external === true) {
894
+ result.name ??= originalKey;
895
+ } else {
896
+ delete result.name;
897
+ }
898
+ return result;
899
+ }
900
+
734
901
  // src/core/composition/namespaceDependencyCompose.ts
735
902
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
736
903
  function namespaceDependencyCompose(options) {
737
904
  const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
738
- const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
739
- const serviceNameMap = make("", Object.keys(doc.services ?? {}));
740
- for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
905
+ const originalServices = doc.services ?? {};
906
+ const usesImplicitDefault = Object.values(originalServices).some((service) => service.network_mode === void 0 && service.networks === void 0);
907
+ if (usesImplicitDefault && !Object.hasOwn(doc.networks ?? {}, "default")) doc.networks = { ...doc.networks ?? {}, default: {} };
908
+ const allocator = options.allocator ?? new GeneratedComposeNameAllocator();
909
+ const identityPrefix = options.identityPrefix ?? JSON.stringify(["dependency", options.dependencyKey, prefix]);
910
+ const make = (kind, keys) => new Map(keys.sort().map((k) => [k, allocator.allocate(JSON.stringify([identityPrefix, kind, k]), kind === "service" ? `${prefix}--${k}` : `${prefix}--${kind}--${k}`)]));
911
+ const serviceNameMap = make("service", Object.keys(doc.services ?? {}));
741
912
  const volumeNameMap = make("volume", Object.keys(doc.volumes ?? {})), networkNameMap = make("network", Object.keys(doc.networks ?? {})), configNameMap = make("config", Object.keys(doc.configs ?? {})), secretNameMap = make("secret", Object.keys(doc.secrets ?? {}));
742
913
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
743
- const rewriteResourceRefs = (svc) => {
914
+ const rewriteResourceDefinitions = (obj, map) => Object.fromEntries(entries(obj).map(([key, definition]) => [map.get(key) ?? key, namespaceResourceDefinition(key, definition)]));
915
+ const addOriginalNetworkAliases = (name, svc) => {
916
+ if (svc.network_mode !== void 0 || svc.networks === void 0) return;
917
+ const attached = Array.isArray(svc.networks) ? Object.fromEntries(svc.networks.filter((network) => typeof network === "string").map((network) => [network, null])) : svc.networks && typeof svc.networks === "object" ? { ...svc.networks } : {};
918
+ for (const [network, rawOptions] of Object.entries(attached)) {
919
+ const options2 = rawOptions && typeof rawOptions === "object" && !Array.isArray(rawOptions) ? rawOptions : {};
920
+ const aliases = Array.isArray(options2.aliases) ? options2.aliases.filter((alias) => typeof alias === "string") : [];
921
+ attached[network] = { ...options2, aliases: [.../* @__PURE__ */ new Set([...aliases, name])] };
922
+ }
923
+ svc.networks = attached;
924
+ };
925
+ const rewriteResourceRefs = (svc, originalName) => {
926
+ rewriteBuildSecretReferences(svc, secretNameMap);
744
927
  if (Array.isArray(svc.depends_on)) {
745
928
  svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
746
929
  } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
@@ -755,33 +938,110 @@ function namespaceDependencyCompose(options) {
755
938
  }
756
939
  if (Array.isArray(svc.volumes_from)) svc.volumes_from = svc.volumes_from.map((v) => typeof v === "string" ? v.replace(/^([^:]+)(.*)$/, (all, n, rest) => `${serviceNameMap.get(n) ?? n}${rest}`) : v);
757
940
  if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => namespaceVolume(v, volumeNameMap));
758
- if (svc.networks === void 0 && svc.network_mode === void 0 && svc.extends === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
941
+ if (svc.networks === void 0 && svc.network_mode === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
759
942
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) svc[key] = `service:${serviceNameMap.get(svc[key].slice(8)) ?? svc[key].slice(8)}`;
760
- if (svc.extends && typeof svc.extends === "object" && !svc.extends.file) {
761
- const ref = svc.extends;
762
- if (typeof ref.service === "string") ref.service = serviceNameMap.get(ref.service) ?? ref.service;
763
- }
764
943
  if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
765
944
  else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
766
945
  for (const key of ["configs", "secrets"]) if (Array.isArray(svc[key])) svc[key] = svc[key].map((v) => typeof v === "string" ? (key === "configs" ? configNameMap : secretNameMap).get(v) ?? v : v && typeof v === "object" ? { ...v, source: (key === "configs" ? configNameMap : secretNameMap).get(v.source) ?? v.source } : v);
946
+ addOriginalNetworkAliases(originalName, svc);
767
947
  };
768
- for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
948
+ for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
769
949
  doc.services = rewriteKeys(doc.services, serviceNameMap);
770
- if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
771
- if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
772
- if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
773
- if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
950
+ if (doc.volumes) doc.volumes = rewriteResourceDefinitions(doc.volumes, volumeNameMap);
951
+ if (doc.networks) doc.networks = rewriteResourceDefinitions(doc.networks, networkNameMap);
952
+ if (doc.configs) doc.configs = rewriteResourceDefinitions(doc.configs, configNameMap);
953
+ if (doc.secrets) doc.secrets = rewriteResourceDefinitions(doc.secrets, secretNameMap);
774
954
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
775
955
  }
776
956
 
957
+ // src/core/composition/validateComposeResourceReferences.ts
958
+ function validateComposeResourceReferences(document, context, onlyServices) {
959
+ const fail = (configPath, kind, name) => {
960
+ throw new ConfigError({
961
+ sourceFile: context.sourceFile,
962
+ configPath,
963
+ ...context.stage ? { stage: context.stage } : {},
964
+ composition: context.composition,
965
+ referencedObject: name,
966
+ reason: `Compose ${kind} reference "${name}" has no top-level definition`
967
+ });
968
+ };
969
+ const exists = (kind, name) => {
970
+ const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
971
+ return Boolean(definitions && Object.hasOwn(definitions, name));
972
+ };
973
+ const check = (path22, kind, name) => {
974
+ if (kind === "network" && name === "default") return;
975
+ if (!exists(kind, name)) fail(path22, kind, name);
976
+ };
977
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
978
+ validateServiceResources(serviceName, service, check);
979
+ }
980
+ }
981
+ function validateServiceResources(serviceName, service, check) {
982
+ for (const mount of Array.isArray(service.volumes) ? service.volumes : []) {
983
+ const parsed = parseVolume(mount);
984
+ if (parsed?.type === "volume" && parsed.source) {
985
+ check(`services.${serviceName}.volumes`, "volume", parsed.source);
986
+ }
987
+ }
988
+ const networks = service.networks;
989
+ const networkNames = Array.isArray(networks) ? networks.filter((name) => typeof name === "string") : networks && typeof networks === "object" ? Object.keys(networks) : [];
990
+ for (const name of networkNames) {
991
+ check(`services.${serviceName}.networks`, "network", name);
992
+ }
993
+ for (const kind of ["configs", "secrets"]) {
994
+ const entries2 = service[kind];
995
+ if (!Array.isArray(entries2)) continue;
996
+ for (const entry of entries2) {
997
+ const name = typeof entry === "string" ? entry : entry && typeof entry === "object" && typeof entry.source === "string" ? entry.source : void 0;
998
+ if (name) check(`services.${serviceName}.${kind}`, kind === "configs" ? "config" : "secret", name);
999
+ }
1000
+ }
1001
+ for (const name of collectBuildSecretReferences(service)) {
1002
+ check(`services.${serviceName}.build.secrets`, "secret", name);
1003
+ }
1004
+ }
1005
+
1006
+ // src/core/composition/assertComposeLifecycleAcyclic.ts
1007
+ function assertComposeLifecycleAcyclic(services, context) {
1008
+ const graph = new Map(
1009
+ Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()])
1010
+ );
1011
+ for (const [name, service] of Object.entries(services)) {
1012
+ const value = service.depends_on;
1013
+ const targets = Array.isArray(value) ? value.filter((item) => typeof item === "string") : value && typeof value === "object" ? Object.keys(value) : [];
1014
+ for (const target of targets) {
1015
+ if (graph.has(target)) graph.get(name).add(target);
1016
+ }
1017
+ }
1018
+ assertAcyclicGraph(graph, context);
1019
+ }
1020
+
1021
+ // src/core/composition/composeHealthcheck.ts
1022
+ function isEnabledValidComposeHealthcheck(value) {
1023
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1024
+ const health = value;
1025
+ if (health.disable === true) return false;
1026
+ const test = health.test;
1027
+ if (typeof test === "string") return test.trim().length > 0;
1028
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
1029
+ if (test[0] !== "CMD" && test[0] !== "CMD-SHELL") return false;
1030
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
1031
+ }
1032
+
777
1033
  // src/core/composition/validateDependencyCompose.ts
778
1034
  function validateDependencyCompose(dependencyKey, dependency, document, context) {
779
1035
  const fail = (configPath, reason, value) => {
780
1036
  throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
781
1037
  };
782
1038
  if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
1039
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: "service" });
783
1040
  const services = document.services ?? {};
784
1041
  for (const [name, svc] of Object.entries(services)) {
1042
+ assertNoServiceBuildContexts(svc, `services.${name}`, context.composePath);
1043
+ if (svc.profiles !== void 0) fail(`services.${name}.profiles`, "dependency Compose profiles are unsupported because a materialized dependency is atomic");
1044
+ if (svc.extends !== void 0) fail(`services.${name}.extends`, "dependency Compose extends is unsupported until effective endpoint-owner networking and health can be validated");
785
1045
  if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
786
1046
  if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
787
1047
  if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
@@ -804,13 +1064,13 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
804
1064
  for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
805
1065
  }
806
1066
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
807
- if (svc.extends && typeof svc.extends === "object") {
808
- const ref = svc.extends;
809
- if (ref.file !== void 0) fail(`services.${name}.extends.file`, "external extends is unsupported for atomic dependency implementations");
810
- if (typeof ref.service === "string") internalRefs.push(["extends.service", ref.service]);
811
- }
812
1067
  for (const [property, target] of internalRefs) if (!services[target]) fail(`services.${name}.${property}`, `internal service reference "${target}" does not exist in this dependency Compose bundle`, target);
813
1068
  }
1069
+ assertComposeLifecycleAcyclic(services, {
1070
+ sourceFile: context.composePath,
1071
+ stage: context.stage,
1072
+ composition: "service"
1073
+ });
814
1074
  if (!Object.keys(dependency.endpoints).length) return;
815
1075
  if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
816
1076
  const owners = /* @__PURE__ */ new Set();
@@ -821,8 +1081,7 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
821
1081
  }
822
1082
  for (const owner of owners) {
823
1083
  if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
824
- const health = services[owner].healthcheck;
825
- if (!health || health.disable === true || !health.test || typeof health.test === "string" && !health.test.trim() || Array.isArray(health.test) && (!health.test.length || health.test[0] === "NONE" || health.test.every((v) => typeof v === "string" && !v.trim()))) fail(`services.${owner}.healthcheck`, `endpoint owner requires an enabled, non-empty healthcheck`);
1084
+ if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
826
1085
  }
827
1086
  }
828
1087
  function canonicalBuildContext(value, baseDir) {
@@ -832,24 +1091,48 @@ function isSameBuildContext(actual, expected, baseDir) {
832
1091
  return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
833
1092
  }
834
1093
  function validateAndPrepareAppOverride(document, context) {
835
- const fail = (path20, reason, value) => {
836
- throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1094
+ const fail = (path22, reason, value) => {
1095
+ throw new ConfigError({ sourceFile: context.file, configPath: path22, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
837
1096
  };
1097
+ const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1098
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
838
1099
  const keys = Object.keys(document.services ?? {});
839
1100
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
1101
+ validateComposeResourceReferences(document, { sourceFile: context.file, stage: context.stage, composition: "service" });
840
1102
  const app = structuredClone(document.services.app);
841
- for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
842
- if (app.healthcheck && typeof app.healthcheck === "object") {
843
- const health = app.healthcheck;
844
- for (const key of Object.keys(health)) if (!["interval", "timeout", "retries", "start_period", "start_interval"].includes(key)) fail(`services.app.healthcheck.${key}`, "override may set only healthcheck timing fields");
1103
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
1104
+ if (Object.hasOwn(app, "healthcheck")) {
1105
+ const healthcheck = app.healthcheck;
1106
+ if (healthcheck === null || typeof healthcheck !== "object" || Array.isArray(healthcheck)) {
1107
+ fail(
1108
+ "services.app.healthcheck",
1109
+ "override healthcheck must be a mapping of timing fields",
1110
+ healthcheck
1111
+ );
1112
+ }
1113
+ const allowedTiming = /* @__PURE__ */ new Set([
1114
+ "interval",
1115
+ "timeout",
1116
+ "retries",
1117
+ "start_period",
1118
+ "start_interval"
1119
+ ]);
1120
+ for (const key of Object.keys(healthcheck)) {
1121
+ if (!allowedTiming.has(key)) {
1122
+ fail(
1123
+ `services.app.healthcheck.${key}`,
1124
+ "override may set only healthcheck timing fields"
1125
+ );
1126
+ }
1127
+ }
845
1128
  }
846
1129
  if (typeof app.build === "string") {
847
1130
  fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
848
1131
  }
849
1132
  if (app.build && typeof app.build === "object") {
850
1133
  const build = app.build;
851
- for (const key of ["target", "dockerfile"]) {
852
- if (build[key] !== void 0) {
1134
+ for (const key of Object.keys(build)) {
1135
+ if (!["args", "context"].includes(key)) {
853
1136
  fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
854
1137
  }
855
1138
  }
@@ -865,24 +1148,26 @@ function validateAndPrepareAppOverride(document, context) {
865
1148
  const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
866
1149
  for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
867
1150
  app.environment = env;
1151
+ const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
868
1152
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
869
1153
  const resources = {};
870
1154
  for (const kind of resourceKeys) {
871
- const defs = document[kind] ?? {}, refs2 = /* @__PURE__ */ new Set(), value = app[kind];
1155
+ const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = app[kind];
872
1156
  if (Array.isArray(value)) for (const ref of value) {
873
1157
  if (kind === "volumes") {
874
1158
  const volume = parseVolume(ref);
875
- if (volume?.type === "volume" && volume.source) refs2.add(volume.source);
876
- } else if (typeof ref === "string") refs2.add(ref);
877
- else if (ref && typeof ref === "object" && typeof ref.source === "string") refs2.add(ref.source);
1159
+ if (volume?.type === "volume" && volume.source) refs.add(volume.source);
1160
+ } else if (typeof ref === "string") refs.add(ref);
1161
+ else if (ref && typeof ref === "object" && typeof ref.source === "string") refs.add(ref.source);
878
1162
  }
879
- else if (value && typeof value === "object") for (const name of Object.keys(value)) refs2.add(name);
1163
+ else if (value && typeof value === "object") for (const name of Object.keys(value)) refs.add(name);
880
1164
  const names = /* @__PURE__ */ new Map(), mapped = {};
881
1165
  for (const [name, definition] of Object.entries(defs)) {
882
- if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
883
- const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
1166
+ if (!refs.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1167
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1168
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
884
1169
  names.set(name, target);
885
- mapped[target] = definition;
1170
+ mapped[target] = namespaceResourceDefinition(name, definition);
886
1171
  }
887
1172
  if (names.size) resources[kind] = mapped;
888
1173
  if (Array.isArray(value)) app[kind] = value.map((ref) => kind === "volumes" ? namespaceVolume(ref, names) : typeof ref === "string" ? names.get(ref) ?? ref : ref && typeof ref === "object" && typeof ref.source === "string" ? { ...ref, source: names.get(ref.source) ?? ref.source } : ref);
@@ -891,6 +1176,26 @@ function validateAndPrepareAppOverride(document, context) {
891
1176
  return { app, resources };
892
1177
  }
893
1178
 
1179
+ // src/core/composition/mergeAppOverride.ts
1180
+ function isMap(value) {
1181
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1182
+ const prototype = Object.getPrototypeOf(value);
1183
+ return prototype === Object.prototype || prototype === null;
1184
+ }
1185
+ function mergeValue(inherited, overlay) {
1186
+ if (overlay === void 0) return structuredClone(inherited);
1187
+ if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1188
+ return Object.fromEntries(
1189
+ [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1190
+ key,
1191
+ Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1192
+ ])
1193
+ );
1194
+ }
1195
+ function mergeAppOverride(inherited, overlay) {
1196
+ return mergeValue(inherited, overlay);
1197
+ }
1198
+
894
1199
  // src/core/composition/dependencyLifecycle.ts
895
1200
  function asMap(value) {
896
1201
  if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
@@ -945,13 +1250,13 @@ function buildStandaloneDependencyEndpoints(key, build, serviceNames, materializ
945
1250
  function getExecutionProfile(stage, full) {
946
1251
  switch (stage) {
947
1252
  case "dev":
948
- return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
1253
+ return { configStage: "dev", envStage: "dev", appTarget: "dev", execMode: "dev", infraMode: full ? "integrated" : "isolated", attachTester: false };
949
1254
  case "prod":
950
- return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
1255
+ return { configStage: "prod", envStage: "prod", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: false };
951
1256
  case "test":
952
- return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
1257
+ return { configStage: "test", envStage: "test", appTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
953
1258
  case "e2e":
954
- return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
1259
+ return { configStage: "e2e", envStage: "e2e", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: true, testerTarget: "test-e2e" };
955
1260
  }
956
1261
  }
957
1262
  function mergeDocument(target, source, context) {
@@ -960,7 +1265,7 @@ function mergeDocument(target, source, context) {
960
1265
  if (!src) continue;
961
1266
  const dst = target[section] ??= {};
962
1267
  for (const [key, value] of Object.entries(src)) {
963
- if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
1268
+ if (key in dst) throw new ConfigError({ ...context, configPath: `${context.configPath}.${section}.${key}`, value: key, reason: "Internal Compose namespace collision" });
964
1269
  dst[key] = value;
965
1270
  }
966
1271
  }
@@ -974,24 +1279,22 @@ function getTemplateSeed(stage, meshMode) {
974
1279
  if (meshMode) delete merged.services.tester;
975
1280
  return merged;
976
1281
  }
977
- function ownEnv(build, stage) {
978
- const env = { ...build.app.env };
979
- const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
980
- for (const key of reserved) if (key in env) throw new ConfigError({ sourceFile: "build.json", configPath: "app.env", stage, composition: "service", value: key, reason: "Application env cannot set a Builder-owned key" });
981
- return env;
982
- }
983
- function resolveEnv(input, registry, source) {
1282
+ function resolveEnv(input, registry, baseContext) {
984
1283
  const out = {};
985
1284
  for (const [key, value] of Object.entries(input)) {
986
- collectBuilderReferences(value, "build", `${source}.${key}`);
987
- out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
1285
+ if (value === null) {
1286
+ out[key] = null;
1287
+ continue;
1288
+ }
1289
+ const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
1290
+ out[key] = interpolateBuilderReferences(value, "build", registry, context).replace(/\$/g, "$$$$");
988
1291
  }
989
1292
  return out;
990
1293
  }
991
- function addPorts(service, endpointPairs) {
1294
+ function addPorts(service, endpointPairs, sourceFile, stage) {
992
1295
  for (const [ep, hostPort] of endpointPairs) {
993
1296
  const ports = Array.isArray(service.ports) ? service.ports : [];
994
- if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ configPath: ep.logicalPath, stage: "service", value: hostPort, reason: "Duplicate host port publication" });
1297
+ if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ sourceFile, configPath: ep.logicalPath, stage, composition: "service", referencedObject: ep.logicalPath, value: hostPort, reason: "Duplicate host port publication" });
995
1298
  ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
996
1299
  service.ports = ports;
997
1300
  }
@@ -1002,28 +1305,29 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1002
1305
  const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1003
1306
  const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1004
1307
  const projectName = deriveProjectName(rawName, stage);
1308
+ const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1005
1309
  const namespaced = {};
1006
1310
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1007
1311
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1008
1312
  const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1009
1313
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1010
1314
  if (Object.keys(dep.endpoints).length) {
1011
- const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
1315
+ const ns = namespaceDependencyCompose({ dependencyKey: key, namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document, allocator: nameAllocator, identityPrefix: JSON.stringify(["service", options.appServiceName ?? "app", "dependency", key]) });
1012
1316
  namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1013
1317
  }
1014
1318
  }
1015
1319
  const materialized = {};
1016
1320
  const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
1017
1321
  let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
1018
- if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
1322
+ if (profile.infraMode === "integrated") for (const [key, entry] of Object.entries(namespaced)) {
1019
1323
  if (options.suppressDependencies?.has(key)) continue;
1020
1324
  const dep = effective.dependencies[key];
1021
1325
  const item = structuredClone(entry.doc);
1022
- mergeDocument(compose, item, `dependency ${key}`);
1326
+ mergeDocument(compose, item, { sourceFile: entry.source, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1023
1327
  const endpointOwnerMap = /* @__PURE__ */ new Map();
1024
1328
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1025
1329
  const endpointOwners = new Set(endpointOwnerMap.values());
1026
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
1330
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1027
1331
  }
1028
1332
  const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1029
1333
  const depEndpoints = {};
@@ -1047,7 +1351,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1047
1351
  for (const [name, e] of Object.entries(dep.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `dependencies.${key}.endpoints.${name}`, requested: e.publicPort });
1048
1352
  }
1049
1353
  }
1050
- const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
1354
+ const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode), { sourceFile: buildPath, composition: "service" });
1051
1355
  for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
1052
1356
  ep.publicHost = PUBLIC_HOST;
1053
1357
  ep.publicPort = allocation.get(ep.logicalPath);
@@ -1058,31 +1362,49 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1058
1362
  ep.publicPort = allocation.get(ep.logicalPath);
1059
1363
  ep.effectivelyPublished = true;
1060
1364
  }
1061
- const registry = (ref) => {
1365
+ const registry = (ref, context) => {
1062
1366
  if (ref.target === "app") {
1063
1367
  const ep2 = appEndpoints[ref.endpoint];
1064
- if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1065
- return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1368
+ if (!ep2) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1369
+ return resolveEndpointProperty(ep2, ref.property, { ...context, referencedObject: ref.raw });
1066
1370
  }
1067
1371
  const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1068
- if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1069
- return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
1372
+ if (!ep) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1373
+ return resolveEndpointProperty(ep, ref.property, { ...context, referencedObject: ref.raw });
1070
1374
  };
1071
1375
  for (const [key, dep] of Object.entries(effective.dependencies)) {
1072
- const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1376
+ const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, { sourceFile: buildPath, configPath: `dependencies.${key}.env`, stage, composition: "service" });
1073
1377
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1074
1378
  }
1075
- const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1076
- let buildAppEnvironment = { ...appEnv };
1077
- const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1078
- if (fs.existsSync(runtimeDotenv)) {
1079
- const text = fs.readFileSync(runtimeDotenv, "utf8");
1080
- for (const line of text.split(/\r?\n/)) {
1081
- const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
1082
- if (match && (match[1] !== "PORT" || getPrimaryEndpoint(effective.app.endpoints))) throw new ConfigError({ sourceFile: runtimeDotenv, configPath: match[1], stage, composition: "service", reason: "Dotenv file cannot define Builder-owned environment" });
1379
+ const appEnvironmentLayers = [];
1380
+ for (const layer of effective.layers) {
1381
+ if (Object.keys(layer.appEnv).length) {
1382
+ const configPath = layer.stage === "base" ? "app.env" : `${layer.stage}.app.env`;
1383
+ assertNoBuilderOwnedEnvKeys(layer.appEnv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { sourceFile: buildPath, configPath, stage, composition: "service" });
1384
+ appEnvironmentLayers.push({ kind: "build-json", stage: layer.stage, configPath, values: { ...layer.appEnv } });
1385
+ }
1386
+ }
1387
+ const resolveAppLayers = () => {
1388
+ const result = {};
1389
+ const laterKeys = new Set(Object.keys(options.externalAppEnv ?? {}));
1390
+ for (const [key, layer] of selectAppEnvironmentEntries(appEnvironmentLayers, laterKeys)) {
1391
+ if (layer.kind === "build-json") {
1392
+ const context = {
1393
+ sourceFile: buildPath,
1394
+ configPath: layer.configPath,
1395
+ stage,
1396
+ composition: "service"
1397
+ };
1398
+ result[key] = resolveEnv({ [key]: layer.values[key] }, registry, context)[key];
1399
+ } else {
1400
+ result[key] = layer.values[key];
1401
+ }
1083
1402
  }
1084
- }
1085
- const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1403
+ return result;
1404
+ };
1405
+ const runtimeDotenv = path.join(root, `.env.${profile.envStage}`);
1406
+ assertDotenvDoesNotDefineKeys(runtimeDotenv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { configPath: `.env.${profile.envStage}`, stage, composition: "service" });
1407
+ const internal = { EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1086
1408
  const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1087
1409
  const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1088
1410
  const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
@@ -1091,14 +1413,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1091
1413
  else delete appBuild.dockerfile;
1092
1414
  appBuild.target = profile.appTarget;
1093
1415
  app.build = appBuild;
1094
- app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
1095
- app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1416
+ app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.envStage}`) : `.env.${profile.envStage}`, required: false }];
1417
+ app.environment = { ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1096
1418
  if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1097
- for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
1419
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]], buildPath, stage);
1098
1420
  for (const [key, dependency] of Object.entries(materialized)) {
1099
1421
  for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1100
1422
  const endpoint = depEndpoints[key][epName];
1101
- if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
1423
+ if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]], dependency.composePath, stage);
1102
1424
  }
1103
1425
  for (const owner of dependency.endpointOwners) {
1104
1426
  const svc = compose.services[owner];
@@ -1111,34 +1433,47 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1111
1433
  }
1112
1434
  for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1113
1435
  }
1114
- if (effective.overrideCompose) {
1115
- const overridePath = resolveInsideProject(root, effective.overrideCompose, {
1436
+ for (const layer of effective.layers) {
1437
+ if (!layer.overrideCompose) continue;
1438
+ const overridePath = resolveInsideProject(root, layer.overrideCompose, {
1116
1439
  sourceFile: buildPath,
1117
- configPath: "override-compose",
1440
+ configPath: `${layer.stage}.override-compose`,
1118
1441
  stage
1119
1442
  });
1120
1443
  const loadedOverride = loadComposeDocument(overridePath, {
1121
1444
  sourceFile: buildPath,
1122
- configPath: "override-compose",
1445
+ configPath: `${layer.stage}.override-compose`,
1123
1446
  stage,
1124
1447
  composition: "service"
1125
1448
  });
1126
1449
  const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1127
1450
  const prepared = validateAndPrepareAppOverride(overrideDocument, {
1128
1451
  file: overridePath,
1129
- stage,
1452
+ stage: layer.stage === "base" ? stage : layer.stage,
1130
1453
  expectedBuildContext: String(appBuild.context),
1131
- buildContextBaseDir: outputDir
1454
+ buildContextBaseDir: outputDir,
1455
+ allocator: nameAllocator,
1456
+ resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1132
1457
  });
1133
- for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1134
- const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1135
- const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
1458
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, { sourceFile: overridePath, configPath: `${layer.stage}.override-compose`, stage, composition: "service" });
1459
+ const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, `${layer.stage}.override-compose.services.app.environment`);
1460
+ const overrideEnv = rawOverrideEnv;
1136
1461
  if (getPrimaryEndpoint(effective.app.endpoints) && "PORT" in overrideEnv) throw new ConfigError({ sourceFile: overridePath, configPath: "services.app.environment.PORT", stage, composition: "service", reason: "Override cannot set Builder-owned PORT" });
1137
- buildAppEnvironment = { ...appEnv, ...overrideEnv };
1138
- const merged = { ...app, ...prepared.app };
1139
- merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1462
+ const overrideStage = layer.stage === "base" ? stage : layer.stage;
1463
+ const stageOrder = { base: 0, dev: 1, prod: 1, test: 1, e2e: 2 };
1464
+ let insertAt = appEnvironmentLayers.findIndex((item) => (stageOrder[item.stage] ?? 0) > (stageOrder[overrideStage] ?? 0));
1465
+ if (insertAt < 0) insertAt = appEnvironmentLayers.length;
1466
+ appEnvironmentLayers.splice(insertAt, 0, { kind: "override-compose", stage: overrideStage, sourceFile: overridePath, configPath: `${layer.stage}.override-compose.services.app.environment`, values: overrideEnv });
1467
+ const preparedApp = { ...prepared.app };
1468
+ delete preparedApp.environment;
1469
+ delete preparedApp.build;
1470
+ const merged = mergeAppOverride(app, preparedApp);
1471
+ merged.environment = { ...app.environment, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1140
1472
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1141
- if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
1473
+ if (overrideBuild.args !== void 0) {
1474
+ const current = appBuild.args, incoming = overrideBuild.args;
1475
+ appBuild.args = current && incoming && typeof current === "object" && typeof incoming === "object" && !Array.isArray(current) && !Array.isArray(incoming) ? { ...current, ...incoming } : incoming;
1476
+ }
1142
1477
  merged.build = appBuild;
1143
1478
  merged.env_file = app.env_file;
1144
1479
  merged.depends_on = app.depends_on;
@@ -1146,19 +1481,27 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1146
1481
  compose.services.app = merged;
1147
1482
  app = merged;
1148
1483
  }
1484
+ if (!options.deferReferenceResolution) {
1485
+ const finalEnv = resolveAppLayers();
1486
+ app.environment = { ...finalEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1487
+ }
1149
1488
  if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1150
1489
  delete compose.services.app;
1151
1490
  compose.services[options.appServiceName] = app;
1152
1491
  }
1153
- if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
1492
+ if (profile.infraMode === "integrated") applyDependencyLifecycle(app, materialized, effective);
1154
1493
  if (profile.attachTester && !options.meshMode) {
1494
+ const testerDotenvPath = path.join(root, ".env.e2e-tester"), testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY];
1495
+ assertDotenvDoesNotDefineKeys(testerDotenvPath, testerBuilderKeys, { configPath: ".env.e2e-tester", stage: "e2e", composition: "service" });
1155
1496
  const testerEnvRaw = effective.tester?.env ?? {};
1156
- assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
1157
- const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1158
- compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1497
+ assertNoBuilderOwnedEnvKeys(testerEnvRaw, testerBuilderKeys, { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" });
1498
+ const testerContext = { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" };
1499
+ assertTesterReferencesArePublic(testerEnvRaw, "build", testerContext);
1500
+ const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, testerContext);
1501
+ compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: profile.testerTarget ?? "test-e2e" }, network_mode: "host", env_file: [{ path: ".env.e2e-tester", required: false }], environment: { ...testerEnv, EXEC_MODE: "e2e" }, depends_on: { app: { condition: "service_healthy" } } };
1159
1502
  }
1160
- const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1161
- return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, builderAppEnvironment, buildAppEnvironment, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1503
+ nameAllocator.assertUnique();
1504
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, appEnvironmentLayers, builderInternalEnvironment: { ...internal }, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyServiceNames: Object.fromEntries(Object.entries(materialized).map(([key, dep]) => [key, [...dep.serviceNames]])), dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1162
1505
  }
1163
1506
 
1164
1507
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1178,7 +1521,7 @@ function checkInfra(projectDir = process.cwd()) {
1178
1521
  checkDockerfileContract(buildJson, absProjectDir);
1179
1522
  checkYamlFiles(buildJson, absProjectDir);
1180
1523
  checkAllEffectiveServiceStages(absProjectDir);
1181
- console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1524
+ console.log(pc14.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1182
1525
  }
1183
1526
  function checkComposeAvailability() {
1184
1527
  const composeCheck = spawnSync(
@@ -1223,7 +1566,7 @@ function checkDependencies() {
1223
1566
  const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
1224
1567
  if (count > 25) {
1225
1568
  console.warn(
1226
- pc22.yellow(
1569
+ pc14.yellow(
1227
1570
  `
1228
1571
  \u26A0\uFE0F High Docker Network Count Warning: Detected ${count} networks. Docker's default address pool can become exhausted, resulting in "could not find an available, non-overlapping IPv4 address pool" errors.
1229
1572
  To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
@@ -1268,7 +1611,8 @@ var envSchema2 = z.record(z.string(), z.string());
1268
1611
  var meshServiceSchema = z.object({ path: z.string().min(1), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1269
1612
  var meshServiceStageOverlaySchema = z.object({ path: z.string().min(1).optional(), env: envSchema2.optional(), dependencies: z.record(identifierSchema2, serviceNameSchema).optional(), dependsOn: z.array(serviceNameSchema).optional(), publish: z.array(z.string()).optional() }).strict();
1270
1613
  var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1271
- var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: z.record(serviceNameSchema, meshServiceSchema), dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
1614
+ var rootServicesSchema = z.record(serviceNameSchema, meshServiceSchema).refine((services) => Object.keys(services).length >= 1, { message: "must contain at least one root service" });
1615
+ var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: rootServicesSchema, dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
1272
1616
 
1273
1617
  // src/core/mesh/getMeshJson.ts
1274
1618
  function getMeshJson(projectDir = process.cwd()) {
@@ -1296,14 +1640,15 @@ function getMeshJson(projectDir = process.cwd()) {
1296
1640
 
1297
1641
  // src/core/config/resolveMeshStage.ts
1298
1642
  function resolveMeshStage(mesh, stage, sourceFile) {
1299
- const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
1300
- for (const name of names) {
1301
- const base = mesh.services[name], patch = overlays[name];
1302
- const merged = { path: patch?.path ?? base?.path, env: mergeStringMap(base?.env, patch?.env), dependencies: { ...base?.dependencies ?? {}, ...patch?.dependencies ?? {} }, dependsOn: unionStable(base?.dependsOn, patch?.dependsOn), publish: unionStable(base?.publish, patch?.publish) };
1303
- if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1304
- services[name] = merged;
1643
+ if (Object.keys(mesh.services).length === 0) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "mesh.json must declare at least one root service" });
1644
+ const services = {};
1645
+ for (const [name, service] of Object.entries(mesh.services)) services[name] = { path: service.path, env: { ...service.env ?? {} }, dependencies: { ...service.dependencies ?? {} }, dependsOn: [...service.dependsOn ?? []], publish: [...service.publish ?? []] };
1646
+ for (const overlayStage of stageOverlayChain(stage)) for (const [name, patch] of Object.entries(mesh[overlayStage]?.services ?? {})) {
1647
+ const prior = services[name] ?? { path: void 0, env: {}, dependencies: {}, dependsOn: [], publish: [] };
1648
+ services[name] = { path: patch.path ?? prior.path, env: mergeStringMap(prior.env, patch.env), dependencies: { ...prior.dependencies, ...patch.dependencies ?? {} }, dependsOn: unionStable(prior.dependsOn, patch.dependsOn), publish: unionStable(prior.publish, patch.publish) };
1305
1649
  }
1306
1650
  if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1651
+ for (const [name, service] of Object.entries(services)) if (!service.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1307
1652
  const graph = /* @__PURE__ */ new Map();
1308
1653
  for (const [name, service] of Object.entries(services)) {
1309
1654
  if (!BUILDER_IDENTIFIER_PATTERN.test(name) || RESERVED_MESH_SERVICE_NAMES.has(name)) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", value: name, reason: "Invalid or reserved mesh service name" });
@@ -1381,40 +1726,56 @@ function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1381
1726
  }
1382
1727
 
1383
1728
  // src/core/mesh/v2/meshReferences.ts
1384
- function resolveMesh(ref, ctx, source) {
1729
+ function resolveMesh(ref, ctx, context) {
1385
1730
  const name = ref.meshService;
1386
- if (!ctx.services[name]) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1731
+ if (!ctx.services[name]) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1387
1732
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1388
- const ep = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1389
- if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1390
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1733
+ const endpoint = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1734
+ if (!endpoint) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1735
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1391
1736
  }
1392
- function resolveBuild(ref, consumer, ctx, source) {
1737
+ function resolveBuild(ref, consumer, ctx, context) {
1393
1738
  const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1394
- const ep = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1395
- if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist" });
1739
+ const endpoint = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1740
+ if (!endpoint) {
1741
+ const reason = provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist";
1742
+ throw new ConfigError({ ...context, referencedObject: ref.raw, reason });
1743
+ }
1396
1744
  try {
1397
- return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1745
+ return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1398
1746
  } catch (error) {
1399
- if (provider && error instanceof ConfigError) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`, reason: error.message });
1747
+ if (provider && error instanceof ConfigError) {
1748
+ throw new ConfigError({
1749
+ ...context,
1750
+ referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`,
1751
+ reason: error.message
1752
+ });
1753
+ }
1400
1754
  throw error;
1401
1755
  }
1402
1756
  }
1403
- function interpolate(value, scope, resolve, source) {
1404
- const sentinel = "\0DOLLAR\0";
1405
- return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
1406
- const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
1407
- return resolve(ref);
1408
- }).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
1757
+ function interpolate(value, scope, ctx, configPath, consumer) {
1758
+ const context = {
1759
+ sourceFile: scope === "mesh" ? ctx.meshJsonPath : ctx.services[consumer]?.buildJsonPath ?? ctx.meshJsonPath,
1760
+ configPath,
1761
+ stage: ctx.stage,
1762
+ composition: scope === "mesh" ? "mesh" : "service"
1763
+ };
1764
+ return interpolateBuilderReferences(value, scope, (ref, refContext) => scope === "mesh" ? resolveMesh(ref, ctx, refContext) : resolveBuild(ref, consumer, ctx, refContext), context).replace(/\$/g, "$$$$");
1409
1765
  }
1410
1766
  function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1411
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1767
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", ctx, `${sourcePrefix}.${key}`)]));
1412
1768
  }
1413
1769
  function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1414
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1415
- }
1416
- function assertMeshTesterEnvPublic(env, source) {
1417
- assertTesterReferencesArePublic(env, "mesh", source);
1770
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", ctx, `${sourcePrefix}.${key}`, consumer)]));
1771
+ }
1772
+ function assertMeshTesterEnvPublic(env, ctx, configPath = "tester.env") {
1773
+ assertTesterReferencesArePublic(env, "mesh", {
1774
+ sourceFile: ctx.meshJsonPath,
1775
+ configPath,
1776
+ stage: ctx.stage,
1777
+ composition: "mesh"
1778
+ });
1418
1779
  }
1419
1780
 
1420
1781
  // src/core/mesh/v2/lifecycle.ts
@@ -1444,95 +1805,147 @@ function applyMeshLifecycleEdges(services, edges) {
1444
1805
  }
1445
1806
  }
1446
1807
 
1447
- // src/core/mesh/v2/compileMeshTester.ts
1448
- function refs(svc) {
1449
- const out = [];
1450
- const add = (v) => {
1451
- if (typeof v === "string") out.push(v);
1452
- };
1453
- if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1454
- else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1455
- if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1456
- if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1457
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1458
- return out;
1808
+ // src/core/composition/composeDependsOn.ts
1809
+ function normalizeComposeDependsOn(value) {
1810
+ if (Array.isArray(value)) {
1811
+ return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1812
+ }
1813
+ return value && typeof value === "object" ? { ...value } : {};
1459
1814
  }
1460
- function referencedResources(svc, doc) {
1461
- const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1462
- for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1463
- if (typeof v === "string") {
1464
- const source = v.split(":")[0];
1465
- if (doc.volumes?.[source]) sets.volumes.add(source);
1466
- } else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
1467
- }
1468
- const nets = svc.networks;
1469
- if (Array.isArray(nets)) nets.forEach((n) => {
1470
- if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
1471
- });
1472
- else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
1473
- if (doc.networks?.[n]) sets.networks.add(n);
1474
- });
1475
- for (const kind of ["configs", "secrets"]) {
1476
- const v = svc[kind];
1477
- if (Array.isArray(v)) for (const x of v) {
1478
- const n = typeof x === "string" ? x : x?.source;
1479
- if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1815
+
1816
+ // src/core/mesh/v2/compileMeshTester.ts
1817
+ function appendEnvFile(existing, next) {
1818
+ if (existing === void 0) return [next];
1819
+ return Array.isArray(existing) ? [...existing, next] : [existing, next];
1820
+ }
1821
+ function envFilePaths(value) {
1822
+ const entries2 = Array.isArray(value) ? value : [value];
1823
+ return entries2.flatMap((entry) => typeof entry === "string" ? [entry] : entry && typeof entry === "object" && typeof entry.path === "string" ? [entry.path] : []);
1824
+ }
1825
+ function validateServiceReferences(document, sourceFile, stage) {
1826
+ for (const [name, service] of Object.entries(document.services)) {
1827
+ const refs = [];
1828
+ const add = (value) => {
1829
+ if (typeof value === "string" && value) refs.push(value);
1830
+ };
1831
+ if (Array.isArray(service.depends_on)) service.depends_on.forEach(add);
1832
+ else if (service.depends_on && typeof service.depends_on === "object") Object.keys(service.depends_on).forEach(add);
1833
+ if (Array.isArray(service.links)) service.links.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1834
+ if (Array.isArray(service.volumes_from)) service.volumes_from.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1835
+ for (const key of ["network_mode", "ipc", "pid"]) {
1836
+ const value = service[key];
1837
+ if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1480
1838
  }
1839
+ for (const ref of refs) if (!document.services[ref]) throw new ConfigError({ sourceFile, configPath: `services.${name}`, stage, composition: "mesh", referencedObject: ref, reason: "Tester Compose service reference does not exist" });
1840
+ }
1841
+ }
1842
+ function applyTesterBuildTarget(service) {
1843
+ if (service.build === void 0) return;
1844
+ if (typeof service.build === "string") {
1845
+ service.build = { context: service.build, target: "test-e2e" };
1846
+ return;
1481
1847
  }
1482
- return sets;
1848
+ if (service.build && typeof service.build === "object" && !Array.isArray(service.build)) service.build = { ...service.build, target: "test-e2e" };
1483
1849
  }
1484
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1485
- const meshPath = `${meshDir}/mesh.json`, file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1850
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1851
+ const meshPath = path.join(meshDir, "mesh.json"), file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1486
1852
  if (!raw.services || !raw.services[tester.service]) throw new ConfigError({ sourceFile: meshPath, configPath: "tester.service", stage, composition: "mesh", value: tester.service, reason: "Selected tester service does not exist in tester Compose" });
1487
- const included = /* @__PURE__ */ new Set(), visit = (name) => {
1488
- if (included.has(name)) return;
1489
- if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1490
- included.add(name);
1491
- for (const ref of refs(raw.services[name])) visit(ref);
1492
- };
1493
- visit(tester.service);
1494
- for (const name of included) {
1495
- const svc = raw.services[name];
1496
- if (name !== tester.service && svc.network_mode === "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Only the selected tester runner may use host networking" });
1497
- if (name === tester.service && svc.network_mode !== void 0 && svc.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1498
- if (name === tester.service && svc.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare networks" });
1499
- }
1500
- const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1501
- for (const name of included) {
1502
- const own = referencedResources(raw.services[name], raw);
1503
- for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
1504
- }
1505
- const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1506
- for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1507
- const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
1853
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" });
1854
+ validateServiceReferences(raw, file, stage);
1855
+ assertComposeLifecycleAcyclic(raw.services, {
1856
+ sourceFile: file,
1857
+ stage,
1858
+ composition: "mesh"
1859
+ });
1860
+ for (const [serviceName, service] of Object.entries(raw.services)) {
1861
+ if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${serviceName}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated safely" });
1862
+ assertNoServiceBuildContexts(service, `services.${serviceName}`, file);
1863
+ }
1864
+ const selectedRaw = raw.services[tester.service];
1865
+ if (selectedRaw.network_mode !== void 0 && selectedRaw.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1866
+ if (selectedRaw.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare Compose networks" });
1867
+ if (selectedRaw.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
1868
+ const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1869
+ const testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY], rawRunnerEnvironment = normalizeComposeEnvironment(selectedRaw.environment, "tester runner environment");
1870
+ assertNoBuilderOwnedEnvKeys(rawRunnerEnvironment, testerBuilderKeys, { sourceFile: file, configPath: `services.${tester.service}.environment`, stage, composition: "mesh" });
1871
+ for (const envFile of envFilePaths(selectedRaw.env_file)) assertDotenvDoesNotDefineKeys(path.resolve(meshDir, envFile), testerBuilderKeys, { configPath: `services.${tester.service}.env_file`, stage, composition: "mesh" });
1872
+ const meshTesterDotenv = path.join(meshDir, ".env.e2e-tester");
1873
+ assertDotenvDoesNotDefineKeys(meshTesterDotenv, testerBuilderKeys, { configPath: ".env.e2e-tester", stage, composition: "mesh" });
1874
+ const testerEnv = tester.env ?? {};
1875
+ assertNoBuilderOwnedEnvKeys(testerEnv, testerBuilderKeys, { sourceFile: meshPath, configPath: "tester.env", stage, composition: "mesh" });
1876
+ assertMeshTesterEnvPublic(testerEnv, meshCtx);
1877
+ const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: raw, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1508
1878
  const runner = ns.serviceNameMap.get(tester.service);
1509
1879
  const runnerSvc = ns.document.services[runner];
1510
- if (runnerSvc.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
1880
+ applyTesterBuildTarget(runnerSvc);
1511
1881
  runnerSvc.network_mode = "host";
1512
1882
  delete runnerSvc.networks;
1513
- const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1514
- const env = tester.env ?? {};
1515
- assertMeshTesterEnvPublic(env, "tester.env");
1516
- runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1517
- const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
1883
+ runnerSvc.env_file = appendEnvFile(runnerSvc.env_file, { path: ".env.e2e-tester", required: false });
1884
+ runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(testerEnv, meshCtx, "tester.env"), EXEC_MODE: "e2e" };
1885
+ const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1518
1886
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1519
1887
  runnerSvc.depends_on = depends;
1520
1888
  return { services: ns.document.services, ...ns.document.volumes ? { volumes: ns.document.volumes } : {}, ...ns.document.networks ? { networks: ns.document.networks } : {}, ...ns.document.configs ? { configs: ns.document.configs } : {}, ...ns.document.secrets ? { secrets: ns.document.secrets } : {}, runnerServiceName: runner };
1521
1889
  }
1890
+
1891
+ // src/core/mesh/v2/resolveMeshAppEnvironment.ts
1892
+ function resolveMeshAppEnvironmentLayers(serviceName, layers, context, laterKeys = /* @__PURE__ */ new Set()) {
1893
+ const result = {};
1894
+ for (const [key, layer] of selectAppEnvironmentEntries(layers, laterKeys)) {
1895
+ if (layer.kind === "build-json") {
1896
+ result[key] = resolveServiceBuildEnvThroughMesh(
1897
+ serviceName,
1898
+ { [key]: layer.values[key] },
1899
+ context,
1900
+ `services.${serviceName}.${layer.configPath}`
1901
+ )[key];
1902
+ } else {
1903
+ result[key] = layer.values[key];
1904
+ }
1905
+ }
1906
+ return result;
1907
+ }
1908
+ function validPort(value) {
1909
+ if (!/^\d+$/.test(value)) return void 0;
1910
+ const port = Number(value);
1911
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
1912
+ }
1913
+ function parsePublishedHostPort(value) {
1914
+ if (value && typeof value === "object") {
1915
+ const published = value.published;
1916
+ if (typeof published === "number" && Number.isInteger(published)) {
1917
+ return published >= 1 && published <= 65535 ? published : void 0;
1918
+ }
1919
+ if (typeof published === "string") return validPort(published);
1920
+ return void 0;
1921
+ }
1922
+ if (typeof value !== "string") return void 0;
1923
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
1924
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
1925
+ if (mapping.startsWith("[")) {
1926
+ const close = mapping.indexOf("]");
1927
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
1928
+ const suffix = mapping.slice(close + 1);
1929
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
1930
+ return match ? validPort(match[1]) : void 0;
1931
+ }
1932
+ const parts = mapping.split(":");
1933
+ if (parts.length === 2) return validPort(parts[0]);
1934
+ if (parts.length >= 3) {
1935
+ const hostIp = parts.slice(0, -2).join(":");
1936
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
1937
+ }
1938
+ return void 0;
1939
+ }
1940
+
1941
+ // src/utils/assertUniqueHostPortMappings.ts
1522
1942
  function assertUniqueHostPortMappings(yamlConfig) {
1523
1943
  const parsed = parse(yamlConfig);
1524
1944
  const owners = /* @__PURE__ */ new Map();
1525
1945
  for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1526
1946
  for (const port of service?.ports ?? []) {
1527
- let hostPort = null;
1528
- if (typeof port === "string") {
1529
- const parts = port.split(":");
1530
- if (parts.length === 2) hostPort = Number(parts[0]);
1531
- if (parts.length === 3) hostPort = Number(parts[1]);
1532
- } else if (port && typeof port === "object" && "published" in port) {
1533
- hostPort = Number(port.published);
1534
- }
1535
- if (!hostPort || !Number.isInteger(hostPort)) continue;
1947
+ const hostPort = parsePublishedHostPort(port);
1948
+ if (hostPort === void 0) continue;
1536
1949
  const existing = owners.get(hostPort);
1537
1950
  if (existing) {
1538
1951
  throw new ScriptError(
@@ -1561,6 +1974,26 @@ function appendPort(service, target, published) {
1561
1974
  ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1562
1975
  service.ports = ports;
1563
1976
  }
1977
+ function buildMeshPortIntents(services, publication) {
1978
+ const intents = [];
1979
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
1980
+ const service = services[name];
1981
+ const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1982
+ for (const pub of appPublications) {
1983
+ const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
1984
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1985
+ }
1986
+ const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
1987
+ for (const dependency of dependencyNames) {
1988
+ const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1989
+ for (const pub of dependencyPublications) {
1990
+ const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
1991
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1992
+ }
1993
+ }
1994
+ }
1995
+ return intents;
1996
+ }
1564
1997
  function ownerFor(pub, fragment) {
1565
1998
  return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1566
1999
  }
@@ -1568,15 +2001,20 @@ function setEnv(service, env) {
1568
2001
  const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1569
2002
  service.environment = { ...current, ...env };
1570
2003
  }
2004
+ function attachNetworkIfCompatible(service, networkName) {
2005
+ if (service.network_mode !== void 0) return;
2006
+ service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
2007
+ }
1571
2008
  function compileMeshComposition(stage, meshDir, options = {}) {
1572
2009
  const meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, stage, meshPath), services = loadEffectiveMeshServices(meshDir, effective, stage), bindings = buildDependencyBindings(services, stage, meshPath), bindingMap = bindingsMap(bindings);
1573
2010
  const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
2011
+ const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
1574
2012
  const fragments = {};
1575
2013
  const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1576
2014
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1577
2015
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((ep) => svc.effectiveBuild.app.endpoints[ep]?.primary) ? ["PORT"] : []]) if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage, composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1578
2016
  const suppress = new Set(Object.keys(svc.dependencyBindings));
1579
- const fragment = compileServiceComposition(stage, svc.absolutePath, { full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
2017
+ const fragment = compileServiceComposition(stage, svc.absolutePath, { nameAllocator, full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
1580
2018
  fragments[name] = fragment;
1581
2019
  mergeFragment(compose, fragment.compose, name);
1582
2020
  const app = compose.services[name];
@@ -1591,31 +2029,19 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1591
2029
  const owner = ep.networkHost;
1592
2030
  const ownerService = compose.services[owner];
1593
2031
  if (ownerService) {
1594
- const old = normalizeNetworks(ownerService.networks);
1595
- old[privateName] = null;
1596
- ownerService.networks = old;
2032
+ attachNetworkIfCompatible(ownerService, privateName);
2033
+ attachNetworkIfCompatible(ownerService, "mesh");
1597
2034
  }
1598
2035
  }
1599
- for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
2036
+ for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
1600
2037
  const ownerService = compose.services[generated];
1601
- const old = normalizeNetworks(ownerService.networks);
1602
- old[privateName] = null;
1603
- ownerService.networks = old;
2038
+ attachNetworkIfCompatible(ownerService, privateName);
1604
2039
  }
1605
2040
  }
1606
2041
  }
1607
2042
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1608
2043
  }
1609
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1610
- for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint))) {
1611
- const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1612
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1613
- }
1614
- for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "dependency").sort((a, b) => `${a.dependency}.${a.endpoint}`.localeCompare(`${b.dependency}.${b.endpoint}`))) {
1615
- const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1616
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1617
- }
1618
- const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
2044
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode), { sourceFile: meshPath, composition: "mesh" });
1619
2045
  const endpoints = { app: {}, dependencies: {} };
1620
2046
  for (const [name, svc] of Object.entries(services)) {
1621
2047
  endpoints.app[name] = {};
@@ -1652,15 +2078,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1652
2078
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1653
2079
  for (const [name, fragment] of Object.entries(fragments)) {
1654
2080
  const app = compose.services[name];
1655
- const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1656
2081
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1657
- setEnv(app, { ...buildEnv, ...meshEnv });
2082
+ const serviceEnv = resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, refContext, new Set(Object.keys(meshEnv)));
2083
+ app.environment = { ...serviceEnv, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1658
2084
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1659
2085
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1660
2086
  if (logicalBinding) continue;
1661
2087
  const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1662
- const prefix = `svc--${name}--dep--${depName}--`;
1663
- for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
2088
+ for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
2089
+ const service = compose.services[serviceName];
2090
+ if (service) setEnv(service, resolvedDep);
2091
+ }
1664
2092
  }
1665
2093
  }
1666
2094
  const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
@@ -1695,40 +2123,115 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1695
2123
  let testerServiceName;
1696
2124
  if (stage === "e2e") {
1697
2125
  if (!raw.tester && !options.allowMissingTester) throw new ConfigError({ sourceFile: meshPath, configPath: "tester", stage, composition: "mesh", reason: "Global mesh E2E requires root mesh.json.tester { compose, service, env? }" });
1698
- const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
2126
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
1699
2127
  if (built) {
1700
2128
  const fragment = { services: built.services, ...built.volumes ? { volumes: built.volumes } : {}, ...built.networks ? { networks: built.networks } : {}, ...built.configs ? { configs: built.configs } : {}, ...built.secrets ? { secrets: built.secrets } : {} };
1701
2129
  mergeFragment(compose, fragment, "mesh tester");
1702
2130
  testerServiceName = built.runnerServiceName;
1703
2131
  }
1704
2132
  }
2133
+ nameAllocator.assertUnique();
1705
2134
  const yaml = stringify(compose);
1706
2135
  assertUniqueHostPortMappings(yaml);
1707
2136
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1708
2137
  }
1709
2138
 
2139
+ // src/core/mesh/v2/validateMeshTestStage.ts
2140
+ function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
2141
+ const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
2142
+ const publication = resolveMeshPublication(
2143
+ services,
2144
+ bindings,
2145
+ "test",
2146
+ meshPath
2147
+ );
2148
+ for (const pub of publication) {
2149
+ if (pub.target === "dependency") {
2150
+ throw new ConfigError({
2151
+ sourceFile: meshPath,
2152
+ configPath: `services.${pub.ownerMeshService}.publish`,
2153
+ stage: "test",
2154
+ composition: "mesh",
2155
+ value: pub.logicalPath,
2156
+ reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
2157
+ });
2158
+ }
2159
+ }
2160
+ const appPublications = publication.filter((pub) => pub.target === "app").sort(
2161
+ (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
2162
+ ).map((pub) => {
2163
+ const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
2164
+ return {
2165
+ meshService: pub.ownerMeshService,
2166
+ endpoint: pub.endpoint,
2167
+ logicalPath: pub.logicalPath,
2168
+ containerPort: endpoint.port,
2169
+ requested: endpoint.publicPort
2170
+ };
2171
+ });
2172
+ const allocatedPorts = /* @__PURE__ */ new Map();
2173
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
2174
+ const intents = appPublications.filter((pub) => pub.meshService === name).map((pub) => ({
2175
+ logicalPath: pub.logicalPath,
2176
+ requested: pub.requested
2177
+ }));
2178
+ const ownPorts = allocateHostPorts(
2179
+ meshDir,
2180
+ "test",
2181
+ intents,
2182
+ validationMode,
2183
+ { sourceFile: meshPath, composition: "mesh" }
2184
+ );
2185
+ for (const [logicalPath, port] of ownPorts) allocatedPorts.set(logicalPath, port);
2186
+ }
2187
+ return { bindings, appPublications, allocatedPorts };
2188
+ }
2189
+ function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
2190
+ for (const publication of validated.appPublications) {
2191
+ if (publication.meshService !== meshService) continue;
2192
+ const published = validated.allocatedPorts.get(publication.logicalPath);
2193
+ const ports = Array.isArray(app.ports) ? app.ports : [];
2194
+ ports.push({
2195
+ target: publication.containerPort,
2196
+ published,
2197
+ host_ip: PUBLIC_HOST,
2198
+ protocol: "tcp"
2199
+ });
2200
+ app.ports = ports;
2201
+ const endpoint = endpointRegistry[publication.endpoint];
2202
+ if (endpoint) {
2203
+ endpoint.publicHost = PUBLIC_HOST;
2204
+ endpoint.publicPort = published;
2205
+ endpoint.effectivelyPublished = true;
2206
+ }
2207
+ }
2208
+ }
2209
+
1710
2210
  // src/core/mesh/checkers/checkMeshServices.ts
1711
- function checkMeshServices(mesh, meshDir) {
2211
+ function checkMeshServices(mesh, meshDir, options = {}) {
1712
2212
  const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
1713
2213
  const checked = /* @__PURE__ */ new Set();
1714
- for (const stage of ["dev", "prod", "test", "e2e"]) {
2214
+ const stages = options.includeTestStage ? ["dev", "prod", "test", "e2e"] : ["dev", "prod", "e2e"];
2215
+ for (const stage of stages) {
1715
2216
  const effective = resolveMeshStage(mesh, stage, meshPath);
1716
2217
  const services = loadEffectiveMeshServices(root, effective, stage);
2218
+ const testValidation = stage === "test" ? validateMeshTestStage(services, root, meshPath, true) : void 0;
1717
2219
  for (const [name, svc] of Object.entries(services)) {
1718
2220
  if (!checked.has(svc.absolutePath)) {
1719
- console.log(pc22.cyan(`
2221
+ console.log(pc14.cyan(`
1720
2222
  \u{1F50D} Checking mesh service ${name}...`));
1721
2223
  checkInfra(svc.absolutePath);
1722
2224
  checked.add(svc.absolutePath);
1723
2225
  }
1724
2226
  if (stage === "test") {
1725
2227
  const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
2228
+ applyTestAppPublications(testValidation, name, fragment.compose.services.app, fragment.endpoints.app);
1726
2229
  const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
1727
2230
  const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
1728
2231
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1729
2232
  if (key in svc.meshEnv) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
1730
2233
  }
1731
- resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2234
+ resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, ctx, new Set(Object.keys(svc.meshEnv)));
1732
2235
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1733
2236
  resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1734
2237
  }
@@ -1751,11 +2254,13 @@ function checkMeshTester(mesh, meshDir, options = {}) {
1751
2254
  function checkMesh(meshDir = process.cwd(), options = {}) {
1752
2255
  const absMeshDir = resolveProjectDir(meshDir);
1753
2256
  const mesh = getMeshJson(absMeshDir);
1754
- checkMeshServices(mesh, absMeshDir);
2257
+ checkMeshServices(mesh, absMeshDir, {
2258
+ includeTestStage: Boolean(options.includeTestStage)
2259
+ });
1755
2260
  checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
1756
2261
  console.log(
1757
- pc22.bold(
1758
- pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2262
+ pc14.bold(
2263
+ pc14.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
1759
2264
  )
1760
2265
  );
1761
2266
  }
@@ -1875,18 +2380,19 @@ function ensureSignalHandlers() {
1875
2380
  }
1876
2381
  if (isShuttingDown) return;
1877
2382
  isShuttingDown = true;
1878
- for (const item of activeComposeSet) {
1879
- try {
1880
- teardownCompose(item.yamlConfig, item.projectDir, {
1881
- removeVolumes: item.removeVolumes ?? false
1882
- }).catch(() => {
1883
- });
1884
- } catch {
1885
- }
1886
- }
1887
- activeComposeSet.clear();
1888
2383
  const signalNumber = os.constants.signals[signal] ?? 0;
1889
- process.exit(128 + signalNumber);
2384
+ void (async () => {
2385
+ for (const item of activeComposeSet) {
2386
+ try {
2387
+ await teardownCompose(item.yamlConfig, item.projectDir, {
2388
+ removeVolumes: item.removeVolumes ?? false
2389
+ });
2390
+ activeComposeSet.delete(item);
2391
+ } catch (error) {
2392
+ console.error("Compose cleanup failed during signal shutdown:", error);
2393
+ }
2394
+ }
2395
+ })().finally(() => process.exit(128 + signalNumber));
1890
2396
  };
1891
2397
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1892
2398
  for (const sig of SIGNALS) {
@@ -1982,17 +2488,11 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
1982
2488
  6e4
1983
2489
  );
1984
2490
  }
1985
- if (result.error) {
1986
- if (!silent) {
1987
- console.error(
1988
- pc22.red(`Failed to run docker compose down: ${result.error.message}`)
1989
- );
1990
- }
1991
- } else if (result.status !== 0 && !silent) {
1992
- console.error(
1993
- pc22.red(
1994
- `Docker compose down exited with non-zero status code: ${result.status}`
1995
- )
2491
+ if (result.error || result.status !== 0) {
2492
+ const detail = result.error?.message ?? `exit code ${result.status ?? "unknown"}`;
2493
+ throw new ScriptError(
2494
+ `Failed to tear down Compose project in ${absProjectDir} after two attempts: ${detail}`,
2495
+ result.error ? { cause: result.error } : void 0
1996
2496
  );
1997
2497
  }
1998
2498
  } finally {
@@ -2124,7 +2624,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2124
2624
  );
2125
2625
  }
2126
2626
  console.log(
2127
- pc22.cyan(`
2627
+ pc14.cyan(`
2128
2628
  \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2129
2629
  );
2130
2630
  if (options.debug) {
@@ -2132,7 +2632,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2132
2632
  const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
2133
2633
  const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2134
2634
  console.log(
2135
- pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
2635
+ pc14.yellow("\nFinal merged Mesh YAML configuration:\n"),
2136
2636
  redactYamlSecrets(yaml)
2137
2637
  );
2138
2638
  } catch {
@@ -2153,7 +2653,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2153
2653
  }
2154
2654
  clearRunState(meshDir);
2155
2655
  console.log(
2156
- pc22.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2656
+ pc14.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2157
2657
  `)
2158
2658
  );
2159
2659
  return 0;
@@ -2190,6 +2690,36 @@ Examples:
2190
2690
  }
2191
2691
  );
2192
2692
  };
2693
+
2694
+ // src/core/runWithCleanup.ts
2695
+ async function runWithCleanup(run, cleanup) {
2696
+ let executionFailed = false;
2697
+ let executionError;
2698
+ try {
2699
+ const status = await run();
2700
+ if (status !== 0) {
2701
+ executionFailed = true;
2702
+ executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2703
+ }
2704
+ return status;
2705
+ } catch (error) {
2706
+ executionFailed = true;
2707
+ executionError = error;
2708
+ throw error;
2709
+ } finally {
2710
+ try {
2711
+ await cleanup();
2712
+ } catch (cleanupError) {
2713
+ if (executionFailed) {
2714
+ throw new AggregateError(
2715
+ [executionError, cleanupError],
2716
+ `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2717
+ );
2718
+ }
2719
+ throw cleanupError;
2720
+ }
2721
+ }
2722
+ }
2193
2723
  function extractHostPorts(yamlConfig) {
2194
2724
  const ports = [];
2195
2725
  try {
@@ -2197,15 +2727,9 @@ function extractHostPorts(yamlConfig) {
2197
2727
  if (parsed?.services && typeof parsed.services === "object") {
2198
2728
  for (const svc of Object.values(parsed.services)) {
2199
2729
  if (Array.isArray(svc?.ports)) {
2200
- for (const p of svc.ports) {
2201
- if (typeof p === "string") {
2202
- const parts = p.split(":");
2203
- const hostPort = parts.length > 1 ? parseInt(parts[0], 10) : parseInt(p, 10);
2204
- if (!isNaN(hostPort)) ports.push(hostPort);
2205
- } else if (typeof p === "object" && p.published) {
2206
- const hostPort = parseInt(p.published, 10);
2207
- if (!isNaN(hostPort)) ports.push(hostPort);
2208
- }
2730
+ for (const mapping of svc.ports) {
2731
+ const hostPort = parsePublishedHostPort(mapping);
2732
+ if (hostPort !== void 0) ports.push(hostPort);
2209
2733
  }
2210
2734
  }
2211
2735
  }
@@ -2296,19 +2820,19 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2296
2820
  // src/core/mesh/runners/runMeshDev.ts
2297
2821
  async function runMeshDev(options = {}) {
2298
2822
  const meshDir = resolveProjectDir(options.projectDir);
2299
- console.log(pc22.cyan(`
2823
+ console.log(pc14.cyan(`
2300
2824
  \u{1F680} Starting Global DEV Mesh Environment...`));
2301
2825
  const { yaml } = compileMeshEnvironment("dev", meshDir);
2302
2826
  const parsed = parse(yaml);
2303
2827
  const projectName = parsed?.name || "mesh-dev";
2304
2828
  if (options.debug) {
2305
2829
  console.log(
2306
- pc22.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2830
+ pc14.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2307
2831
  redactYamlSecrets(yaml)
2308
2832
  );
2309
2833
  }
2310
2834
  if (options.dryRun) {
2311
- console.log(pc22.green("Dry run complete. Compose was not started."));
2835
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2312
2836
  return 0;
2313
2837
  }
2314
2838
  const hostPorts = extractHostPorts(yaml);
@@ -2323,34 +2847,34 @@ async function runMeshDev(options = {}) {
2323
2847
  if (options.detach) {
2324
2848
  upArgs.push("-d");
2325
2849
  }
2326
- let status = 0;
2327
- try {
2328
- status = await runCompose(upArgs, yaml, meshDir, {
2850
+ const status = await runWithCleanup(
2851
+ () => runCompose(upArgs, yaml, meshDir, {
2329
2852
  removeVolumes: false
2330
- });
2331
- } finally {
2332
- if (!options.detach) {
2333
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2334
- clearRunState(meshDir);
2853
+ }),
2854
+ async () => {
2855
+ if (!options.detach) {
2856
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2857
+ clearRunState(meshDir);
2858
+ }
2335
2859
  }
2336
- }
2860
+ );
2337
2861
  return status;
2338
2862
  }
2339
2863
  async function runMeshProd(options = {}) {
2340
2864
  const meshDir = resolveProjectDir(options.projectDir);
2341
- console.log(pc22.cyan(`
2865
+ console.log(pc14.cyan(`
2342
2866
  \u{1F3ED} Starting Global PROD Mesh Environment...`));
2343
2867
  const { yaml } = compileMeshEnvironment("prod", meshDir);
2344
2868
  const parsed = parse(yaml);
2345
2869
  const projectName = parsed?.name || "mesh-prod";
2346
2870
  if (options.debug) {
2347
2871
  console.log(
2348
- pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2872
+ pc14.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2349
2873
  redactYamlSecrets(yaml)
2350
2874
  );
2351
2875
  }
2352
2876
  if (options.dryRun) {
2353
- console.log(pc22.green("Dry run complete. Compose was not started."));
2877
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2354
2878
  return 0;
2355
2879
  }
2356
2880
  const hostPorts = extractHostPorts(yaml);
@@ -2365,88 +2889,267 @@ async function runMeshProd(options = {}) {
2365
2889
  if (options.detach) {
2366
2890
  upArgs.push("-d");
2367
2891
  }
2368
- let status = 0;
2369
- try {
2370
- status = await runCompose(upArgs, yaml, meshDir, {
2892
+ const status = await runWithCleanup(
2893
+ () => runCompose(upArgs, yaml, meshDir, {
2371
2894
  removeVolumes: false
2372
- });
2373
- } finally {
2374
- if (!options.detach) {
2375
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2376
- clearRunState(meshDir);
2895
+ }),
2896
+ async () => {
2897
+ if (!options.detach) {
2898
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2899
+ clearRunState(meshDir);
2900
+ }
2377
2901
  }
2378
- }
2902
+ );
2379
2903
  return status;
2380
2904
  }
2381
- async function runMeshTestUnit(options = {}) {
2382
- const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
2383
- console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2384
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2385
- console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
2386
- const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
2387
- const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
2388
- const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2389
- const env = svc.meshEnv;
2390
- for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((k) => svc.effectiveBuild.app.endpoints[k]?.primary) ? ["PORT"] : []]) if (key in env) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
2391
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2392
- for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2393
- const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2394
- const app = compiled.compose.services.app;
2395
- app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2396
- const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2397
- compiled.compose.name = projectName;
2398
- const yaml = stringify(compiled.compose);
2399
- if (options.debug) console.log(yaml);
2400
- if (options.dryRun) {
2401
- console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
2402
- continue;
2403
- }
2404
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
2405
- writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
2406
- let status;
2407
- try {
2408
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
2409
- } finally {
2410
- await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
2411
- clearRunState(svc.absolutePath);
2412
- }
2413
- if (status !== 0) return status;
2905
+ var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2906
+
2907
+ // src/core/runners/runTestUnit.ts
2908
+ var runTestUnit = async (options) => {
2909
+ if (!options.skipBanner) {
2910
+ console.log(pc14.bold(pc14.blue(`
2911
+ ========================================`)));
2912
+ console.log(pc14.bold(pc14.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2913
+ console.log(pc14.bold(pc14.blue(`========================================
2914
+ `)));
2915
+ }
2916
+ const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2917
+ silenceWarnings: options.silenceWarnings
2918
+ });
2919
+ const parsed = parse(finalYamlConfig);
2920
+ const projectName = parsed?.name || "test";
2921
+ if (options.debug) {
2922
+ console.log(
2923
+ pc14.yellow("Final merged YAML configuration:\n"),
2924
+ redactYamlSecrets(finalYamlConfig)
2925
+ );
2414
2926
  }
2415
- return 0;
2416
- }
2417
- async function runMeshTestE2e(options = {}) {
2418
- const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
2419
- if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
2420
- const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
2421
- if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
2422
- if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
2423
2927
  if (options.dryRun) {
2424
- console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
2928
+ console.log(pc14.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2425
2929
  return 0;
2426
2930
  }
2427
- await checkHostPortCollisions(extractHostPorts(yaml));
2428
- const projectName = parse(yaml)?.name || "mesh-e2e";
2429
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2430
- writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
2431
- let status = 0;
2432
- try {
2433
- status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
2434
- } finally {
2435
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
2436
- clearRunState(meshDir);
2931
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2932
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2933
+ removeVolumes: true,
2934
+ silent: true
2935
+ });
2936
+ writeRunState(options.projectDir, {
2937
+ projectName,
2938
+ stage: "test-unit",
2939
+ projectDir: options.projectDir
2940
+ });
2941
+ const status = await runWithCleanup(
2942
+ () => runCompose(
2943
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2944
+ finalYamlConfig,
2945
+ options.projectDir,
2946
+ { removeVolumes: true }
2947
+ ),
2948
+ async () => {
2949
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2950
+ clearRunState(options.projectDir);
2951
+ }
2952
+ );
2953
+ if (status === 0) {
2954
+ console.log(pc14.bold(pc14.green(`
2955
+ \u2705 Unit tests passed successfully.
2956
+ `)));
2957
+ } else {
2958
+ console.error(pc14.red(`
2959
+ \u274C Unit tests failed with exit code ${status}.
2960
+ `));
2961
+ }
2962
+ return status;
2963
+ };
2964
+ var runTestE2e = async (options) => {
2965
+ if (!options.skipBanner) {
2966
+ console.log(pc14.bold(pc14.blue(`
2967
+ ========================================`)));
2968
+ console.log(pc14.bold(pc14.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2969
+ console.log(pc14.bold(pc14.blue(`========================================
2970
+ `)));
2971
+ }
2972
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2973
+ silenceWarnings: options.silenceWarnings
2974
+ });
2975
+ const parsed = parse(finalYamlConfig);
2976
+ const projectName = parsed?.name || "e2e";
2977
+ if (options.debug) {
2978
+ console.log(
2979
+ pc14.yellow("Final merged YAML configuration:\n"),
2980
+ redactYamlSecrets(finalYamlConfig)
2981
+ );
2982
+ }
2983
+ if (options.dryRun) {
2984
+ console.log(pc14.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2985
+ return 0;
2986
+ }
2987
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2988
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2989
+ removeVolumes: true,
2990
+ silent: true
2991
+ });
2992
+ writeRunState(options.projectDir, {
2993
+ projectName,
2994
+ stage: "test-e2e",
2995
+ projectDir: options.projectDir
2996
+ });
2997
+ const status = await runWithCleanup(
2998
+ () => runCompose(
2999
+ [
3000
+ "up",
3001
+ "--build",
3002
+ "--abort-on-container-exit",
3003
+ "--exit-code-from",
3004
+ "tester"
3005
+ ],
3006
+ finalYamlConfig,
3007
+ options.projectDir,
3008
+ { removeVolumes: true }
3009
+ ),
3010
+ async () => {
3011
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3012
+ clearRunState(options.projectDir);
3013
+ }
3014
+ );
3015
+ if (status === 0) {
3016
+ console.log(pc14.bold(pc14.green(`
3017
+ \u2705 E2E tests passed successfully.
3018
+ `)));
3019
+ } else {
3020
+ console.error(pc14.red(`
3021
+ \u274C E2E tests failed with exit code ${status}.
3022
+ `));
3023
+ }
3024
+ return status;
3025
+ };
3026
+
3027
+ // src/core/runners/runTest.ts
3028
+ var runTest = async (options) => {
3029
+ console.log(pc14.bold(pc14.blue(`
3030
+ ========================================`)));
3031
+ console.log(pc14.bold(pc14.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3032
+ console.log(pc14.bold(pc14.blue(`========================================
3033
+ `)));
3034
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3035
+ if (unitStatus !== 0) {
3036
+ console.error(
3037
+ pc14.red(
3038
+ `
3039
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3040
+ `
3041
+ )
3042
+ );
3043
+ return unitStatus;
3044
+ }
3045
+ console.log(
3046
+ pc14.bold(pc14.green(`
3047
+ \u2705 [1/2] Unit tests passed successfully.
3048
+ `))
3049
+ );
3050
+ console.log(pc14.bold(pc14.blue(`========================================`)));
3051
+ console.log(pc14.bold(pc14.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3052
+ console.log(pc14.bold(pc14.blue(`========================================
3053
+ `)));
3054
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3055
+ if (e2eStatus !== 0) {
3056
+ console.error(
3057
+ pc14.red(`
3058
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3059
+ `)
3060
+ );
3061
+ return e2eStatus;
3062
+ }
3063
+ console.log(pc14.bold(pc14.green(`
3064
+ \u2705 [2/2] E2E tests passed successfully.
3065
+ `)));
3066
+ console.log(
3067
+ pc14.bold(
3068
+ pc14.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3069
+ `)
3070
+ )
3071
+ );
3072
+ return 0;
3073
+ };
3074
+
3075
+ // src/core/mesh/runners/runMeshServiceTests.ts
3076
+ async function runMeshServiceTests(options = {}) {
3077
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), mesh = getMeshJson(meshDir);
3078
+ const rootServices = Object.entries(mesh.services).sort(([left], [right]) => left.localeCompare(right));
3079
+ for (const [serviceName, service] of rootServices) {
3080
+ const serviceDir = resolveInsideProject(meshDir, service.path, { sourceFile: meshPath, configPath: `services.${serviceName}.path`, stage: "test" });
3081
+ console.log(pc14.bold(pc14.cyan(`
3082
+ -> Running full standalone test lifecycle for [${serviceName}]
3083
+ `)));
3084
+ const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} });
3085
+ if (status !== 0) return status;
2437
3086
  }
3087
+ return 0;
3088
+ }
3089
+ async function runMeshTestE2e(options = {}) {
3090
+ const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
3091
+ if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
3092
+ const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
3093
+ if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
3094
+ if (options.debug) console.log(pc14.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
3095
+ if (options.dryRun) {
3096
+ console.log(pc14.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
3097
+ return 0;
3098
+ }
3099
+ await checkHostPortCollisions(extractHostPorts(yaml));
3100
+ const projectName = parse(yaml)?.name || "mesh-e2e";
3101
+ await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3102
+ writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
3103
+ const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true }), async () => {
3104
+ await teardownCompose(yaml, meshDir, { removeVolumes: true });
3105
+ clearRunState(meshDir);
3106
+ });
2438
3107
  return status;
2439
3108
  }
2440
3109
 
2441
3110
  // src/core/mesh/runners/runMeshTest.ts
2442
3111
  async function runMeshTest(options = {}) {
2443
- console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
2444
- console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
2445
- const unitStatus = await runMeshTestUnit(options);
2446
- if (unitStatus !== 0) return unitStatus;
2447
- console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
3112
+ console.log(pc14.bold(pc14.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3113
+ console.log(pc14.bold(pc14.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3114
+ const serviceStatus = await runMeshServiceTests(options);
3115
+ if (serviceStatus !== 0) return serviceStatus;
3116
+ console.log(pc14.bold(pc14.blue("[2/2] GLOBAL MESH E2E")));
2448
3117
  return runMeshTestE2e(options);
2449
3118
  }
3119
+ async function runMeshTestUnit(options = {}) {
3120
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test"), validated = validateMeshTestStage(services, meshDir, meshPath, Boolean(options.dryRun));
3121
+ console.log(pc14.bold(pc14.blue("\nEXPLICIT MESH TEST-STAGE (UNIT/ISOLATED)\n")));
3122
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
3123
+ console.log(pc14.cyan(`-> Running isolated unit tests for [${name}]`));
3124
+ const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
3125
+ const app = compiled.compose.services.app;
3126
+ applyTestAppPublications(validated, name, app, compiled.endpoints.app);
3127
+ const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
3128
+ const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
3129
+ const env = svc.meshEnv;
3130
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.keys(svc.effectiveBuild.app.endpoints).some((k) => svc.effectiveBuild.app.endpoints[k]?.primary) ? ["PORT"] : []]) if (key in env) throw new ConfigError({ sourceFile: meshPath, configPath: `services.${name}.env.${key}`, stage: "test", composition: "mesh", reason: "Mesh service env cannot set Builder-owned environment" });
3131
+ const resolvedBuild = resolveMeshAppEnvironmentLayers(name, compiled.appEnvironmentLayers, refCtx, new Set(Object.keys(svc.meshEnv)));
3132
+ for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
3133
+ const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
3134
+ app.environment = { ...resolvedBuild, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
3135
+ const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
3136
+ compiled.compose.name = projectName;
3137
+ const yaml = stringify(compiled.compose);
3138
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3139
+ if (options.dryRun) {
3140
+ console.log(pc14.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
3141
+ continue;
3142
+ }
3143
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
3144
+ writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
3145
+ const status = await runWithCleanup(() => runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true }), async () => {
3146
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
3147
+ clearRunState(svc.absolutePath);
3148
+ });
3149
+ if (status !== 0) return status;
3150
+ }
3151
+ return 0;
3152
+ }
2450
3153
 
2451
3154
  // src/commands/mesh/commands/up/handler.ts
2452
3155
  async function handleMeshUp(rawStage = "dev", options = {}) {
@@ -2457,7 +3160,10 @@ async function handleMeshUp(rawStage = "dev", options = {}) {
2457
3160
  projectDir
2458
3161
  };
2459
3162
  if (["dev", "prod", "test-unit", "test-e2e", "test"].includes(stage) && !options.skipChecks) {
2460
- checkMesh(projectDir, { requireTester: stage === "test-e2e" || stage === "test" });
3163
+ checkMesh(projectDir, {
3164
+ requireTester: stage === "test-e2e" || stage === "test",
3165
+ includeTestStage: stage === "test-unit"
3166
+ });
2461
3167
  }
2462
3168
  switch (stage) {
2463
3169
  case "dev":
@@ -2504,7 +3210,8 @@ Examples:
2504
3210
  $ builder mesh up test-e2e
2505
3211
 
2506
3212
  JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
2507
- The test command runs per-service unit tests before global E2E.`
3213
+ The test command runs each root service test lifecycle (unit, then service E2E) before global E2E.
3214
+ The explicit test-unit stage exercises mesh.json.test overlays only.`
2508
3215
  ).action(
2509
3216
  async (stage = "dev", options = {}) => {
2510
3217
  const exitCode = await handleMeshUp(stage, {
@@ -2532,7 +3239,7 @@ var registerMeshCommand = (program) => {
2532
3239
  registerMeshCheckCommand(meshCmd);
2533
3240
  };
2534
3241
  async function handlePrune(options = {}) {
2535
- console.log(pc22.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3242
+ console.log(pc14.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
2536
3243
  const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
2537
3244
  stdio: "inherit",
2538
3245
  encoding: "utf-8"
@@ -2552,13 +3259,13 @@ async function handlePrune(options = {}) {
2552
3259
  });
2553
3260
  }
2554
3261
  if (options.volumes) {
2555
- console.log(pc22.cyan("\u{1F9F9} Pruning dangling volumes..."));
3262
+ console.log(pc14.cyan("\u{1F9F9} Pruning dangling volumes..."));
2556
3263
  spawnSync("docker", ["volume", "prune", "-f"], {
2557
3264
  stdio: "inherit",
2558
3265
  encoding: "utf-8"
2559
3266
  });
2560
3267
  }
2561
- console.log(pc22.green("\u2705 Docker environment pruned successfully.\n"));
3268
+ console.log(pc14.green("\u2705 Docker environment pruned successfully.\n"));
2562
3269
  return 0;
2563
3270
  }
2564
3271
 
@@ -2576,9 +3283,6 @@ var registerPruneCommand = (cmd) => {
2576
3283
 
2577
3284
  // src/types/index.ts
2578
3285
  var SERVICE_STAGES = ["dev", "prod", "test", "test-unit", "test-e2e"];
2579
- var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2580
-
2581
- // src/commands/service/commands/down/handler.ts
2582
3286
  async function handleServiceDown(rawStage = "dev", options = {}) {
2583
3287
  const projectDir = resolveProjectDir(options.projectDir);
2584
3288
  const stage = (rawStage || "dev").toLowerCase();
@@ -2589,7 +3293,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2589
3293
  );
2590
3294
  }
2591
3295
  console.log(
2592
- pc22.cyan(`
3296
+ pc14.cyan(`
2593
3297
  \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
2594
3298
  );
2595
3299
  if (options.debug) {
@@ -2600,7 +3304,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2600
3304
  else if (stage === "test-e2e") env = "e2e";
2601
3305
  const finalYamlConfig = compileEnvironment(env, projectDir);
2602
3306
  console.log(
2603
- pc22.yellow("Final merged YAML configuration:\n"),
3307
+ pc14.yellow("Final merged YAML configuration:\n"),
2604
3308
  redactYamlSecrets(finalYamlConfig)
2605
3309
  );
2606
3310
  } catch {
@@ -2621,7 +3325,7 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2621
3325
  }
2622
3326
  clearRunState(projectDir);
2623
3327
  console.log(
2624
- pc22.green(`\u2705 Service environment [${stage}] stopped and removed.
3328
+ pc14.green(`\u2705 Service environment [${stage}] stopped and removed.
2625
3329
  `)
2626
3330
  );
2627
3331
  return 0;
@@ -2660,7 +3364,7 @@ Examples:
2660
3364
  };
2661
3365
  var runDev = async (options) => {
2662
3366
  console.log(
2663
- pc22.cyan(
3367
+ pc14.cyan(
2664
3368
  options.full ? `\u{1F680} Starting DEV environment (full / integrated)...` : `\u{1F680} Starting DEV environment...`
2665
3369
  )
2666
3370
  );
@@ -2672,12 +3376,12 @@ var runDev = async (options) => {
2672
3376
  const projectName = parsed?.name || "dev";
2673
3377
  if (options.debug) {
2674
3378
  console.log(
2675
- pc22.yellow("Final merged YAML configuration:\n"),
3379
+ pc14.yellow("Final merged YAML configuration:\n"),
2676
3380
  redactYamlSecrets(finalYamlConfig)
2677
3381
  );
2678
3382
  }
2679
3383
  if (options.dryRun) {
2680
- console.log(pc22.green("Dry run complete. Compose was not started."));
3384
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2681
3385
  return 0;
2682
3386
  }
2683
3387
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -2692,23 +3396,23 @@ var runDev = async (options) => {
2692
3396
  if (options.detach) {
2693
3397
  upArgs.push("-d");
2694
3398
  }
2695
- let status = 0;
2696
- try {
2697
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3399
+ const status = await runWithCleanup(
3400
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
2698
3401
  removeVolumes: false
2699
- });
2700
- } finally {
2701
- if (!options.detach) {
2702
- await teardownCompose(finalYamlConfig, options.projectDir, {
2703
- removeVolumes: false
2704
- });
2705
- clearRunState(options.projectDir);
3402
+ }),
3403
+ async () => {
3404
+ if (!options.detach) {
3405
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3406
+ removeVolumes: false
3407
+ });
3408
+ clearRunState(options.projectDir);
3409
+ }
2706
3410
  }
2707
- }
3411
+ );
2708
3412
  return status;
2709
3413
  };
2710
3414
  var runProd = async (options) => {
2711
- console.log(pc22.cyan(`\u{1F3ED} Starting PROD environment...`));
3415
+ console.log(pc14.cyan(`\u{1F3ED} Starting PROD environment...`));
2712
3416
  const finalYamlConfig = compileEnvironment("prod", options.projectDir, {
2713
3417
  silenceWarnings: options.silenceWarnings
2714
3418
  });
@@ -2716,12 +3420,12 @@ var runProd = async (options) => {
2716
3420
  const projectName = parsed?.name || "prod";
2717
3421
  if (options.debug) {
2718
3422
  console.log(
2719
- pc22.yellow("Final merged YAML configuration:\n"),
3423
+ pc14.yellow("Final merged YAML configuration:\n"),
2720
3424
  redactYamlSecrets(finalYamlConfig)
2721
3425
  );
2722
3426
  }
2723
3427
  if (options.dryRun) {
2724
- console.log(pc22.green("Dry run complete. Compose was not started."));
3428
+ console.log(pc14.green("Dry run complete. Compose was not started."));
2725
3429
  return 0;
2726
3430
  }
2727
3431
  const hostPorts = extractHostPorts(finalYamlConfig);
@@ -2736,186 +3440,20 @@ var runProd = async (options) => {
2736
3440
  if (options.detach) {
2737
3441
  upArgs.push("-d");
2738
3442
  }
2739
- let status = 0;
2740
- try {
2741
- status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3443
+ const status = await runWithCleanup(
3444
+ () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
2742
3445
  removeVolumes: false
2743
- });
2744
- } finally {
2745
- if (!options.detach) {
2746
- await teardownCompose(finalYamlConfig, options.projectDir, {
2747
- removeVolumes: false
2748
- });
2749
- clearRunState(options.projectDir);
3446
+ }),
3447
+ async () => {
3448
+ if (!options.detach) {
3449
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3450
+ removeVolumes: false
3451
+ });
3452
+ clearRunState(options.projectDir);
3453
+ }
2750
3454
  }
2751
- }
2752
- return status;
2753
- };
2754
- var runTestUnit = async (options) => {
2755
- if (!options.skipBanner) {
2756
- console.log(pc22.bold(pc22.blue(`
2757
- ========================================`)));
2758
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2759
- console.log(pc22.bold(pc22.blue(`========================================
2760
- `)));
2761
- }
2762
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2763
- silenceWarnings: options.silenceWarnings
2764
- });
2765
- const parsed = parse(finalYamlConfig);
2766
- const projectName = parsed?.name || "test";
2767
- if (options.debug) {
2768
- console.log(
2769
- pc22.yellow("Final merged YAML configuration:\n"),
2770
- redactYamlSecrets(finalYamlConfig)
2771
- );
2772
- }
2773
- if (options.dryRun) {
2774
- console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2775
- return 0;
2776
- }
2777
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2778
- await teardownCompose(finalYamlConfig, options.projectDir, {
2779
- removeVolumes: true,
2780
- silent: true
2781
- });
2782
- writeRunState(options.projectDir, {
2783
- projectName,
2784
- stage: "test-unit",
2785
- projectDir: options.projectDir
2786
- });
2787
- let status = 0;
2788
- try {
2789
- status = await runCompose(
2790
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2791
- finalYamlConfig,
2792
- options.projectDir,
2793
- { removeVolumes: true }
2794
- );
2795
- } finally {
2796
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2797
- clearRunState(options.projectDir);
2798
- }
2799
- if (status === 0) {
2800
- console.log(pc22.bold(pc22.green(`
2801
- \u2705 Unit tests passed successfully.
2802
- `)));
2803
- } else {
2804
- console.error(pc22.red(`
2805
- \u274C Unit tests failed with exit code ${status}.
2806
- `));
2807
- }
2808
- return status;
2809
- };
2810
- var runTestE2e = async (options) => {
2811
- if (!options.skipBanner) {
2812
- console.log(pc22.bold(pc22.blue(`
2813
- ========================================`)));
2814
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2815
- console.log(pc22.bold(pc22.blue(`========================================
2816
- `)));
2817
- }
2818
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2819
- silenceWarnings: options.silenceWarnings
2820
- });
2821
- const parsed = parse(finalYamlConfig);
2822
- const projectName = parsed?.name || "e2e";
2823
- if (options.debug) {
2824
- console.log(
2825
- pc22.yellow("Final merged YAML configuration:\n"),
2826
- redactYamlSecrets(finalYamlConfig)
2827
- );
2828
- }
2829
- if (options.dryRun) {
2830
- console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2831
- return 0;
2832
- }
2833
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2834
- await teardownCompose(finalYamlConfig, options.projectDir, {
2835
- removeVolumes: true,
2836
- silent: true
2837
- });
2838
- writeRunState(options.projectDir, {
2839
- projectName,
2840
- stage: "test-e2e",
2841
- projectDir: options.projectDir
2842
- });
2843
- let status = 0;
2844
- try {
2845
- status = await runCompose(
2846
- [
2847
- "up",
2848
- "--build",
2849
- "--abort-on-container-exit",
2850
- "--exit-code-from",
2851
- "tester"
2852
- ],
2853
- finalYamlConfig,
2854
- options.projectDir,
2855
- { removeVolumes: true }
2856
- );
2857
- } finally {
2858
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2859
- clearRunState(options.projectDir);
2860
- }
2861
- if (status === 0) {
2862
- console.log(pc22.bold(pc22.green(`
2863
- \u2705 E2E tests passed successfully.
2864
- `)));
2865
- } else {
2866
- console.error(pc22.red(`
2867
- \u274C E2E tests failed with exit code ${status}.
2868
- `));
2869
- }
2870
- return status;
2871
- };
2872
-
2873
- // src/core/runners/runTest.ts
2874
- var runTest = async (options) => {
2875
- console.log(pc22.bold(pc22.blue(`
2876
- ========================================`)));
2877
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
2878
- console.log(pc22.bold(pc22.blue(`========================================
2879
- `)));
2880
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
2881
- if (unitStatus !== 0) {
2882
- console.error(
2883
- pc22.red(
2884
- `
2885
- \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
2886
- `
2887
- )
2888
- );
2889
- return unitStatus;
2890
- }
2891
- console.log(
2892
- pc22.bold(pc22.green(`
2893
- \u2705 [1/2] Unit tests passed successfully.
2894
- `))
2895
3455
  );
2896
- console.log(pc22.bold(pc22.blue(`========================================`)));
2897
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
2898
- console.log(pc22.bold(pc22.blue(`========================================
2899
- `)));
2900
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
2901
- if (e2eStatus !== 0) {
2902
- console.error(
2903
- pc22.red(`
2904
- \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
2905
- `)
2906
- );
2907
- return e2eStatus;
2908
- }
2909
- console.log(pc22.bold(pc22.green(`
2910
- \u2705 [2/2] E2E tests passed successfully.
2911
- `)));
2912
- console.log(
2913
- pc22.bold(
2914
- pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
2915
- `)
2916
- )
2917
- );
2918
- return 0;
3456
+ return status;
2919
3457
  };
2920
3458
 
2921
3459
  // src/commands/service/commands/up/handler.ts
@@ -3048,6 +3586,16 @@ async function handleExportEnv(rawStage, options = {}) {
3048
3586
  throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3049
3587
  }
3050
3588
  const projectDir = resolveProjectDir(options.projectDir);
3589
+ const runtimeInputs = new Set(
3590
+ STAGES.map((s) => canonicalPath(path.join(projectDir, `.env.${s}`)))
3591
+ );
3592
+ const assertSafeDestination = (candidate) => {
3593
+ if (runtimeInputs.has(canonicalPath(candidate))) {
3594
+ throw new ScriptError(
3595
+ `Resolved env export cannot overwrite a runtime .env.<stage> input: ${candidate}`
3596
+ );
3597
+ }
3598
+ };
3051
3599
  const stages = stage === void 0 ? STAGES : [stage];
3052
3600
  const snapshots = stages.map((stage2) => ({
3053
3601
  stage: stage2,
@@ -3065,7 +3613,7 @@ async function handleExportEnv(rawStage, options = {}) {
3065
3613
  const files = [];
3066
3614
  try {
3067
3615
  for (const snapshot of snapshots) {
3068
- let filename = path.join(projectDir, `.env.${snapshot.stage}`);
3616
+ let filename = path.join(projectDir, `.env.${snapshot.stage}.resolved`);
3069
3617
  while (true) {
3070
3618
  let overwrite = false;
3071
3619
  if (existsSync(filename)) {
@@ -3075,9 +3623,11 @@ async function handleExportEnv(rawStage, options = {}) {
3075
3623
  const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3076
3624
  if (!name) continue;
3077
3625
  filename = path.resolve(projectDir, name);
3626
+ assertSafeDestination(filename);
3078
3627
  continue;
3079
3628
  }
3080
3629
  }
3630
+ assertSafeDestination(filename);
3081
3631
  mkdirSync(path.dirname(filename), { recursive: true });
3082
3632
  try {
3083
3633
  writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
@@ -3086,7 +3636,7 @@ async function handleExportEnv(rawStage, options = {}) {
3086
3636
  throw error;
3087
3637
  }
3088
3638
  files.push(filename);
3089
- console.log(pc22.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3639
+ console.log(pc14.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3090
3640
  break;
3091
3641
  }
3092
3642
  }
@@ -3162,10 +3712,10 @@ async function runCli(argv = process.argv) {
3162
3712
  (arg) => arg === "-h" || arg === "--help" || arg === "-V" || arg === "--version"
3163
3713
  );
3164
3714
  if (!isHelpOrVersion && argv.length > 2) {
3165
- console.log(pc22.dim(`builder v${version}`));
3715
+ console.log(pc14.dim(`builder v${version}`));
3166
3716
  }
3167
3717
  if (argv.length <= 2) {
3168
- console.log(pc22.dim(`builder v${version}
3718
+ console.log(pc14.dim(`builder v${version}
3169
3719
  `));
3170
3720
  cli.outputHelp();
3171
3721
  return;
@@ -3188,20 +3738,20 @@ async function runCli(argv = process.argv) {
3188
3738
  if (err instanceof ScriptError) {
3189
3739
  exitCode = err.exitCode;
3190
3740
  const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3191
- console.error(pc22.red(`
3741
+ console.error(pc14.red(`
3192
3742
  ${formatted}
3193
3743
  `));
3194
3744
  if (isVerbose && err.stack) {
3195
- console.error(pc22.dim(err.stack));
3745
+ console.error(pc14.dim(err.stack));
3196
3746
  }
3197
3747
  } else {
3198
3748
  const message = errorMessage(err);
3199
3749
  const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3200
- console.error(pc22.red(`
3750
+ console.error(pc14.red(`
3201
3751
  ${formatted}
3202
3752
  `));
3203
3753
  if (isVerbose && err instanceof Error && err.stack) {
3204
- console.error(pc22.dim(err.stack));
3754
+ console.error(pc14.dim(err.stack));
3205
3755
  }
3206
3756
  }
3207
3757
  if (process.env.VITEST) {