@solid-stack/builder 2.2.0 → 3.0.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 (163) hide show
  1. package/README.md +40 -592
  2. package/dist/bin.js +1715 -1946
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/command.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -1
  6. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  7. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  8. package/dist/commands/prune/command.d.ts.map +1 -1
  9. package/dist/commands/prune/handler.d.ts +3 -1
  10. package/dist/commands/prune/handler.d.ts.map +1 -1
  11. package/dist/commands/service/command.d.ts.map +1 -1
  12. package/dist/commands/service/commands/down/handler.d.ts.map +1 -1
  13. package/dist/commands/service/commands/up/command.d.ts.map +1 -1
  14. package/dist/commands/service/commands/up/handler.d.ts.map +1 -1
  15. package/dist/core/buildSchema.d.ts +217 -952
  16. package/dist/core/buildSchema.d.ts.map +1 -1
  17. package/dist/core/checkers/checkDockerfileContract.d.ts +1 -0
  18. package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
  19. package/dist/core/checkers/checkInfra.d.ts +7 -1
  20. package/dist/core/checkers/checkInfra.d.ts.map +1 -1
  21. package/dist/core/checkers/getDeclaredYamlFiles.d.ts +1 -1
  22. package/dist/core/checkers/getDeclaredYamlFiles.d.ts.map +1 -1
  23. package/dist/core/compileApplicationEnv.d.ts +7 -2
  24. package/dist/core/compileApplicationEnv.d.ts.map +1 -1
  25. package/dist/core/compileEnvironment.d.ts +1 -0
  26. package/dist/core/compileEnvironment.d.ts.map +1 -1
  27. package/dist/core/composeCleanup.d.ts.map +1 -1
  28. package/dist/core/composition/compileGraphComposition.d.ts +16 -0
  29. package/dist/core/composition/compileGraphComposition.d.ts.map +1 -0
  30. package/dist/core/composition/compileServiceComposition.d.ts +2 -13
  31. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  32. package/dist/core/composition/compileTester.d.ts +24 -0
  33. package/dist/core/composition/compileTester.d.ts.map +1 -0
  34. package/dist/core/composition/composeDependsOn.d.ts +8 -4
  35. package/dist/core/composition/composeDependsOn.d.ts.map +1 -1
  36. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -1
  37. package/dist/core/composition/dotenv.d.ts +3 -0
  38. package/dist/core/composition/dotenv.d.ts.map +1 -0
  39. package/dist/core/composition/generatedNames.d.ts.map +1 -1
  40. package/dist/core/composition/inspectRequiredHealth.d.ts +11 -0
  41. package/dist/core/composition/inspectRequiredHealth.d.ts.map +1 -0
  42. package/dist/core/composition/mergeMainOverride.d.ts +3 -0
  43. package/dist/core/composition/mergeMainOverride.d.ts.map +1 -0
  44. package/dist/core/composition/types.d.ts +21 -39
  45. package/dist/core/composition/types.d.ts.map +1 -1
  46. package/dist/core/composition/validateMaterializedComposeBuildInputs.d.ts.map +1 -1
  47. package/dist/core/composition/validateMaterializedComposeFiles.d.ts.map +1 -1
  48. package/dist/core/composition/validateOverrideCompose.d.ts +4 -4
  49. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  50. package/dist/core/composition/validateServiceCompose.d.ts +12 -0
  51. package/dist/core/composition/validateServiceCompose.d.ts.map +1 -0
  52. package/dist/core/config/constants.d.ts +2 -4
  53. package/dist/core/config/constants.d.ts.map +1 -1
  54. package/dist/core/config/endpointProperties.d.ts +2 -2
  55. package/dist/core/config/endpointProperties.d.ts.map +1 -1
  56. package/dist/core/config/executionProfile.d.ts +11 -0
  57. package/dist/core/config/executionProfile.d.ts.map +1 -0
  58. package/dist/core/config/hostPorts.d.ts +7 -1
  59. package/dist/core/config/hostPorts.d.ts.map +1 -1
  60. package/dist/core/config/publication.d.ts +11 -0
  61. package/dist/core/config/publication.d.ts.map +1 -0
  62. package/dist/core/config/references.d.ts +15 -15
  63. package/dist/core/config/references.d.ts.map +1 -1
  64. package/dist/core/config/resolveBuildStage.d.ts.map +1 -1
  65. package/dist/core/config/resolveMeshStage.d.ts +1 -1
  66. package/dist/core/config/resolveMeshStage.d.ts.map +1 -1
  67. package/dist/core/config/serviceGraph.d.ts +10 -0
  68. package/dist/core/config/serviceGraph.d.ts.map +1 -0
  69. package/dist/core/config/stageMerge.d.ts +2 -3
  70. package/dist/core/config/stageMerge.d.ts.map +1 -1
  71. package/dist/core/config/types.d.ts +104 -27
  72. package/dist/core/config/types.d.ts.map +1 -1
  73. package/dist/core/mesh/applyMeshExtends.d.ts +3 -0
  74. package/dist/core/mesh/applyMeshExtends.d.ts.map +1 -0
  75. package/dist/core/mesh/checkers/checkMesh.d.ts +2 -0
  76. package/dist/core/mesh/checkers/checkMesh.d.ts.map +1 -1
  77. package/dist/core/mesh/checkers/checkMeshServices.d.ts +2 -1
  78. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  79. package/dist/core/mesh/checkers/checkMeshTester.d.ts +1 -3
  80. package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
  81. package/dist/core/mesh/compileMeshComposition.d.ts +6 -0
  82. package/dist/core/mesh/compileMeshComposition.d.ts.map +1 -0
  83. package/dist/core/mesh/compileMeshEnvironment.d.ts +3 -2
  84. package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
  85. package/dist/core/mesh/loadMeshSources.d.ts +4 -0
  86. package/dist/core/mesh/loadMeshSources.d.ts.map +1 -0
  87. package/dist/core/mesh/meshSchema.d.ts +41 -225
  88. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  89. package/dist/core/mesh/runners/runMeshDev.d.ts +1 -1
  90. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  91. package/dist/core/mesh/runners/runMeshProd.d.ts +1 -1
  92. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  93. package/dist/core/mesh/runners/runMeshServiceTests.d.ts +2 -1
  94. package/dist/core/mesh/runners/runMeshServiceTests.d.ts.map +1 -1
  95. package/dist/core/mesh/runners/runMeshTest.d.ts +7 -1
  96. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  97. package/dist/core/mesh/runners/runMeshTestE2e.d.ts +2 -1
  98. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  99. package/dist/core/mesh/types.d.ts +18 -24
  100. package/dist/core/mesh/types.d.ts.map +1 -1
  101. package/dist/core/runCompose.d.ts +4 -0
  102. package/dist/core/runCompose.d.ts.map +1 -1
  103. package/dist/core/runners/runDev.d.ts.map +1 -1
  104. package/dist/core/runners/runFiniteTester.d.ts +12 -2
  105. package/dist/core/runners/runFiniteTester.d.ts.map +1 -1
  106. package/dist/core/runners/runLongLived.d.ts +15 -0
  107. package/dist/core/runners/runLongLived.d.ts.map +1 -0
  108. package/dist/core/runners/runProd.d.ts.map +1 -1
  109. package/dist/core/runners/runTest.d.ts +7 -1
  110. package/dist/core/runners/runTest.d.ts.map +1 -1
  111. package/dist/core/runners/runTestE2e.d.ts +9 -1
  112. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  113. package/dist/core/runners/runTestUnit.d.ts +9 -1
  114. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  115. package/dist/index.js +1718 -1947
  116. package/dist/index.js.map +1 -1
  117. package/dist/templates/docker/docker-compose.base.yml +1 -1
  118. package/dist/templates/docker/docker-compose.dev.yml +1 -4
  119. package/dist/templates/docker/docker-compose.e2e.yml +1 -6
  120. package/dist/templates/docker/docker-compose.prod.yml +1 -1
  121. package/dist/templates/docker/docker-compose.test.yml +1 -1
  122. package/dist/templates/policy/dockerfile/dockerfile.rego +3 -6
  123. package/dist/types/index.d.ts +51 -32
  124. package/dist/types/index.d.ts.map +1 -1
  125. package/dist/utils/runState.d.ts +9 -1
  126. package/dist/utils/runState.d.ts.map +1 -1
  127. package/package.json +11 -6
  128. package/schemas/build-schema.json +868 -507
  129. package/schemas/mesh-schema.json +947 -384
  130. package/templates/docker/docker-compose.base.yml +1 -1
  131. package/templates/docker/docker-compose.dev.yml +1 -4
  132. package/templates/docker/docker-compose.e2e.yml +1 -6
  133. package/templates/docker/docker-compose.prod.yml +1 -1
  134. package/templates/docker/docker-compose.test.yml +1 -1
  135. package/templates/policy/dockerfile/dockerfile.rego +3 -6
  136. package/dist/core/composition/dependencyLifecycle.d.ts +0 -4
  137. package/dist/core/composition/dependencyLifecycle.d.ts.map +0 -1
  138. package/dist/core/composition/mergeAppOverride.d.ts +0 -3
  139. package/dist/core/composition/mergeAppOverride.d.ts.map +0 -1
  140. package/dist/core/composition/selectAppEnvironmentEntries.d.ts +0 -3
  141. package/dist/core/composition/selectAppEnvironmentEntries.d.ts.map +0 -1
  142. package/dist/core/composition/serviceEndpoints.d.ts +0 -5
  143. package/dist/core/composition/serviceEndpoints.d.ts.map +0 -1
  144. package/dist/core/composition/validateDependencyCompose.d.ts +0 -8
  145. package/dist/core/composition/validateDependencyCompose.d.ts.map +0 -1
  146. package/dist/core/mesh/v2/compileMeshComposition.d.ts +0 -6
  147. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +0 -1
  148. package/dist/core/mesh/v2/compileMeshTester.d.ts +0 -15
  149. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +0 -1
  150. package/dist/core/mesh/v2/lifecycle.d.ts +0 -10
  151. package/dist/core/mesh/v2/lifecycle.d.ts.map +0 -1
  152. package/dist/core/mesh/v2/loadMeshServices.d.ts +0 -5
  153. package/dist/core/mesh/v2/loadMeshServices.d.ts.map +0 -1
  154. package/dist/core/mesh/v2/meshReferences.d.ts +0 -17
  155. package/dist/core/mesh/v2/meshReferences.d.ts.map +0 -1
  156. package/dist/core/mesh/v2/publication.d.ts +0 -3
  157. package/dist/core/mesh/v2/publication.d.ts.map +0 -1
  158. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts +0 -4
  159. package/dist/core/mesh/v2/resolveMeshAppEnvironment.d.ts.map +0 -1
  160. package/dist/core/mesh/v2/substitution.d.ts +0 -5
  161. package/dist/core/mesh/v2/substitution.d.ts.map +0 -1
  162. package/dist/core/mesh/v2/types.d.ts +0 -40
  163. package/dist/core/mesh/v2/types.d.ts.map +0 -1
package/dist/bin.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Argument } from 'commander';
3
- import pc15 from 'picocolors';
3
+ import pc9 from 'picocolors';
4
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
- import { parseAllDocuments, parse, stringify } from 'yaml';
9
+ import { stringify, parse, parseAllDocuments } from 'yaml';
10
10
  import crypto, { createHash } from 'crypto';
11
- import net, { isIP } from 'net';
12
11
  import os from 'os';
12
+ import net, { isIP } from 'net';
13
13
  import { createInterface } from 'readline/promises';
14
14
  import { createRequire } from 'module';
15
15
 
@@ -45,28 +45,45 @@ var ConfigError = class extends ScriptError {
45
45
  // src/core/config/constants.ts
46
46
  var BUILDER_IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*$/;
47
47
  var ENDPOINT_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
48
- var DEPENDENCY_REFERENCE_PATTERN = /^dependencies\.([a-z][a-z0-9-]*)$/;
49
48
  var ENDPOINT_PROPERTIES = ["network_host", "network_port", "network_address", "network_url", "public_host", "public_port", "public_address", "public_url"];
50
- var PUBLIC_ENDPOINT_PROPERTIES = /* @__PURE__ */ new Set(["public_host", "public_port", "public_address", "public_url"]);
51
- var RESERVED_MESH_SERVICE_NAMES = /* @__PURE__ */ new Set(["app", "dependencies", "tester", "services", "dev", "prod", "test", "e2e"]);
52
49
  var PUBLIC_HOST = "127.0.0.1";
53
- var AUTO_PORT_CACHE_VERSION = 1;
54
- var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v2.json";
50
+ var AUTO_PORT_CACHE_VERSION = 3;
51
+ var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v3.json";
55
52
  var AUTO_PORT_SCAN_START = 2e4;
56
53
 
57
54
  // src/core/buildSchema.ts
58
- var identifierSchema = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
59
- var envSchema = z.record(z.string(), z.string());
60
- var portSchema = z.number().int().min(1).max(65535);
61
- var publicPortSchema = z.union([portSchema, z.literal("AUTO")]);
62
- var appEndpointSchema = z.object({ port: portSchema, publicPort: publicPortSchema.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
63
- var dependencyEndpointSchema = appEndpointSchema.extend({ service: z.string().min(1) }).strict();
64
- var dependencySchema = z.object({ compose: z.string().min(1), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
65
- var appStageEndpointSchema = appEndpointSchema.partial().strict();
66
- var dependencyStageEndpointSchema = dependencyEndpointSchema.partial().strict();
67
- var dependencyStageSchema = z.object({ compose: z.string().min(1).optional(), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyStageEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
68
- var buildStageSchema = z.object({ "override-compose": z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appStageEndpointSchema).optional() }).strict().optional(), dependencies: z.record(identifierSchema, dependencyStageSchema).optional() }).strict();
69
- var buildJsonSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), dockerfile: z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appEndpointSchema).optional() }).strict(), dependencies: z.record(identifierSchema, dependencySchema).optional(), tester: z.object({ env: envSchema.optional() }).strict().optional(), dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
55
+ var identifier = z.string().regex(BUILDER_IDENTIFIER_PATTERN);
56
+ var nonblank = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
57
+ var env = z.record(z.string(), z.string());
58
+ var port = z.number().int().min(1).max(65535);
59
+ var publicPort = z.union([port, z.literal("AUTO")]);
60
+ var requisite = z.enum(["requirement", "dependency", "prerequisite"]);
61
+ var requisites = z.record(identifier, requisite);
62
+ var requisiteOverlay = z.record(identifier, z.union([requisite, z.literal(false)]));
63
+ var mainEndpointSchema = z.object({ port, publicPort: publicPort.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
64
+ var serviceEndpointSchema = mainEndpointSchema.extend({ service: nonblank }).strict();
65
+ var mainServiceSchema = z.object({ env: env.optional(), endpoints: z.record(identifier, mainEndpointSchema).optional(), requisites: requisites.optional(), "override-compose": nonblank.optional() }).strict();
66
+ var testerServiceSchema = z.object({ compose: nonblank, service: nonblank, env: env.optional() }).strict();
67
+ var ordinaryServiceSchema = z.object({ compose: nonblank, service: nonblank.optional(), env: env.optional(), endpoints: z.record(identifier, serviceEndpointSchema).optional(), requisites: requisites.optional() }).strict().refine((value) => Boolean(value.service) || Boolean(value.endpoints && Object.keys(value.endpoints).length), "endpoint-less service requires service");
68
+ var mainOverlaySchema = z.object({ env: env.optional(), endpoints: z.record(identifier, mainEndpointSchema.partial().strict()).optional(), requisites: requisiteOverlay.optional(), "override-compose": nonblank.optional() }).strict();
69
+ var testerOverlaySchema = testerServiceSchema.partial().strict();
70
+ var ordinaryOverlaySchema = z.object({ compose: nonblank.optional(), service: nonblank.optional(), env: env.optional(), endpoints: z.record(identifier, serviceEndpointSchema.partial().strict()).optional(), requisites: requisiteOverlay.optional() }).strict();
71
+ var buildServicesSchema = z.record(identifier, z.unknown()).superRefine((value, context) => {
72
+ for (const required of ["main", "tester"]) if (!(required in value)) context.addIssue({ code: "custom", path: [required], message: `${required} is required` });
73
+ for (const [key, entry] of Object.entries(value)) {
74
+ const schema = key === "main" ? mainServiceSchema : key === "tester" ? testerServiceSchema : ordinaryServiceSchema;
75
+ const parsed = schema.safeParse(entry);
76
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
77
+ }
78
+ });
79
+ var buildStageSchema = z.object({ services: z.record(identifier, z.unknown()).superRefine((value, context) => {
80
+ for (const [key, entry] of Object.entries(value)) {
81
+ const schema = key === "main" ? mainOverlaySchema : key === "tester" ? testerOverlaySchema : ordinaryOverlaySchema;
82
+ const parsed = schema.safeParse(entry);
83
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
84
+ }
85
+ }).optional() }).strict();
86
+ var buildJsonSchema = z.object({ $schema: z.string().optional(), name: nonblank, services: buildServicesSchema, dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
70
87
 
71
88
  // src/utils/errorMessage.ts
72
89
  function errorMessage(err) {
@@ -147,8 +164,8 @@ function resolveInsideProject(projectDir, relativePath, context) {
147
164
  if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
148
165
  return resolved;
149
166
  }
150
- function resolveApplicationDockerfile(projectDir, relativePath = "Dockerfile", stage) {
151
- const context = { sourceFile: path.join(projectDir, "build.json"), configPath: "dockerfile", ...stage ? { stage } : {} };
167
+ function resolveApplicationDockerfile(projectDir, relativePath = "Dockerfile", stage2) {
168
+ const context = { sourceFile: path.join(projectDir, "build.json"), configPath: "dockerfile", ...stage2 ? { stage: stage2 } : {} };
152
169
  const resolved = resolveInsideProject(projectDir, relativePath, context);
153
170
  if (!existsSync(resolved) || !statSync(resolved).isFile()) throw new ConfigError({ ...context, value: relativePath, reason: `Application Dockerfile not found or not a regular file: ${resolved}` });
154
171
  return resolved;
@@ -172,7 +189,7 @@ function runStep(executable, args, projectDir, ctx) {
172
189
  if (stderr) process.stderr.write(stderr);
173
190
  if (result.error || result.status !== 0) {
174
191
  console.error("\n" + "=".repeat(60));
175
- console.error(pc15.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
192
+ console.error(pc9.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
176
193
  console.error("=".repeat(60));
177
194
  console.error(`Failed Step : ${ctx.stepName}`);
178
195
  if (ctx.targetFile) {
@@ -196,10 +213,10 @@ ${ctx.detail}`);
196
213
 
197
214
  // src/core/checkers/checkDockerfile.ts
198
215
  function checkDockerfile(buildJson, projectDir) {
199
- const dockerfileRel = buildJson.dockerfile || "Dockerfile";
216
+ const dockerfileRel = "Dockerfile";
200
217
  const dockerfilePath = resolveApplicationDockerfile(projectDir, dockerfileRel);
201
218
  const content = readFileSync(dockerfilePath, "utf-8");
202
- console.log(pc15.cyan(`
219
+ console.log(pc9.cyan(`
203
220
  \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
204
221
  runStep(
205
222
  "docker",
@@ -262,128 +279,67 @@ function getDockerfilePolicyDir() {
262
279
  if (!fs.existsSync(path.join(policyDir, "dockerfile.rego"))) throw new ScriptError(`Builder Dockerfile policy not found: ${policyDir}`);
263
280
  return policyDir;
264
281
  }
265
-
266
- // src/core/checkers/checkDockerfileContract.ts
282
+ function assertMainDockerfileContract(projectDir, activeStage) {
283
+ const file = resolveApplicationDockerfile(projectDir, "Dockerfile", activeStage);
284
+ const lines = readFileSync(file, "utf8").replace(/\\\r?\n\s*/g, " ").split(/\r?\n/);
285
+ const stages = /* @__PURE__ */ new Map();
286
+ let current;
287
+ for (const raw of lines) {
288
+ const line = raw.trim();
289
+ if (!line || line.startsWith("#")) continue;
290
+ const from = /^FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/i.exec(line);
291
+ if (from) {
292
+ current = { name: (from[2] ?? `__${stages.size}`).toLowerCase(), parent: from[1].toLowerCase() };
293
+ stages.set(current.name, current);
294
+ continue;
295
+ }
296
+ if (!current) continue;
297
+ const instruction = /^(CMD|ENTRYPOINT|HEALTHCHECK)\s+(.+)$/i.exec(line);
298
+ if (instruction) {
299
+ const key = instruction[1].toLowerCase();
300
+ if (key === "cmd") current.command = instruction[2];
301
+ else if (key === "entrypoint") current.entrypoint = instruction[2];
302
+ else current.health = instruction[2];
303
+ }
304
+ }
305
+ const fail4 = (reason) => {
306
+ throw new ConfigError({ sourceFile: file, configPath: `Dockerfile.${activeStage}`, stage: activeStage, composition: "service", reason });
307
+ };
308
+ for (const name of ["dev", "test", "prod"]) if (!stages.has(name)) fail4(`Missing required Dockerfile target ${name}`);
309
+ const visited = /* @__PURE__ */ new Set();
310
+ let cursor = stages.get(activeStage), runtime = false, health;
311
+ let effectiveCmd, effectiveEntrypoint;
312
+ while (cursor) {
313
+ if (visited.has(cursor.name)) fail4(`Dockerfile stage inheritance cycle at ${cursor.name}`);
314
+ visited.add(cursor.name);
315
+ runtime ||= Boolean(cursor.command || cursor.entrypoint);
316
+ if (effectiveCmd === void 0 && cursor.command !== void 0) effectiveCmd = cursor.command;
317
+ if (effectiveEntrypoint === void 0 && cursor.entrypoint !== void 0) effectiveEntrypoint = cursor.entrypoint;
318
+ if (health === void 0 && cursor.health !== void 0) health = cursor.health;
319
+ cursor = stages.get(cursor.parent);
320
+ }
321
+ if (!runtime) fail4(`${activeStage} requires an effective CMD or ENTRYPOINT`);
322
+ if (activeStage !== "test" && (!health || /^NONE$/i.test(health.trim()))) fail4(`${activeStage} requires a valid healthcheck`);
323
+ if (activeStage === "dev" && [effectiveEntrypoint, effectiveCmd].some((instruction) => instruction !== void 0 && /(?:nohup|&\s*(?:["']?\s*\]|\s*$)|--daemon)/i.test(instruction))) fail4("dev runtime must remain in foreground");
324
+ }
267
325
  function checkDockerfileContract(build, projectDir) {
268
326
  const root = resolveProjectDir(projectDir);
269
- const relative = build.dockerfile ?? "Dockerfile";
327
+ const relative = "Dockerfile";
270
328
  resolveApplicationDockerfile(root, relative);
271
329
  const policyDir = getDockerfilePolicyDir();
272
- console.log(pc15.cyan(`
330
+ console.log(pc9.cyan(`
273
331
  \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
274
332
  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 });
275
333
  }
276
- function loadComposeDocument(absolutePath, context) {
277
- const fail = (reason, value) => {
278
- throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
279
- };
280
- if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) fail("Compose file does not exist or is not a regular file");
281
- let text = "";
282
- try {
283
- text = readFileSync(absolutePath, "utf8");
284
- } catch (e) {
285
- fail(`Failed to read Compose file: ${String(e)}`);
286
- }
287
- let docs = [];
288
- try {
289
- docs = parseAllDocuments(text, { prettyErrors: true });
290
- } catch (e) {
291
- fail(`Invalid Compose YAML: ${String(e)}`);
292
- }
293
- if (docs.length !== 1) fail("Compose file must contain exactly one YAML document");
294
- const errors = docs[0].errors;
295
- if (errors.length) fail(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
296
- let parsed;
297
- try {
298
- parsed = parse(text);
299
- } catch (e) {
300
- fail(`Invalid Compose YAML: ${String(e)}`);
301
- }
302
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail("Compose root must be an object");
303
- return parsed;
304
- }
305
- function getDeclaredYamlFiles(build, projectDir) {
306
- const files = [];
307
- const seen = /* @__PURE__ */ new Set();
308
- const add = (relativePath, source, kind, stage) => {
309
- const absolutePath = path.resolve(projectDir, relativePath);
310
- if (seen.has(absolutePath)) return;
311
- seen.add(absolutePath);
312
- files.push({ relativePath, absolutePath, source, kind, ...stage ? { stage } : {} });
313
- };
314
- for (const [name, dep] of Object.entries(build.dependencies ?? {})) add(dep.compose, `dependencies.${name}.compose`, "dependency-compose");
315
- for (const stage of ["dev", "prod", "test", "e2e"]) {
316
- const overlay = build[stage];
317
- if (overlay?.["override-compose"]) add(overlay["override-compose"], `${stage}.override-compose`, "override-compose", stage);
318
- for (const [name, dep] of Object.entries(overlay?.dependencies ?? {})) if (dep.compose) add(dep.compose, `${stage}.dependencies.${name}.compose`, "dependency-compose", stage);
319
- }
320
- return files;
321
- }
322
-
323
- // src/core/checkers/checkYamlFiles.ts
324
- function checkYamlFiles(build, projectDir) {
325
- const root = resolveProjectDir(projectDir);
326
- const files = getDeclaredYamlFiles(build, root);
327
- if (files.length) console.log(pc15.cyan(`
328
- \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
329
- for (const file of files) {
330
- const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
331
- loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
332
- }
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
- };
362
-
363
- // src/core/composition/composeNetworks.ts
364
- function normalizeNetworks(value) {
365
- if (Array.isArray(value)) return Object.fromEntries(value.filter((name) => typeof name === "string").map((name) => [name, null]));
366
- return value && typeof value === "object" ? { ...value } : {};
367
- }
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
334
 
379
335
  // src/core/config/endpointProperties.ts
380
336
  function resolveEndpointProperty(endpoint, property, context) {
381
337
  const reference = context.referencedObject ?? endpoint.logicalPath;
382
338
  const published = () => {
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` });
339
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, referencedObject: reference, reason: `endpoint is not published; ${property} requires publicPort capability and, in a mesh, a publish selector` });
384
340
  };
385
341
  const scheme = () => {
386
- if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires an endpoint scheme` });
342
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: reference, reason: `Endpoint property ${property} requires scheme` });
387
343
  return endpoint.scheme;
388
344
  };
389
345
  switch (property) {
@@ -413,172 +369,193 @@ function assertPrimaryEndpointInvariant(endpoints, context) {
413
369
  const primaries = Object.entries(endpoints).filter(([, e]) => e.primary === true);
414
370
  if (Object.keys(endpoints).length && primaries.length !== 1) throw new ConfigError({ ...context, value: primaries.map(([n]) => n), reason: `Expected exactly one primary endpoint; found ${primaries.length}` });
415
371
  }
416
- function getPrimaryEndpoint(endpoints) {
417
- return Object.entries(endpoints).find(([, endpoint]) => endpoint.primary === true);
418
- }
419
-
420
- // src/core/config/lifecycleGraph.ts
421
- function assertAcyclicGraph(graph, context) {
422
- const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
423
- const visit = (node) => {
424
- if (visiting.has(node)) {
425
- const start = stack.indexOf(node);
426
- const cycle = [...stack.slice(start), node];
427
- throw new ConfigError({ ...context, configPath: "dependsOn", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
428
- }
429
- if (visited.has(node)) return;
430
- visiting.add(node);
431
- stack.push(node);
432
- for (const next of graph.get(node) ?? []) visit(next);
433
- stack.pop();
434
- visiting.delete(node);
435
- visited.add(node);
436
- };
437
- for (const node of graph.keys()) visit(node);
438
- }
439
372
 
440
373
  // 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"];
374
+ function stageOverlayChain(stage2) {
375
+ return stage2 === "e2e" ? ["prod", "e2e"] : [stage2];
376
+ }
377
+ var plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
378
+ function mergeEffectiveObject(base, patch) {
379
+ if (plain(base) && plain(patch)) {
380
+ const result = structuredClone(base);
381
+ for (const [key, value] of Object.entries(patch)) result[key] = key in result ? mergeEffectiveObject(result[key], value) : structuredClone(value);
382
+ return result;
451
383
  }
384
+ return structuredClone(patch);
452
385
  }
453
- function unionStable(base = [], overlay = []) {
454
- return [.../* @__PURE__ */ new Set([...base, ...overlay])];
455
- }
456
- function mergeStringMap(base, overlay) {
457
- return { ...base ?? {}, ...overlay ?? {} };
386
+ function applyServiceOverlay(base, patch) {
387
+ const without = { ...patch };
388
+ delete without.requisites;
389
+ const result = mergeEffectiveObject(base, without);
390
+ if (patch.requisites) {
391
+ const edges = { ...base.requisites ?? {} };
392
+ for (const [target, kind] of Object.entries(patch.requisites)) {
393
+ if (kind === false) delete edges[target];
394
+ else edges[target] = kind;
395
+ }
396
+ result.requisites = edges;
397
+ }
398
+ return result;
458
399
  }
459
400
 
460
401
  // src/core/config/resolveBuildStage.ts
461
- function resolveBuildStage(build, stage, sourceFile) {
462
- const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
463
- const appEnv = { ...build.app.env ?? {} };
464
- const appEndpoints = structuredClone(build.app.endpoints ?? {});
465
- const dependencies = {};
466
- for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
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 };
486
- delete effective.dev;
487
- delete effective.prod;
488
- delete effective.test;
489
- delete effective.e2e;
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");
491
- assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
492
- const graph = /* @__PURE__ */ new Map();
493
- for (const [name, dep] of Object.entries(dependencies)) {
494
- if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
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");
496
- assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
497
- const node = `dependencies.${name}`;
498
- graph.set(node, /* @__PURE__ */ new Set());
499
- for (const ref of dep.dependsOn) {
500
- const match = DEPENDENCY_REFERENCE_PATTERN.exec(ref);
501
- if (!match) throw context(`dependencies.${name}.dependsOn`, ref, "Expected dependencies.<name> lifecycle reference", ref);
502
- const targetName = match[1];
503
- if (targetName === name) throw context(`dependencies.${name}.dependsOn`, ref, "Dependency cannot depend on itself", ref);
504
- const target = dependencies[targetName];
505
- if (!target) throw context(`dependencies.${name}.dependsOn`, ref, "Unknown dependency", ref);
506
- if (!Object.keys(target.endpoints).length) throw context(`dependencies.${name}.dependsOn`, ref, "Lifecycle target is inert and has no endpoints", ref);
507
- graph.get(node).add(`dependencies.${targetName}`);
508
- }
509
- }
510
- assertAcyclicGraph(graph, { sourceFile, stage, composition: "service" });
511
- return effective;
402
+ var originFor = (sourceFile, configPath, layer) => ({ sourceFile, configPath, projectDir: path.dirname(sourceFile), scope: "build", layer });
403
+ var fail = (sourceFile, stage2, configPath, reason, value) => {
404
+ throw new ConfigError({ sourceFile, stage: stage2, composition: "service", configPath, reason, value });
405
+ };
406
+ function resolveBuildStage(build, stage2, sourceFile) {
407
+ const services2 = structuredClone(build.services);
408
+ const origins = /* @__PURE__ */ new Map();
409
+ const envOrigins = /* @__PURE__ */ new Map();
410
+ const requisiteOrigins = /* @__PURE__ */ new Map();
411
+ const layers = [];
412
+ const deletedRequisiteTargets = [];
413
+ const record = (name, entry, layer) => {
414
+ const where = layer === "base" ? `services.${name}` : `${layer}.services.${name}`;
415
+ const origin = originFor(sourceFile, where, layer);
416
+ origins.set(name, origin);
417
+ const env2 = envOrigins.get(name) ?? /* @__PURE__ */ new Map();
418
+ for (const key of Object.keys(entry.env ?? {})) env2.set(key, originFor(sourceFile, `${where}.env.${key}`, layer));
419
+ envOrigins.set(name, env2);
420
+ const edges = requisiteOrigins.get(name) ?? /* @__PURE__ */ new Map();
421
+ for (const [key, value] of Object.entries(entry.requisites ?? {})) {
422
+ if (value === false) edges.delete(key);
423
+ else edges.set(key, originFor(sourceFile, `${where}.requisites.${key}`, layer));
424
+ }
425
+ requisiteOrigins.set(name, edges);
426
+ };
427
+ for (const [name, value] of Object.entries(services2).sort(([a], [b]) => a.localeCompare(b))) record(name, value, "base");
428
+ layers.push({ stage: "base", services: structuredClone(services2), origin: originFor(sourceFile, "services", "base") });
429
+ for (const overlayStage of stageOverlayChain(stage2)) {
430
+ const patches = build[overlayStage]?.services ?? {};
431
+ for (const [name, patch] of Object.entries(patches).sort(([a], [b]) => a.localeCompare(b))) {
432
+ const current = services2[name];
433
+ const where = `${overlayStage}.services.${name}`;
434
+ if (!current && (name === "main" || name === "tester")) fail(sourceFile, stage2, where, "Required special service is missing from base");
435
+ if (current && patch.compose !== void 0 && patch.compose !== current.compose) fail(sourceFile, stage2, `${where}.compose`, `compose is immutable; previous declaration ${origins.get(name)?.configPath}.compose, attempted ${where}.compose`, patch.compose);
436
+ if (!current && name !== "main" && name !== "tester" && (typeof patch.compose !== "string" || !patch.compose.trim())) fail(sourceFile, stage2, `${where}.compose`, "Stage-introduced service requires a complete compose declaration");
437
+ services2[name] = current ? applyServiceOverlay(current, patch) : structuredClone(patch);
438
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) if (kind === false) deletedRequisiteTargets.push({ target, path: `${where}.requisites.${target}` });
439
+ record(name, patch, overlayStage);
440
+ }
441
+ layers.push({ stage: overlayStage, services: structuredClone(patches), origin: originFor(sourceFile, `${overlayStage}.services`, overlayStage) });
442
+ }
443
+ for (const deleted of deletedRequisiteTargets) if (!(deleted.target in services2)) fail(sourceFile, stage2, deleted.path, "Unknown requisite target", deleted.target);
444
+ for (const [name, value] of Object.entries(services2)) {
445
+ const originPath = origins.get(name)?.configPath ?? `services.${name}`;
446
+ if (name === "tester") {
447
+ if (typeof value.compose !== "string" || typeof value.service !== "string") fail(sourceFile, stage2, originPath, "Effective tester requires compose and service");
448
+ continue;
449
+ }
450
+ const endpoints = value.endpoints ?? {};
451
+ for (const [endpointName, endpoint] of Object.entries(endpoints)) {
452
+ if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535) fail(sourceFile, stage2, `${originPath}.endpoints.${endpointName}.port`, "Effective endpoint requires port in 1..65535", endpoint.port);
453
+ if (name !== "main" && (typeof endpoint.service !== "string" || !endpoint.service.trim())) fail(sourceFile, stage2, `${originPath}.endpoints.${endpointName}.service`, "Effective ordinary endpoint requires service");
454
+ }
455
+ assertPrimaryEndpointInvariant(endpoints, { sourceFile, stage: stage2, configPath: `${originPath}.endpoints` });
456
+ if (name !== "main" && (typeof value.compose !== "string" || !value.compose.trim())) fail(sourceFile, stage2, `${originPath}.compose`, "Effective ordinary service requires compose");
457
+ if (name !== "main" && Object.keys(endpoints).length === 0 && (typeof value.service !== "string" || !value.service.trim())) fail(sourceFile, stage2, `${originPath}.service`, "endpoint-less service requires service");
458
+ if (name !== "main" && Object.keys(endpoints).length > 0 && typeof value.service === "string") {
459
+ const primary = Object.values(endpoints).find((endpoint) => endpoint.primary);
460
+ if (primary?.service && value.service !== primary.service) fail(sourceFile, stage2, `${originPath}.service`, "top-level service must equal primary endpoint owner", value.service);
461
+ }
462
+ value.env ??= {};
463
+ value.endpoints ??= {};
464
+ value.requisites ??= {};
465
+ value.kind = name === "main" ? "main" : "ordinary";
466
+ }
467
+ return { name: build.name, services: services2, layers, origins, envOrigins, requisiteOrigins, sourceFile, projectDir: path.dirname(sourceFile) };
512
468
  }
513
-
514
- // src/core/config/references.ts
515
- var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
516
- var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
517
- var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
518
- var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
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` });
469
+ function normalizeProjectName(name, projectDir) {
470
+ let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
471
+ if (!normalized || !/^[a-z0-9]/.test(normalized)) {
472
+ if (projectDir) {
473
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
474
+ return `project-${hash}`;
475
+ }
476
+ return "project";
477
+ }
478
+ return normalized;
526
479
  }
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" });
480
+ function deriveProjectName(name, stage2, projectDir, options = {}) {
481
+ let base = normalizeProjectName(name, projectDir);
482
+ if (options.hash && projectDir) {
483
+ const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
484
+ base = `${base}-${hash}`;
485
+ }
486
+ if (!stage2) {
487
+ return base;
488
+ }
489
+ const s = stage2.toLowerCase();
490
+ if (s === "dev") {
491
+ return base;
492
+ }
493
+ if (s === "prod") {
494
+ return `${base}-prod`;
495
+ }
496
+ if (s === "test" || s === "test-unit") {
497
+ return `${base}-test`;
498
+ }
499
+ if (s === "e2e" || s === "test-e2e") {
500
+ return `${base}-e2e`;
530
501
  }
531
- return ref;
502
+ return `${base}-${s}`;
532
503
  }
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;
504
+ var EXEC_MODE_KEY = "EXEC_MODE";
505
+ var INFRA_MODE_KEY = "INFRA_MODE";
506
+ var PORT_KEY = "PORT";
507
+ function assertNoBuilderOwnedEnvKeys(env2, keys, context) {
508
+ for (const key of keys) {
509
+ if (!(key in env2)) continue;
510
+ throw new ConfigError({ sourceFile: context.sourceFile, configPath: `${context.configPath}.${key}`, stage: context.stage, composition: context.composition, value: env2[key], reason: `User-controlled environment cannot set Builder-owned key "${key}"` });
511
+ }
538
512
  }
539
- function interpolateBuilderReferences(value, scope, resolve, context) {
540
- const sentinel = "\0DOLLAR\0";
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
- }
513
+ function assertDotenvDoesNotDefineKeys(filePath, keys, context) {
514
+ if (!fs.existsSync(filePath)) return;
515
+ const forbidden = new Set(keys), lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
516
+ for (let index = 0; index < lines.length; index += 1) {
517
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[:=]/.exec(lines[index]);
518
+ if (!match) continue;
519
+ const key = match[1];
520
+ if (!forbidden.has(key)) continue;
521
+ 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}"` });
554
522
  }
555
523
  }
556
524
 
525
+ // src/core/config/executionProfile.ts
526
+ function executionProfile(stage2, composition, full = false) {
527
+ if (composition === "mesh" && stage2 === "test") throw new Error("Mesh test is a workflow, not a configuration stage");
528
+ if (stage2 === "dev") return { configStage: stage2, envStage: stage2, mainTarget: "dev", execMode: "dev", infraMode: composition === "mesh" || full ? "integrated" : "isolated", attachTester: false };
529
+ if (stage2 === "test") return { configStage: stage2, envStage: stage2, mainTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
530
+ return { configStage: stage2, envStage: stage2, mainTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: stage2 === "e2e" };
531
+ }
532
+
557
533
  // src/errors/PortConflictError.ts
558
534
  var PortConflictError = class extends ConfigError {
559
535
  port;
560
536
  firstOwner;
561
537
  secondOwner;
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.` });
538
+ constructor(port2, firstOwner, secondOwner, stage2, sourceFile = "Builder effective composition", composition) {
539
+ super({ sourceFile, configPath: secondOwner, value: port2, stage: stage2, ...composition ? { composition } : {}, referencedObject: firstOwner, reason: `Host port ${port2} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
564
540
  this.name = "PortConflictError";
565
- this.port = port;
541
+ this.port = port2;
566
542
  this.firstOwner = firstOwner;
567
543
  this.secondOwner = secondOwner;
568
544
  }
569
545
  };
570
546
 
571
547
  // src/core/config/hostPorts.ts
572
- function isHostPortAvailableSync(port) {
573
- const script = `const net=require('node:net');const s=net.createServer();s.once('error',()=>process.exit(1));s.listen(${port},'${PUBLIC_HOST}',()=>s.close(()=>process.exit(0)));`;
548
+ function isHostPortAvailableSync(port2) {
549
+ const script = `const net=require('node:net');const s=net.createServer();s.once('error',()=>process.exit(1));s.listen(${port2},'${PUBLIC_HOST}',()=>s.close(()=>process.exit(0)));`;
574
550
  const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
575
551
  return result.status === 0;
576
552
  }
577
- function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false, context) {
553
+ function allocateHostPorts(projectDir, stage2, intentsInDeterministicOrder, validationMode = false, context, adapters = {}) {
554
+ const probe = adapters.probe ?? isHostPortAvailableSync;
578
555
  const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
579
556
  for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
580
557
  const owner = reserved.get(intent.requested);
581
- if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage, context?.sourceFile, context?.composition);
558
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage2, context?.sourceFile, context?.composition);
582
559
  reserved.set(intent.requested, intent.logicalPath);
583
560
  allocated.set(intent.logicalPath, intent.requested);
584
561
  }
@@ -586,7 +563,7 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
586
563
  let placeholder = 6e4;
587
564
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
588
565
  while (reserved.has(placeholder)) placeholder--;
589
- if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage, value: intent.requested, reason: "No validation placeholder port is available" });
566
+ if (placeholder < 1) throw new ConfigError({ ...context ?? {}, configPath: intent.logicalPath, stage: stage2, value: intent.requested, reason: "No validation placeholder port is available" });
590
567
  reserved.set(placeholder, intent.logicalPath);
591
568
  allocated.set(intent.logicalPath, placeholder--);
592
569
  }
@@ -602,113 +579,341 @@ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, valid
602
579
  } catch {
603
580
  cached = {};
604
581
  }
605
- const nextCache = { ...cached };
606
582
  for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
607
583
  const prior = cached[intent.logicalPath];
608
- let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && isHostPortAvailableSync(prior) ? prior : void 0;
584
+ let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && probe(prior) ? prior : void 0;
609
585
  if (selected === void 0) {
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));
611
- selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
586
+ const scan = adapters.candidatePorts ?? [...Array(65536 - AUTO_PORT_SCAN_START).keys()].map((i) => i + AUTO_PORT_SCAN_START).concat([...Array(19999 - 1024 + 1).keys()].map((i) => i + 1024));
587
+ selected = scan.find((p) => p >= 1 && p <= 65535 && !reserved.has(p) && probe(p));
612
588
  }
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" });
589
+ if (selected === void 0) throw new ConfigError({ sourceFile: context?.sourceFile ?? "Builder effective composition", ...context?.composition ? { composition: context.composition } : {}, configPath: intent.logicalPath, stage: stage2, value: intent.requested, reason: "No available host port could be allocated" });
614
590
  reserved.set(selected, intent.logicalPath);
615
591
  allocated.set(intent.logicalPath, selected);
616
- nextCache[intent.logicalPath] = selected;
617
- }
618
- if (intentsInDeterministicOrder.some((i) => i.requested === "AUTO")) {
619
- mkdirSync(path.dirname(cachePath), { recursive: true });
620
- const temp = `${cachePath}.${process.pid}.tmp`;
621
- writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: nextCache }, null, 2));
622
- renameSync(temp, cachePath);
623
592
  }
624
593
  return allocated;
625
594
  }
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}"` });
595
+ function persistHostPortAllocations(projectDir, allocations) {
596
+ if (!allocations.size) return;
597
+ const cachePath = path.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
598
+ let cached = {};
599
+ try {
600
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
601
+ if (parsed?.version === AUTO_PORT_CACHE_VERSION && parsed.allocations && typeof parsed.allocations === "object") cached = parsed.allocations;
602
+ } catch {
633
603
  }
604
+ mkdirSync(path.dirname(cachePath), { recursive: true });
605
+ const temp = `${cachePath}.${process.pid}.tmp`;
606
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: { ...cached, ...Object.fromEntries(allocations) } }, null, 2));
607
+ renameSync(temp, cachePath);
634
608
  }
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}"` });
609
+ function removeHostPortAllocations(projectDir, keys) {
610
+ if (!keys.length) return;
611
+ const cachePath = path.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
612
+ if (!existsSync(cachePath)) return;
613
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
614
+ if (parsed?.version !== AUTO_PORT_CACHE_VERSION || !parsed.allocations || typeof parsed.allocations !== "object") return;
615
+ const remaining = { ...parsed.allocations };
616
+ for (const key of keys) delete remaining[key];
617
+ if (!Object.keys(remaining).length) {
618
+ unlinkSync(cachePath);
619
+ return;
644
620
  }
621
+ const temp = `${cachePath}.${process.pid}.tmp`;
622
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: remaining }, null, 2));
623
+ renameSync(temp, cachePath);
645
624
  }
646
- function normalizeProjectName(name, projectDir) {
647
- let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
648
- if (!normalized || !/^[a-z0-9]/.test(normalized)) {
649
- if (projectDir) {
650
- const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
651
- return `project-${hash}`;
652
- }
653
- return "project";
625
+
626
+ // src/core/config/types.ts
627
+ var nodeId = (meshRoot, sourceService) => JSON.stringify([meshRoot ?? null, sourceService]);
628
+ var displayNode = (id) => {
629
+ const [root, service] = JSON.parse(id);
630
+ return root ? `${root}.source.${service}` : service;
631
+ };
632
+
633
+ // src/core/config/publication.ts
634
+ function resolvePublicationIntent(graph, stage2, composition, publish, meshSourceFile, publishOrigins) {
635
+ const result = [];
636
+ const append = (id, endpoint, origin, selector) => {
637
+ const node = graph.nodes.get(id);
638
+ if (!node) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target is not reachable" });
639
+ const def = node.declaration.endpoints[endpoint];
640
+ if (!def) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target endpoint does not exist" });
641
+ if (def.publicPort === void 0) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector requires an endpoint with publicPort capability" });
642
+ result.push({ nodeId: id, endpoint, requestedPort: def.publicPort, origin, logicalPath: `${displayNode(id)}.endpoints.${endpoint}` });
643
+ };
644
+ if (composition === "service") {
645
+ for (const [id, node] of graph.nodes) for (const [endpoint, def] of Object.entries(node.declaration.endpoints)) if (def.publicPort !== void 0) append(id, endpoint, node.origin, `${displayNode(id)}.endpoints.${endpoint}`);
646
+ } else if (publish) for (const [root, selectors] of publish) {
647
+ const main = nodeId(root, "main"), closure = graph.closures.get(main) ?? /* @__PURE__ */ new Set();
648
+ for (const selector of new Set(selectors)) {
649
+ const match = /^([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/.exec(selector);
650
+ const mainOrigin = graph.nodes.get(main)?.origin;
651
+ if (!mainOrigin) continue;
652
+ const origin = publishOrigins?.get(root) ?? (meshSourceFile ? { ...mainOrigin, sourceFile: meshSourceFile, configPath: `services.${root}.publish`, scope: "mesh" } : mainOrigin);
653
+ if (!match) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "Invalid publish selector; expected <local>.endpoints.<endpoint>" });
654
+ const id = nodeId(root, match[1]);
655
+ if (!closure.has(id)) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition, referencedObject: selector, reason: "publish selector target is not in source main requisite closure" });
656
+ append(id, match[2], origin, selector);
657
+ }
658
+ }
659
+ result.sort((a, b) => `${a.nodeId}:${a.endpoint}`.localeCompare(`${b.nodeId}:${b.endpoint}`));
660
+ const fixed = /* @__PURE__ */ new Map();
661
+ for (const item of result) if (typeof item.requestedPort === "number") {
662
+ const prior = fixed.get(item.requestedPort);
663
+ if (prior) throw new PortConflictError(item.requestedPort, prior.logicalPath, item.logicalPath, stage2, item.origin.sourceFile, composition);
664
+ fixed.set(item.requestedPort, item);
654
665
  }
655
- return normalized;
666
+ return result;
656
667
  }
657
- function deriveProjectName(name, stage, projectDir, options = {}) {
658
- let base = normalizeProjectName(name, projectDir);
659
- if (options.hash && projectDir) {
660
- const hash = crypto.createHash("sha1").update(path.resolve(projectDir)).digest("hex").slice(0, 7);
661
- base = `${base}-${hash}`;
662
- }
663
- if (!stage) {
664
- return base;
665
- }
666
- const s = stage.toLowerCase();
667
- if (s === "dev") {
668
- return base;
669
- }
670
- if (s === "prod") {
671
- return `${base}-prod`;
672
- }
673
- if (s === "test" || s === "test-unit") {
674
- return `${base}-test`;
675
- }
676
- if (s === "e2e" || s === "test-e2e") {
677
- return `${base}-e2e`;
678
- }
679
- return `${base}-${s}`;
668
+
669
+ // src/core/config/references.ts
670
+ var token = /^([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
671
+ var sourceToken = /^source\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
672
+ var meshToken = /^([a-z][a-z0-9-]*)\.source\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
673
+ function fail2(context, raw, reason) {
674
+ throw new ConfigError({ sourceFile: context.origin.sourceFile, configPath: context.origin.configPath, stage: context.stage, composition: context.composition, referencedObject: raw, reason });
675
+ }
676
+ function parseBuilderReference(raw, context) {
677
+ let target, endpoint, property;
678
+ let match;
679
+ if (context.origin.scope === "build" && (match = token.exec(raw))) {
680
+ target = nodeId(context.origin.meshRoot, match[1]);
681
+ endpoint = match[2];
682
+ property = match[3];
683
+ } else if (context.origin.scope === "mesh" && (match = sourceToken.exec(raw))) {
684
+ if (!context.origin.meshRoot) fail2(context, raw, "source-relative reference requires mesh root");
685
+ target = nodeId(context.origin.meshRoot, match[1]);
686
+ endpoint = match[2];
687
+ property = match[3];
688
+ } else if (context.origin.scope === "mesh" && (match = meshToken.exec(raw))) {
689
+ target = nodeId(match[1], match[2]);
690
+ endpoint = match[3];
691
+ property = match[4];
692
+ } else fail2(context, raw, "Invalid V3 endpoint reference grammar");
693
+ if (!ENDPOINT_PROPERTIES.includes(property)) fail2(context, raw, "Unknown endpoint property");
694
+ return { raw, target, endpoint, property, origin: context.origin };
695
+ }
696
+ function resolveBuilderReference(ref, context) {
697
+ const target = context.graph.nodes.get(ref.target);
698
+ if (!target || context.consumer && !context.graph.closures.get(context.consumer)?.has(ref.target)) fail2(context, ref.raw, `outside effective requisite closure: ${context.consumer ? displayNode(context.consumer) : "tester"} -> ${displayNode(ref.target)}`);
699
+ const endpoint = context.endpoints.get(ref.target)?.[ref.endpoint];
700
+ if (!endpoint) fail2(context, ref.raw, `Unknown endpoint ${displayNode(ref.target)}.endpoints.${ref.endpoint}`);
701
+ return resolveEndpointProperty(endpoint, ref.property, { sourceFile: context.origin.sourceFile, configPath: context.origin.configPath, stage: context.stage, composition: context.composition, referencedObject: ref.raw });
702
+ }
703
+ function interpolateBuilderReferences(value, context) {
704
+ const sentinel = "\0DOLLAR\0";
705
+ const protectedValue = value.replace(/\$\$/g, sentinel);
706
+ if (protectedValue.includes("${") && /\$\{[^}]*$/.test(protectedValue)) fail2(context, protectedValue, "Malformed Builder endpoint reference");
707
+ return protectedValue.replace(/\$\{([^}]*)\}/g, (_whole, body) => resolveBuilderReference(parseBuilderReference(body, context), context)).replaceAll(sentinel, "$");
680
708
  }
681
- function parseVolume(mount) {
682
- if (typeof mount === "string") {
683
- const separators = [];
684
- let start = 0;
685
- for (let i = 0; i < mount.length; i++) {
686
- if (mount[i] !== ":") continue;
687
- if (i === start + 1 && /[a-z]/i.test(mount[start]) && /[\\/]/.test(mount[i + 1] ?? "")) continue;
688
- separators.push(i);
689
- start = i + 1;
709
+
710
+ // src/core/config/serviceGraph.ts
711
+ var fail3 = (origin, stage2, reason, referencedObject) => {
712
+ throw new ConfigError({ sourceFile: origin.sourceFile, configPath: origin.configPath, stage: stage2, composition: origin.scope === "mesh" ? "mesh" : "service", ...referencedObject ? { referencedObject } : {}, reason });
713
+ };
714
+ function buildDeclaredGraph(input) {
715
+ const edges = [];
716
+ for (const node of input.nodes.values()) for (const [key, kind] of Object.entries(node.declaration.requisites)) {
717
+ const origin = node.requisiteOrigins.get(key) ?? node.origin;
718
+ let target;
719
+ if (key.startsWith("@mesh:")) target = nodeId(key.slice(6), "main");
720
+ else target = nodeId(node.meshRoot, key);
721
+ const displayKey = key.replace(/^@mesh:/, "");
722
+ if (key === "tester" || key === "@mesh:tester") fail3(origin, input.stage, "tester cannot be a requisite target", displayKey);
723
+ if (!input.nodes.has(target)) fail3(origin, input.stage, "Unknown requisite target", displayKey);
724
+ edges.push({ consumer: node.id, target, kind, origin });
725
+ }
726
+ edges.sort((a, b) => `${a.consumer}:${a.target}:${a.kind}`.localeCompare(`${b.consumer}:${b.target}:${b.kind}`));
727
+ return { nodes: input.nodes, roots: [...input.roots].sort(), edges };
728
+ }
729
+ function computeClosure(start, adjacency) {
730
+ const visited = /* @__PURE__ */ new Set();
731
+ const stack = [start];
732
+ while (stack.length) {
733
+ const id = stack.pop();
734
+ if (visited.has(id)) continue;
735
+ visited.add(id);
736
+ for (const edge of adjacency.get(id) ?? []) stack.push(edge.target);
737
+ }
738
+ return visited;
739
+ }
740
+ function selectReachableGraph(declared, profile) {
741
+ const adjacency = /* @__PURE__ */ new Map();
742
+ for (const edge of declared.edges) {
743
+ const list = adjacency.get(edge.consumer) ?? [];
744
+ list.push(edge);
745
+ adjacency.set(edge.consumer, list);
746
+ }
747
+ const active = /* @__PURE__ */ new Set();
748
+ if (profile.infraMode === "isolated") for (const root of declared.roots) active.add(root);
749
+ else for (const root of declared.roots) for (const id of computeClosure(root, adjacency)) active.add(id);
750
+ const nodes = new Map([...declared.nodes].filter(([id]) => active.has(id)));
751
+ const edges = profile.infraMode === "isolated" ? [] : declared.edges.filter((edge) => active.has(edge.consumer) && active.has(edge.target));
752
+ const activeAdjacency = /* @__PURE__ */ new Map();
753
+ for (const edge of edges) {
754
+ const list = activeAdjacency.get(edge.consumer) ?? [];
755
+ list.push(edge);
756
+ activeAdjacency.set(edge.consumer, list);
757
+ }
758
+ const closures = /* @__PURE__ */ new Map();
759
+ for (const id of nodes.keys()) closures.set(id, computeClosure(id, activeAdjacency));
760
+ const lifecycle = /* @__PURE__ */ new Map();
761
+ for (const id of nodes.keys()) lifecycle.set(id, "long-running");
762
+ const classification = /* @__PURE__ */ new Map();
763
+ for (const edge of edges) {
764
+ const kinds = classification.get(edge.target) ?? /* @__PURE__ */ new Map();
765
+ kinds.set(edge.kind, edge);
766
+ classification.set(edge.target, kinds);
767
+ }
768
+ for (const [id, kinds] of classification) {
769
+ if (kinds.has("dependency") && kinds.has("prerequisite")) {
770
+ const dep = kinds.get("dependency"), pre = kinds.get("prerequisite");
771
+ fail3(pre.origin, profile.stage, `Target ${displayNode(id)} is both dependency and prerequisite; dependency at ${dep.origin.sourceFile}:${dep.origin.configPath}, prerequisite at ${pre.origin.sourceFile}:${pre.origin.configPath}`, displayNode(id));
772
+ }
773
+ if (kinds.has("prerequisite")) {
774
+ if (nodes.get(id)?.kind === "main") fail3(kinds.get("prerequisite").origin, profile.stage, "main cannot be a prerequisite", displayNode(id));
775
+ lifecycle.set(id, "prerequisite");
776
+ }
777
+ }
778
+ const graph = { nodes, roots: declared.roots.filter((id) => active.has(id)), edges, closures, lifecycle };
779
+ validateGraphLifecycle(graph, profile.stage);
780
+ return graph;
781
+ }
782
+ function validateGraphLifecycle(graph, stage2 = "dev") {
783
+ const adjacency = /* @__PURE__ */ new Map();
784
+ for (const edge of graph.edges) if (edge.kind !== "requirement") {
785
+ const list = adjacency.get(edge.consumer) ?? [];
786
+ list.push(edge);
787
+ adjacency.set(edge.consumer, list);
788
+ }
789
+ const gray = /* @__PURE__ */ new Set(), black = /* @__PURE__ */ new Set(), stack = [];
790
+ const visit = (id) => {
791
+ if (black.has(id)) return;
792
+ gray.add(id);
793
+ for (const edge of adjacency.get(id) ?? []) {
794
+ if (gray.has(edge.target)) {
795
+ const first = stack.findIndex((item) => item.consumer === edge.target);
796
+ const cycle = [...stack.slice(Math.max(0, first)), edge].map((item) => `${displayNode(item.consumer)} -${item.kind}-> ${displayNode(item.target)}`).join("; ");
797
+ fail3(edge.origin, stage2, `ordering cycle: ${cycle}`, displayNode(edge.target));
798
+ }
799
+ stack.push(edge);
800
+ visit(edge.target);
801
+ stack.pop();
690
802
  }
691
- const first = separators[0];
692
- if (first === void 0) return { type: "volume", target: mount, suffix: "" };
693
- const source = mount.slice(0, first), end = separators[1];
694
- return { type: isBindMount(source) ? "bind" : "volume", source, target: mount.slice(first + 1, end), suffix: mount.slice(first) };
695
- }
696
- if (mount && typeof mount === "object") {
697
- const value = mount;
698
- return { type: String(value.type ?? "volume"), ...typeof value.source === "string" ? { source: value.source } : {}, target: String(value.target ?? ""), suffix: "" };
699
- }
700
- return void 0;
701
- }
702
- function rewriteVolumeSource(mount, source) {
703
- const parsed = parseVolume(mount);
704
- return typeof mount === "string" ? `${source}${parsed.suffix}` : { ...mount, source };
705
- }
706
- function namespaceVolume(mount, names) {
707
- const parsed = parseVolume(mount);
708
- const source = parsed?.type === "volume" && parsed.source ? names.get(parsed.source) : void 0;
709
- return source ? rewriteVolumeSource(mount, source) : mount;
803
+ gray.delete(id);
804
+ black.add(id);
805
+ };
806
+ for (const id of graph.nodes.keys()) visit(id);
710
807
  }
711
- function isAnonymousVolume(mount) {
808
+
809
+ // src/core/config/lifecycleGraph.ts
810
+ function assertAcyclicGraph(graph, context) {
811
+ const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
812
+ const visit = (node) => {
813
+ if (visiting.has(node)) {
814
+ const start = stack.indexOf(node);
815
+ const cycle = [...stack.slice(start), node];
816
+ throw new ConfigError({ ...context, configPath: "services.depends_on", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
817
+ }
818
+ if (visited.has(node)) return;
819
+ visiting.add(node);
820
+ stack.push(node);
821
+ for (const next of graph.get(node) ?? []) visit(next);
822
+ stack.pop();
823
+ visiting.delete(node);
824
+ visited.add(node);
825
+ };
826
+ for (const node of graph.keys()) visit(node);
827
+ }
828
+
829
+ // src/core/composition/assertComposeLifecycleAcyclic.ts
830
+ function assertComposeLifecycleAcyclic(services2, context) {
831
+ const graph = new Map(
832
+ Object.keys(services2).map((name) => [name, /* @__PURE__ */ new Set()])
833
+ );
834
+ for (const [name, service] of Object.entries(services2)) {
835
+ const value = service.depends_on;
836
+ const targets = Array.isArray(value) ? value.filter((item) => typeof item === "string") : value && typeof value === "object" ? Object.keys(value) : [];
837
+ for (const target of targets) {
838
+ if (graph.has(target)) graph.get(name).add(target);
839
+ }
840
+ }
841
+ assertAcyclicGraph(graph, context);
842
+ }
843
+
844
+ // src/core/composition/composeDependsOn.ts
845
+ function normalizeComposeDependsOn(value) {
846
+ const entries2 = Array.isArray(value) ? value.filter((item) => typeof item === "string").map((name) => [name, { condition: "service_started" }]) : value && typeof value === "object" ? Object.entries(value) : [];
847
+ return Object.fromEntries(entries2.map(([name, raw]) => [name, raw && typeof raw === "object" && !Array.isArray(raw) ? { condition: "service_started", ...raw } : { condition: "service_started" }]));
848
+ }
849
+ function addComposeCondition(service, target, condition) {
850
+ service.depends_on = { ...normalizeComposeDependsOn(service.depends_on), [target]: { condition } };
851
+ }
852
+
853
+ // src/core/composition/composeEnvironment.ts
854
+ function normalizeComposeEnvironment(value, context) {
855
+ const result = {};
856
+ if (value == null) return result;
857
+ if (Array.isArray(value)) {
858
+ for (const item of value) {
859
+ if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
860
+ const at = item.indexOf("=");
861
+ if (at < 0) {
862
+ result[item] = null;
863
+ continue;
864
+ }
865
+ result[item.slice(0, at)] = item.slice(at + 1);
866
+ }
867
+ return result;
868
+ }
869
+ if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
870
+ for (const [key, val] of Object.entries(value)) {
871
+ if (val === null || val === void 0) {
872
+ result[key] = null;
873
+ continue;
874
+ }
875
+ if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
876
+ result[key] = String(val);
877
+ }
878
+ return result;
879
+ }
880
+
881
+ // src/core/composition/composeNetworks.ts
882
+ function normalizeNetworks(value) {
883
+ if (Array.isArray(value)) return Object.fromEntries(value.filter((name) => typeof name === "string").map((name) => [name, null]));
884
+ return value && typeof value === "object" ? { ...value } : {};
885
+ }
886
+ function parseVolume(mount) {
887
+ if (typeof mount === "string") {
888
+ const separators = [];
889
+ let start = 0;
890
+ for (let i = 0; i < mount.length; i++) {
891
+ if (mount[i] !== ":") continue;
892
+ if (i === start + 1 && /[a-z]/i.test(mount[start]) && /[\\/]/.test(mount[i + 1] ?? "")) continue;
893
+ separators.push(i);
894
+ start = i + 1;
895
+ }
896
+ const first = separators[0];
897
+ if (first === void 0) return { type: "volume", target: mount, suffix: "" };
898
+ const source = mount.slice(0, first), end = separators[1];
899
+ return { type: isBindMount(source) ? "bind" : "volume", source, target: mount.slice(first + 1, end), suffix: mount.slice(first) };
900
+ }
901
+ if (mount && typeof mount === "object") {
902
+ const value = mount;
903
+ return { type: String(value.type ?? "volume"), ...typeof value.source === "string" ? { source: value.source } : {}, target: String(value.target ?? ""), suffix: "" };
904
+ }
905
+ return void 0;
906
+ }
907
+ function rewriteVolumeSource(mount, source) {
908
+ const parsed = parseVolume(mount);
909
+ return typeof mount === "string" ? `${source}${parsed.suffix}` : { ...mount, source };
910
+ }
911
+ function namespaceVolume(mount, names) {
912
+ const parsed = parseVolume(mount);
913
+ const source = parsed?.type === "volume" && parsed.source ? names.get(parsed.source) : void 0;
914
+ return source ? rewriteVolumeSource(mount, source) : mount;
915
+ }
916
+ function isAnonymousVolume(mount) {
712
917
  const parsed = parseVolume(mount);
713
918
  return parsed?.type === "volume" && !parsed.source;
714
919
  }
@@ -720,8 +925,8 @@ function isHostFilesystemRoot(source) {
720
925
  }
721
926
  return path.posix.normalize(normalized) === "/";
722
927
  }
723
- function anonymousVolumeServices(services) {
724
- return Object.entries(services).filter(([, service]) => Array.isArray(service.volumes) && service.volumes.some(isAnonymousVolume)).map(([name]) => name);
928
+ function anonymousVolumeServices(services2) {
929
+ return Object.entries(services2).filter(([, service]) => Array.isArray(service.volumes) && service.volumes.some(isAnonymousVolume)).map(([name]) => name);
725
930
  }
726
931
  var posix = (p) => p.replace(/\\/g, "/");
727
932
  function rebase(p, base, out) {
@@ -817,36 +1022,89 @@ function rebaseAppOverridePaths(document, serviceProjectDir, outputProjectDir) {
817
1022
  }
818
1023
  return doc;
819
1024
  }
820
-
821
- // src/core/composition/composeEnvironment.ts
822
- function normalizeComposeEnvironment(value, context) {
823
- const result = {};
824
- if (value == null) return result;
825
- if (Array.isArray(value)) {
826
- for (const item of value) {
827
- if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
828
- const at = item.indexOf("=");
829
- if (at < 0) {
830
- result[item] = null;
831
- continue;
832
- }
833
- result[item.slice(0, at)] = item.slice(at + 1);
1025
+ var GeneratedComposeNameAllocator = class {
1026
+ occupied;
1027
+ allocated = /* @__PURE__ */ new Map();
1028
+ constructor(initialNames = []) {
1029
+ this.occupied = new Set(initialNames);
1030
+ }
1031
+ allocate(identity, hint) {
1032
+ const existing = this.allocated.get(identity);
1033
+ if (existing) return existing;
1034
+ const hash = createHash("sha256").update(identity).digest("hex");
1035
+ const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
1036
+ let rootMain = false;
1037
+ try {
1038
+ const parts = JSON.parse(identity);
1039
+ rootMain = Array.isArray(parts) && parts.length === 2 && parts[1] === "main" && typeof parts[0] === "string" && parts[0].startsWith("[");
1040
+ } catch {
1041
+ rootMain = false;
834
1042
  }
835
- return result;
1043
+ for (const candidate of [
1044
+ ...rootMain ? [safeHint] : [],
1045
+ ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
1046
+ ]) {
1047
+ if (this.occupied.has(candidate)) continue;
1048
+ this.occupied.add(candidate);
1049
+ this.allocated.set(identity, candidate);
1050
+ return candidate;
1051
+ }
1052
+ throw new Error(`Unable to allocate unique Compose name for ${identity}`);
836
1053
  }
837
- if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
838
- for (const [key, val] of Object.entries(value)) {
839
- if (val === null || val === void 0) {
840
- result[key] = null;
841
- continue;
1054
+ assertUnique() {
1055
+ if (new Set(this.allocated.values()).size !== this.allocated.size) {
1056
+ throw new Error("Internal generated Compose name collision");
842
1057
  }
843
- if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
844
- result[key] = String(val);
845
1058
  }
846
- return result;
1059
+ };
1060
+ function loadComposeDocument(absolutePath, context) {
1061
+ const fail4 = (reason, value) => {
1062
+ throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
1063
+ };
1064
+ if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) throw new ConfigError({ ...context, value: absolutePath, reason: "Compose file does not exist or is not a regular file" });
1065
+ let text = "";
1066
+ try {
1067
+ text = readFileSync(absolutePath, "utf8");
1068
+ } catch (e) {
1069
+ fail4(`Failed to read Compose file: ${String(e)}`);
1070
+ }
1071
+ let docs = [];
1072
+ try {
1073
+ docs = parseAllDocuments(text, { prettyErrors: true });
1074
+ } catch (e) {
1075
+ fail4(`Invalid Compose YAML: ${String(e)}`);
1076
+ }
1077
+ if (docs.length !== 1) fail4("Compose file must contain exactly one YAML document");
1078
+ const errors = docs[0].errors;
1079
+ if (errors.length) fail4(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
1080
+ let parsed;
1081
+ try {
1082
+ parsed = parse(text);
1083
+ } catch (e) {
1084
+ fail4(`Invalid Compose YAML: ${String(e)}`);
1085
+ }
1086
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail4("Compose root must be an object");
1087
+ return parsed;
847
1088
  }
848
- function mergeComposeEnvironment(service, overlay) {
849
- service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
1089
+
1090
+ // src/core/composition/mergeMainOverride.ts
1091
+ function isMap(value) {
1092
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1093
+ const prototype = Object.getPrototypeOf(value);
1094
+ return prototype === Object.prototype || prototype === null;
1095
+ }
1096
+ function mergeValue(inherited, overlay) {
1097
+ if (overlay === void 0) return structuredClone(inherited);
1098
+ if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1099
+ return Object.fromEntries(
1100
+ [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1101
+ key,
1102
+ Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1103
+ ])
1104
+ );
1105
+ }
1106
+ function mergeMainOverride(inherited, overlay) {
1107
+ return mergeValue(inherited, overlay);
850
1108
  }
851
1109
 
852
1110
  // src/core/composition/composeBuildResources.ts
@@ -953,183 +1211,60 @@ function namespaceDependencyCompose(options) {
953
1211
  if (doc.secrets) doc.secrets = rewriteResourceDefinitions(doc.secrets, secretNameMap);
954
1212
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
955
1213
  }
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 = (path24, kind, name) => {
974
- if (kind === "network" && name === "default") return;
975
- if (!exists(kind, name)) fail(path24, 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);
1214
+ function validateMaterializedComposeFiles(document, sourceFile, stage2, options = {}) {
1215
+ const baseDir = options.baseDir ?? path.dirname(sourceFile);
1216
+ const within = (file, configPath, required) => {
1217
+ const absolute = path.resolve(baseDir, file), relative = path.relative(baseDir, absolute);
1218
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file escapes its project" });
1219
+ let regular = false;
1220
+ try {
1221
+ const baseReal = fs.realpathSync(baseDir), fileReal = fs.realpathSync(absolute), realRelative = path.relative(baseReal, fileReal);
1222
+ if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file symlink escapes its project" });
1223
+ regular = fs.statSync(fileReal).isFile();
1224
+ } catch (error) {
1225
+ if (error instanceof ConfigError) throw error;
1016
1226
  }
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
-
1033
- // src/core/composition/validateDependencyCompose.ts
1034
- function validateDependencyCompose(dependencyKey, dependency, document, context) {
1035
- const fail = (configPath, reason, value) => {
1036
- throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
1227
+ if (required && !regular) throw new ConfigError({ sourceFile, configPath, stage: stage2, composition: options.composition ?? "service", value: file, reason: "Materialized Compose file resource is missing or not a regular file" });
1037
1228
  };
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" });
1040
- const services = document.services ?? {};
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");
1045
- if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
1046
- if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
1047
- if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
1048
- if (svc.container_name !== void 0) fail(`services.${name}.container_name`, `fixed container_name is forbidden`);
1049
- for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1050
- const mount = parseVolume(v);
1051
- if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail(`services.${name}.volumes`, "host root bind mounts are forbidden", v);
1052
- }
1053
- const internalRefs = [];
1054
- if (Array.isArray(svc.depends_on)) {
1055
- for (const ref of svc.depends_on) if (typeof ref === "string") internalRefs.push(["depends_on", ref]);
1056
- } else if (svc.depends_on && typeof svc.depends_on === "object") {
1057
- for (const ref of Object.keys(svc.depends_on)) internalRefs.push(["depends_on", ref]);
1058
- }
1059
- if (Array.isArray(svc.links)) {
1060
- for (const ref of svc.links) if (typeof ref === "string") internalRefs.push(["links", ref.split(":")[0]]);
1061
- }
1062
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) internalRefs.push(["network_mode", svc.network_mode.slice(8)]);
1063
- if (Array.isArray(svc.volumes_from)) {
1064
- for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
1229
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
1230
+ const entries2 = Array.isArray(service.env_file) ? service.env_file : service.env_file === void 0 ? [] : [service.env_file];
1231
+ for (const [index, entry] of entries2.entries()) {
1232
+ const file = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.path : void 0;
1233
+ if (typeof file !== "string") continue;
1234
+ const required = typeof entry === "string" || entry.required !== false;
1235
+ within(file, `services.${serviceName}.env_file.${index}`, required);
1065
1236
  }
1066
- for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
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);
1068
- }
1069
- assertComposeLifecycleAcyclic(services, {
1070
- sourceFile: context.composePath,
1071
- stage: context.stage,
1072
- composition: "service"
1073
- });
1074
- if (!Object.keys(dependency.endpoints).length) return;
1075
- if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
1076
- const owners = /* @__PURE__ */ new Set();
1077
- for (const [endpoint, definition] of Object.entries(dependency.endpoints)) {
1078
- const owner = definition.service;
1079
- if (!services[owner]) fail(`endpoints.${endpoint}.service`, `declared endpoint owner "${owner}" does not exist`, owner);
1080
- owners.add(owner);
1081
- }
1082
- for (const owner of owners) {
1083
- if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
1084
- if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
1085
1237
  }
1086
- }
1087
- function validateMaterializedComposeFiles(document, sourceFile, stage, options = {}) {
1088
- const baseDir = options.baseDir ?? path.dirname(sourceFile);
1089
1238
  for (const kind of ["configs", "secrets"]) {
1090
1239
  for (const [name, raw] of Object.entries(document[kind] ?? {})) {
1091
1240
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1092
1241
  const file = raw.file;
1093
1242
  if (typeof file !== "string") continue;
1094
- const absolute = path.resolve(baseDir, file);
1095
- let regular = false;
1096
- try {
1097
- regular = fs.statSync(absolute).isFile();
1098
- } catch {
1099
- }
1100
- if (!regular) {
1101
- throw new ConfigError({
1102
- sourceFile,
1103
- configPath: `${kind}.${name}.file`,
1104
- stage,
1105
- composition: options.composition ?? "service",
1106
- value: file,
1107
- reason: "Materialized Compose file resource is missing or not a regular file"
1108
- });
1109
- }
1243
+ within(file, `${kind}.${name}.file`, true);
1110
1244
  }
1111
1245
  }
1112
1246
  }
1113
- function validateMaterializedComposeBuildInputs(document, sourceFile, stage, composition) {
1247
+ function validateMaterializedComposeBuildInputs(document, sourceFile, stage2, composition) {
1114
1248
  const baseDir = path.dirname(sourceFile);
1115
1249
  for (const [name, service] of Object.entries(document.services ?? {})) {
1116
1250
  const build = service.build;
1117
1251
  if (build === void 0) continue;
1252
+ assertNoServiceBuildContexts(service, `services.${name}`, sourceFile);
1118
1253
  const objectBuild = build && typeof build === "object" && !Array.isArray(build) ? build : void 0;
1119
1254
  const context = typeof build === "string" ? build : objectBuild?.context ?? ".";
1120
1255
  const configPath = `services.${name}.build`;
1121
- const fail = (field, value, reason) => {
1256
+ const fail4 = (field, value, reason) => {
1122
1257
  throw new ConfigError({
1123
1258
  sourceFile,
1124
1259
  configPath: `${configPath}.${field}`,
1125
- stage,
1260
+ stage: stage2,
1126
1261
  composition,
1127
1262
  value,
1128
1263
  reason
1129
1264
  });
1130
1265
  };
1131
1266
  if (typeof context !== "string" || context.trim() === "") {
1132
- return fail("context", context, "Local build context must be a non-empty path");
1267
+ return fail4("context", context, "Local build context must be a non-empty path");
1133
1268
  }
1134
1269
  if (isRemoteBuildContext(context)) continue;
1135
1270
  const absoluteContext = path.resolve(baseDir, context);
@@ -1139,7 +1274,7 @@ function validateMaterializedComposeBuildInputs(document, sourceFile, stage, com
1139
1274
  } catch {
1140
1275
  }
1141
1276
  if (!directory) {
1142
- fail(
1277
+ fail4(
1143
1278
  "context",
1144
1279
  context,
1145
1280
  "Materialized local build context is missing or not a directory"
@@ -1148,7 +1283,7 @@ function validateMaterializedComposeBuildInputs(document, sourceFile, stage, com
1148
1283
  if (objectBuild?.dockerfile_inline !== void 0) continue;
1149
1284
  const dockerfile = objectBuild?.dockerfile ?? "Dockerfile";
1150
1285
  if (typeof dockerfile !== "string" || dockerfile.trim() === "") {
1151
- return fail("dockerfile", dockerfile, "Dockerfile path must be a non-empty string");
1286
+ return fail4("dockerfile", dockerfile, "Dockerfile path must be a non-empty string");
1152
1287
  }
1153
1288
  const absoluteDockerfile = path.resolve(absoluteContext, dockerfile);
1154
1289
  let regular = false;
@@ -1157,7 +1292,7 @@ function validateMaterializedComposeBuildInputs(document, sourceFile, stage, com
1157
1292
  } catch {
1158
1293
  }
1159
1294
  if (!regular) {
1160
- fail(
1295
+ fail4(
1161
1296
  "dockerfile",
1162
1297
  dockerfile,
1163
1298
  "Materialized local Dockerfile is missing or not a regular file"
@@ -1165,28 +1300,83 @@ function validateMaterializedComposeBuildInputs(document, sourceFile, stage, com
1165
1300
  }
1166
1301
  }
1167
1302
  }
1303
+
1304
+ // src/core/composition/validateComposeResourceReferences.ts
1305
+ function validateComposeResourceReferences(document, context, onlyServices) {
1306
+ const fail4 = (configPath, kind, name) => {
1307
+ throw new ConfigError({
1308
+ sourceFile: context.sourceFile,
1309
+ configPath,
1310
+ ...context.stage ? { stage: context.stage } : {},
1311
+ composition: context.composition,
1312
+ referencedObject: name,
1313
+ reason: `Compose ${kind} reference "${name}" has no top-level definition`
1314
+ });
1315
+ };
1316
+ const exists = (kind, name) => {
1317
+ const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
1318
+ return Boolean(definitions && Object.hasOwn(definitions, name));
1319
+ };
1320
+ const check = (path25, kind, name) => {
1321
+ if (kind === "network" && name === "default") return;
1322
+ if (!exists(kind, name)) fail4(path25, kind, name);
1323
+ };
1324
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
1325
+ validateServiceResources(serviceName, service, check);
1326
+ }
1327
+ }
1328
+ function validateServiceResources(serviceName, service, check) {
1329
+ for (const mount of Array.isArray(service.volumes) ? service.volumes : []) {
1330
+ const parsed = parseVolume(mount);
1331
+ if (parsed?.type === "volume" && parsed.source) {
1332
+ check(`services.${serviceName}.volumes`, "volume", parsed.source);
1333
+ }
1334
+ }
1335
+ const networks = service.networks;
1336
+ const networkNames = Array.isArray(networks) ? networks.filter((name) => typeof name === "string") : networks && typeof networks === "object" ? Object.keys(networks) : [];
1337
+ for (const name of networkNames) {
1338
+ check(`services.${serviceName}.networks`, "network", name);
1339
+ }
1340
+ for (const kind of ["configs", "secrets"]) {
1341
+ const entries2 = service[kind];
1342
+ if (!Array.isArray(entries2)) continue;
1343
+ for (const entry of entries2) {
1344
+ const name = typeof entry === "string" ? entry : entry && typeof entry === "object" && typeof entry.source === "string" ? entry.source : void 0;
1345
+ if (name) check(`services.${serviceName}.${kind}`, kind === "configs" ? "config" : "secret", name);
1346
+ }
1347
+ }
1348
+ for (const name of collectBuildSecretReferences(service)) {
1349
+ check(`services.${serviceName}.build.secrets`, "secret", name);
1350
+ }
1351
+ }
1352
+
1353
+ // src/core/composition/validateOverrideCompose.ts
1168
1354
  function canonicalBuildContext(value, baseDir) {
1169
1355
  return canonicalPath(path.resolve(baseDir, value));
1170
1356
  }
1171
1357
  function isSameBuildContext(actual, expected, baseDir) {
1172
1358
  return canonicalBuildContext(actual, baseDir) === canonicalBuildContext(expected, baseDir);
1173
1359
  }
1174
- function validateAndPrepareAppOverride(document, context) {
1175
- const fail = (path24, reason, value) => {
1176
- throw new ConfigError({ sourceFile: context.file, configPath: path24, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1360
+ function validateAndPrepareMainOverride(document, context) {
1361
+ const fail4 = (path25, reason, value) => {
1362
+ throw new ConfigError({ sourceFile: context.file, configPath: path25, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
1177
1363
  };
1178
1364
  const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1179
- for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
1365
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail4(key, "unsupported override Compose top-level field");
1180
1366
  const keys = Object.keys(document.services ?? {});
1181
- if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
1367
+ if (keys.length !== 1 || keys[0] !== "main") fail4("services", "override must define exactly one service named main");
1182
1368
  validateComposeResourceReferences(document, { sourceFile: context.file, stage: context.stage, composition: "service" });
1183
- const app = structuredClone(document.services.app);
1184
- 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");
1185
- if (Object.hasOwn(app, "healthcheck")) {
1186
- const healthcheck = app.healthcheck;
1369
+ const main = structuredClone(document.services.main);
1370
+ for (const volume of Array.isArray(main.volumes) ? main.volumes : []) {
1371
+ const mount = parseVolume(volume);
1372
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail4("services.main.volumes", "host root bind mounts are forbidden");
1373
+ }
1374
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (main[k] !== void 0) fail4(`services.main.${k}`, "override cannot own endpoint or lifecycle behavior");
1375
+ if (Object.hasOwn(main, "healthcheck")) {
1376
+ const healthcheck = main.healthcheck;
1187
1377
  if (healthcheck === null || typeof healthcheck !== "object" || Array.isArray(healthcheck)) {
1188
- fail(
1189
- "services.app.healthcheck",
1378
+ fail4(
1379
+ "services.main.healthcheck",
1190
1380
  "override healthcheck must be a mapping of timing fields",
1191
1381
  healthcheck
1192
1382
  );
@@ -1200,40 +1390,40 @@ function validateAndPrepareAppOverride(document, context) {
1200
1390
  ]);
1201
1391
  for (const key of Object.keys(healthcheck)) {
1202
1392
  if (!allowedTiming.has(key)) {
1203
- fail(
1204
- `services.app.healthcheck.${key}`,
1393
+ fail4(
1394
+ `services.main.healthcheck.${key}`,
1205
1395
  "override may set only healthcheck timing fields"
1206
1396
  );
1207
1397
  }
1208
1398
  }
1209
1399
  }
1210
- if (typeof app.build === "string") {
1211
- fail("services.app.build", "override cannot replace Builder-owned app build context; use object-form build.args for build arguments", app.build);
1400
+ if (typeof main.build === "string") {
1401
+ fail4("services.main.build", "override cannot replace Builder-owned main build context; use object-form build.args for build arguments", main.build);
1212
1402
  }
1213
- if (app.build && typeof app.build === "object") {
1214
- const build = app.build;
1403
+ if (main.build && typeof main.build === "object") {
1404
+ const build = main.build;
1215
1405
  for (const key of Object.keys(build)) {
1216
1406
  if (!["args", "context"].includes(key)) {
1217
- fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
1407
+ fail4(`services.main.build.${key}`, "override cannot change Builder-owned build configuration");
1218
1408
  }
1219
1409
  }
1220
1410
  if (build.context !== void 0) {
1221
1411
  if (typeof build.context !== "string") {
1222
- fail("services.app.build.context", "override app build context must be a string", build.context);
1412
+ fail4("services.main.build.context", "override main build context must be a string", build.context);
1223
1413
  }
1224
1414
  if (!isSameBuildContext(build.context, context.expectedBuildContext, context.buildContextBaseDir)) {
1225
- fail("services.app.build.context", "override cannot change app build context", build.context);
1415
+ fail4("services.main.build.context", "override cannot change main build context", build.context);
1226
1416
  }
1227
1417
  }
1228
1418
  }
1229
- const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
1230
- for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
1231
- app.environment = env;
1419
+ const env2 = normalizeComposeEnvironment(main.environment, "services.main.environment");
1420
+ for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env2) fail4(`services.main.environment.${k}`, "override cannot set Builder-owned environment");
1421
+ main.environment = env2;
1232
1422
  const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
1233
1423
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
1234
1424
  const resources = {};
1235
1425
  for (const kind of resourceKeys) {
1236
- const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = app[kind];
1426
+ const defs = document[kind] ?? {}, refs = /* @__PURE__ */ new Set(), value = main[kind];
1237
1427
  if (Array.isArray(value)) for (const ref of value) {
1238
1428
  if (kind === "volumes") {
1239
1429
  const volume = parseVolume(ref);
@@ -1244,365 +1434,434 @@ function validateAndPrepareAppOverride(document, context) {
1244
1434
  else if (value && typeof value === "object") for (const name of Object.keys(value)) refs.add(name);
1245
1435
  const names = /* @__PURE__ */ new Map(), mapped = {};
1246
1436
  for (const [name, definition] of Object.entries(defs)) {
1247
- if (!refs.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
1248
- const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1249
- const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
1437
+ if (!refs.has(name)) fail4(`${kind}.${name}`, "override resource must be consumed by main");
1438
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "main" ? `svc--${context.resourceNamespace}--main-override` : "main-override";
1439
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "main", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
1250
1440
  names.set(name, target);
1251
1441
  mapped[target] = namespaceResourceDefinition(name, definition);
1252
1442
  }
1253
1443
  if (names.size) resources[kind] = mapped;
1254
- 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);
1255
- else if (value && typeof value === "object") app[kind] = Object.fromEntries(Object.entries(value).map(([name, definition]) => [names.get(name) ?? name, definition]));
1444
+ if (Array.isArray(value)) main[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);
1445
+ else if (value && typeof value === "object") main[kind] = Object.fromEntries(Object.entries(value).map(([name, definition]) => [names.get(name) ?? name, definition]));
1256
1446
  }
1257
- return { app, resources };
1447
+ return { main, resources };
1258
1448
  }
1259
1449
 
1260
- // src/core/composition/mergeAppOverride.ts
1261
- function isMap(value) {
1262
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1263
- const prototype = Object.getPrototypeOf(value);
1264
- return prototype === Object.prototype || prototype === null;
1265
- }
1266
- function mergeValue(inherited, overlay) {
1267
- if (overlay === void 0) return structuredClone(inherited);
1268
- if (!isMap(inherited) || !isMap(overlay)) return structuredClone(overlay);
1269
- return Object.fromEntries(
1270
- [.../* @__PURE__ */ new Set([...Object.keys(inherited), ...Object.keys(overlay)])].map((key) => [
1271
- key,
1272
- Object.hasOwn(overlay, key) ? mergeValue(inherited[key], overlay[key]) : structuredClone(inherited[key])
1273
- ])
1274
- );
1275
- }
1276
- function mergeAppOverride(inherited, overlay) {
1277
- return mergeValue(inherited, overlay);
1450
+ // src/core/composition/composeHealthcheck.ts
1451
+ function isEnabledValidComposeHealthcheck(value) {
1452
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1453
+ const health = value;
1454
+ if (health.disable === true) return false;
1455
+ const test = health.test;
1456
+ if (typeof test === "string") return test.trim().length > 0 && !/^NONE$/i.test(test.trim());
1457
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
1458
+ const type = test[0]?.toUpperCase();
1459
+ if (type !== "CMD" && type !== "CMD-SHELL") return false;
1460
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
1278
1461
  }
1279
1462
 
1280
- // src/core/composition/composeDependsOn.ts
1281
- function normalizeComposeDependsOn(value) {
1282
- const entries2 = Array.isArray(value) ? value.filter((item) => typeof item === "string").map((name) => [name, {}]) : value && typeof value === "object" ? Object.entries(value) : [];
1283
- return Object.fromEntries(entries2.map(([name, options]) => [
1284
- name,
1285
- {
1286
- ...options && typeof options === "object" && !Array.isArray(options) ? options : {},
1287
- condition: "service_healthy"
1288
- }
1289
- ]));
1290
- }
1291
- function enforceHealthyDependsOn(document) {
1292
- for (const service of Object.values(document.services ?? {})) {
1293
- if (service.depends_on === void 0) continue;
1294
- service.depends_on = normalizeComposeDependsOn(service.depends_on);
1295
- }
1296
- }
1297
-
1298
- // src/core/composition/dependencyLifecycle.ts
1299
- function healthyMerge(target, owners) {
1300
- const current = normalizeComposeDependsOn(target.depends_on);
1301
- for (const owner of owners) {
1302
- const old = current[owner];
1303
- current[owner] = { ...old && typeof old === "object" ? old : {}, condition: "service_healthy" };
1304
- }
1305
- target.depends_on = current;
1306
- }
1307
- function applyDependencyLifecycle(app, materialized, effectiveBuild) {
1308
- const appOwners = /* @__PURE__ */ new Set();
1309
- for (const dep of Object.values(materialized)) for (const owner of dep.endpointOwners) appOwners.add(owner);
1310
- healthyMerge(app, appOwners);
1311
- for (const [key, dep] of Object.entries(materialized)) {
1312
- const config = effectiveBuild.dependencies[key];
1313
- if (!config) continue;
1314
- for (const raw of config.dependsOn) {
1315
- const match = DEPENDENCY_REFERENCE_PATTERN.exec(raw);
1316
- if (!match) continue;
1317
- const target = materialized[match[1]];
1318
- if (!target) continue;
1319
- for (const sourceOwner of dep.endpointOwners) {
1320
- const source = dep.compose.services[sourceOwner];
1321
- if (source) healthyMerge(source, target.endpointOwners);
1463
+ // src/core/composition/validateServiceCompose.ts
1464
+ function validateServiceCompose(name, declaration, document, context) {
1465
+ const fail4 = (configPath, reason, value) => {
1466
+ throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: context.composition, referencedObject: name, reason, value });
1467
+ };
1468
+ if (document.include !== void 0) fail4("include", "Compose include is unsupported for atomic service implementations");
1469
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: context.composition });
1470
+ const services2 = document.services ?? {};
1471
+ if (!Object.keys(services2).length) fail4("services", "Ordinary service Compose must define services");
1472
+ for (const [key, svc] of Object.entries(services2)) {
1473
+ if (svc.profiles !== void 0 || svc.extends !== void 0) fail4(`services.${key}`, "Compose profiles and extends are unsupported for atomic service implementations");
1474
+ if (svc.ports !== void 0 || svc.network_mode === "host" || svc.container_name !== void 0 || svc.privileged === true) fail4(`services.${key}`, "Service cannot own host ports, host networking, container_name or privileged mode");
1475
+ for (const volume of Array.isArray(svc.volumes) ? svc.volumes : []) {
1476
+ const mount = parseVolume(volume);
1477
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) fail4(`services.${key}.volumes`, "host root bind mounts are forbidden");
1478
+ }
1479
+ const references = [];
1480
+ if (Array.isArray(svc.depends_on)) references.push(...svc.depends_on.filter((value) => typeof value === "string"));
1481
+ else if (svc.depends_on && typeof svc.depends_on === "object") references.push(...Object.keys(svc.depends_on));
1482
+ if (Array.isArray(svc.links)) references.push(...svc.links.filter((value) => typeof value === "string").map((value) => value.split(":")[0]));
1483
+ if (Array.isArray(svc.volumes_from)) references.push(...svc.volumes_from.filter((value) => typeof value === "string").map((value) => value.split(":")[0]));
1484
+ for (const prop of ["network_mode", "ipc", "pid"]) {
1485
+ const raw = svc[prop];
1486
+ if (typeof raw === "string" && raw.startsWith("service:")) references.push(raw.slice(8));
1487
+ }
1488
+ for (const target of references) if (!services2[target]) fail4(`services.${key}`, `internal service reference ${target} does not exist`);
1489
+ }
1490
+ const endpoints = declaration.endpoints;
1491
+ const declarationOrigin = declaration.origin ?? context.declarationOrigin;
1492
+ const failDeclaration = (configPath, reason, value) => {
1493
+ if (declarationOrigin) throw new ConfigError({ sourceFile: declarationOrigin.sourceFile, configPath: `${declarationOrigin.configPath}.${configPath}`, stage: context.stage, composition: context.composition, referencedObject: name, reason, value });
1494
+ return fail4(configPath, reason, value);
1495
+ };
1496
+ let representative;
1497
+ if (Object.keys(endpoints).length) {
1498
+ const primary = Object.values(endpoints).find((endpoint) => endpoint.primary);
1499
+ representative = primary.service;
1500
+ if (declaration.service && declaration.service !== representative) failDeclaration("service", "top-level service must equal primary endpoint owner", declaration.service);
1501
+ } else {
1502
+ if (!declaration.service) failDeclaration("service", "endpoint-less service requires service");
1503
+ representative = declaration.service;
1504
+ }
1505
+ if (!services2[representative]) failDeclaration("service", "lifecycle representative does not exist", representative);
1506
+ for (const [endpoint, definition] of Object.entries(endpoints)) {
1507
+ if (!services2[definition.service]) failDeclaration(`endpoints.${endpoint}.service`, "endpoint owner does not exist", definition.service);
1508
+ if (services2[definition.service].network_mode !== void 0) fail4(`services.${definition.service}.network_mode`, "endpoint owner cannot use network_mode");
1509
+ }
1510
+ if (context.healthRequired) {
1511
+ const health = services2[representative].healthcheck;
1512
+ if (health === void 0 || health && typeof health === "object" && !Array.isArray(health) && health.test === void 0 && health.disable !== true) context.deferHealth?.(representative);
1513
+ else if (!isEnabledValidComposeHealthcheck(health)) fail4(`services.${representative}.healthcheck`, "requires a valid healthcheck");
1514
+ }
1515
+ if (context.prerequisite && services2[representative].restart !== void 0 && services2[representative].restart !== "no") fail4(`services.${representative}.restart`, "prerequisite cannot have a restart policy");
1516
+ assertComposeLifecycleAcyclic(services2, { sourceFile: context.composePath, stage: context.stage, composition: context.composition });
1517
+ return representative;
1518
+ }
1519
+ function readDotenvValues(file) {
1520
+ if (!fs.existsSync(file)) return {};
1521
+ const source = fs.readFileSync(file, "utf8"), result = {};
1522
+ let offset = 0;
1523
+ while (offset < source.length) {
1524
+ const start = offset;
1525
+ while (offset < source.length && source[offset] !== "\n") offset++;
1526
+ let line = source.slice(start, offset).replace(/\r$/, "");
1527
+ offset++;
1528
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[:=]\s*(.*)$/.exec(line);
1529
+ if (!match) continue;
1530
+ const key = match[1];
1531
+ let value = match[2];
1532
+ if (value.startsWith("'") || value.startsWith('"')) {
1533
+ const quote = value[0];
1534
+ value = value.slice(1);
1535
+ const closingQuote = () => {
1536
+ for (let index = 0; index < value.length; index++) {
1537
+ if (value[index] !== quote) continue;
1538
+ if (quote === "'") return index;
1539
+ let backslashes = 0;
1540
+ for (let cursor = index - 1; cursor >= 0 && value[cursor] === "\\"; cursor--) backslashes++;
1541
+ if (backslashes % 2 === 0) return index;
1542
+ }
1543
+ return -1;
1544
+ };
1545
+ let end = closingQuote();
1546
+ while (end < 0 && offset < source.length) {
1547
+ const nextStart = offset;
1548
+ while (offset < source.length && source[offset] !== "\n") offset++;
1549
+ value += "\n" + source.slice(nextStart, offset).replace(/\r$/, "");
1550
+ offset++;
1551
+ end = closingQuote();
1322
1552
  }
1323
- }
1553
+ if (end >= 0) value = value.slice(0, end);
1554
+ if (quote === '"') value = value.replace(/\\([nrt"\\])/g, (_all, char) => char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? " " : char);
1555
+ } else value = value.replace(/\s+#.*$/, "").trim();
1556
+ result[key] = value;
1324
1557
  }
1558
+ return result;
1325
1559
  }
1326
1560
 
1327
- // src/core/composition/serviceEndpoints.ts
1328
- function buildStandaloneAppEndpoints(build, stage, host = "app") {
1329
- const out = {};
1330
- for (const [name, e] of Object.entries(build.app.endpoints)) out[name] = { logicalPath: `app.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: e.publicPort !== void 0 };
1331
- return out;
1332
- }
1333
- function buildStandaloneDependencyEndpoints(key, build, serviceNames, materialized) {
1334
- const out = {};
1335
- for (const [name, e] of Object.entries(build.dependencies[key]?.endpoints ?? {})) {
1336
- const host = serviceNames.get(e.service) ?? e.service;
1337
- out[name] = { logicalPath: `dependencies.${key}.endpoints.${name}`, networkHost: host, networkPort: e.port, ...e.scheme ? { scheme: e.scheme } : {}, ...materialized && e.publicPort !== void 0 ? { publicHost: PUBLIC_HOST } : {}, effectivelyPublished: materialized && e.publicPort !== void 0 };
1338
- }
1339
- return out;
1340
- }
1341
-
1342
- // src/core/composition/compileServiceComposition.ts
1343
- function getExecutionProfile(stage, full) {
1344
- switch (stage) {
1345
- case "dev":
1346
- return { configStage: "dev", envStage: "dev", appTarget: "dev", execMode: "dev", infraMode: full ? "integrated" : "isolated", attachTester: false };
1347
- case "prod":
1348
- return { configStage: "prod", envStage: "prod", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: false };
1349
- case "test":
1350
- return { configStage: "test", envStage: "test", appTarget: "test", execMode: "test", infraMode: "isolated", attachTester: false };
1351
- case "e2e":
1352
- return { configStage: "e2e", envStage: "e2e", appTarget: "prod", execMode: "prod", infraMode: "integrated", attachTester: true, testerTarget: "test-e2e" };
1561
+ // src/core/composition/compileTester.ts
1562
+ function compileTester(input) {
1563
+ const { tester, origin, stage: stage2, composition } = input;
1564
+ const file = resolveInsideProject(origin.projectDir, tester.compose, { sourceFile: origin.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2 });
1565
+ const raw = loadComposeDocument(file, { sourceFile: origin.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2, composition });
1566
+ if (!raw.services?.[tester.service]) throw new ConfigError({ sourceFile: input.serviceOrigin?.sourceFile ?? origin.sourceFile, configPath: input.serviceOrigin?.configPath ?? `${origin.configPath}.service`, stage: stage2, composition, referencedObject: tester.service, reason: "Selected tester service does not exist" });
1567
+ if (raw.include !== void 0) throw new ConfigError({ sourceFile: file, configPath: "include", stage: stage2, composition, reason: "Tester Compose include is unsupported" });
1568
+ validateComposeResourceReferences(raw, { sourceFile: file, stage: stage2, composition });
1569
+ assertComposeLifecycleAcyclic(raw.services, { sourceFile: file, stage: stage2, composition });
1570
+ for (const [name, service] of Object.entries(raw.services)) {
1571
+ if (service.ports !== void 0 || service.container_name !== void 0 || service.privileged === true) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage: stage2, composition, reason: "Tester Compose cannot own ports, fixed container names or privileged mode" });
1572
+ for (const volume of Array.isArray(service.volumes) ? service.volumes : []) {
1573
+ const mount = parseVolume(volume);
1574
+ if (mount?.type === "bind" && mount.source && isHostFilesystemRoot(mount.source)) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.volumes`, stage: stage2, composition, reason: "host root bind mounts are forbidden" });
1575
+ }
1576
+ assertNoBuilderOwnedEnvKeys(normalizeComposeEnvironment(service.environment, `services.${name}.environment`), ["EXEC_MODE", "INFRA_MODE"], { sourceFile: file, configPath: `services.${name}.environment`, stage: stage2, composition });
1577
+ const files = Array.isArray(service.env_file) ? service.env_file : service.env_file ? [service.env_file] : [];
1578
+ for (const item of files) {
1579
+ const candidate = typeof item === "string" ? item : item && typeof item === "object" ? item.path : void 0;
1580
+ if (typeof candidate === "string") assertDotenvDoesNotDefineKeys(path.resolve(path.dirname(file), candidate), ["EXEC_MODE", "INFRA_MODE"], { configPath: `services.${name}.env_file`, stage: stage2, composition });
1581
+ }
1582
+ }
1583
+ validateMaterializedComposeFiles(raw, file, stage2, { composition });
1584
+ validateMaterializedComposeBuildInputs(raw, file, stage2, composition);
1585
+ for (const [key, value] of Object.entries(tester.env ?? {})) {
1586
+ const leaf = input.envOrigins?.get(key) ?? { ...origin, configPath: `${origin.configPath}.env.${key}` };
1587
+ assertNoBuilderOwnedEnvKeys({ [key]: value }, ["EXEC_MODE", "INFRA_MODE"], { sourceFile: leaf.sourceFile, configPath: leaf.configPath.slice(0, leaf.configPath.lastIndexOf(".")), stage: stage2, composition });
1588
+ }
1589
+ const dotenv = path.join(origin.projectDir, ".env.e2e-tester");
1590
+ assertDotenvDoesNotDefineKeys(dotenv, ["EXEC_MODE", "INFRA_MODE"], { configPath: ".env.e2e-tester", stage: stage2, composition });
1591
+ const rebased = rebaseComposePaths(raw, file, input.projectDir);
1592
+ const named = namespaceDependencyCompose({ dependencyKey: "tester", namespacePrefix: "tester", document: rebased, allocator: input.allocator, identityPrefix: JSON.stringify([composition, "tester"]) });
1593
+ const runner = named.serviceNameMap.get(tester.service), selected = named.document.services[runner];
1594
+ for (const [name, service] of Object.entries(named.document.services)) {
1595
+ if (name === runner) continue;
1596
+ if (service.network_mode === void 0) service.networks = { ...normalizeNetworks(service.networks), builder: null };
1597
+ }
1598
+ if (raw.services[tester.service].network_mode === void 0 && raw.services[tester.service].networks === void 0) {
1599
+ selected.network_mode = "host";
1600
+ delete selected.networks;
1601
+ } else if (selected.network_mode === void 0) selected.networks = { ...normalizeNetworks(selected.networks), builder: null };
1602
+ const defaults = normalizeComposeEnvironment(selected.environment, `services.${tester.service}.environment`);
1603
+ const resolved = {};
1604
+ for (const [key, value] of Object.entries(tester.env ?? {})) {
1605
+ const leaf = input.envOrigins?.get(key) ?? { ...origin, configPath: `${origin.configPath}.env.${key}` };
1606
+ resolved[key] = interpolateBuilderReferences(value, { graph: input.graph, endpoints: input.endpoints, origin: leaf, stage: stage2, composition }).replace(/\$/g, "$$$$");
1607
+ }
1608
+ selected.env_file = [...Array.isArray(selected.env_file) ? selected.env_file : selected.env_file ? [selected.env_file] : [], { path: path.relative(input.projectDir, dotenv).replace(/\\/g, "/"), required: false }];
1609
+ const testerDotenv = Object.fromEntries(Object.entries(readDotenvValues(dotenv)).map(([key, value]) => [key, value.replace(/\$/g, "$$$$")]));
1610
+ selected.environment = { ...defaults, ...testerDotenv, ...resolved };
1611
+ return { document: named.document, runner, serviceNames: Object.keys(named.document.services) };
1612
+ }
1613
+
1614
+ // src/core/composition/compileGraphComposition.ts
1615
+ var BUILDER_OWNER_LABEL = "dev.solidstack.builder.owned";
1616
+ var unique = (array) => [...new Set(array)];
1617
+ var copyOrigin = (origin, root) => root ? { ...origin, meshRoot: root } : origin;
1618
+ function makeGraph(input) {
1619
+ const nodes = /* @__PURE__ */ new Map();
1620
+ const roots = [];
1621
+ for (const [rootKey, build] of input.instances) {
1622
+ const root = rootKey || void 0;
1623
+ roots.push(nodeId(root, "main"));
1624
+ for (const [name, declaration] of Object.entries(build.services)) {
1625
+ if (name === "tester") continue;
1626
+ const id = nodeId(root, name), origin = copyOrigin(build.origins.get(name), root);
1627
+ nodes.set(id, { id, kind: name === "main" ? "main" : "ordinary", projectDir: build.projectDir, sourceService: name, ...root ? { meshRoot: root } : {}, declaration, envLayers: [], origin, envOrigins: new Map([...build.envOrigins.get(name) ?? []].map(([key, value]) => [key, copyOrigin(value, root)])), requisiteOrigins: new Map([...build.requisiteOrigins.get(name) ?? []].map(([key, value]) => [key, copyOrigin(value, root)])) });
1628
+ }
1629
+ }
1630
+ input.mesh?.tester ?? input.instances.get("")?.services.tester;
1631
+ input.mesh ? { sourceFile: input.mesh.sourceFile, projectDir: input.projectDir} : { sourceFile: input.instances.get("").sourceFile, projectDir: input.projectDir};
1632
+ const declared = buildDeclaredGraph({ nodes, roots, stage: input.stage, composition: input.composition });
1633
+ return selectReachableGraph(declared, { infraMode: executionProfile(input.stage, input.composition, input.full).infraMode, stage: input.stage });
1634
+ }
1635
+ function mergeDocument(target, fragment, origin, stage2) {
1636
+ for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
1637
+ const values = fragment[section];
1638
+ if (!values) continue;
1639
+ const output = target[section] ??= {};
1640
+ for (const [key, value] of Object.entries(values)) {
1641
+ if (key in output) throw new ConfigError({ sourceFile: origin.sourceFile, configPath: `${origin.configPath}.${section}.${key}`, stage: stage2, composition: origin.scope === "mesh" ? "mesh" : "service", reason: "Generated Compose identity collision" });
1642
+ output[key] = value;
1643
+ }
1353
1644
  }
1354
1645
  }
1355
- function mergeDocument(target, source, context) {
1356
- for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
1357
- const src = source[section];
1358
- if (!src) continue;
1359
- const dst = target[section] ??= {};
1360
- for (const [key, value] of Object.entries(src)) {
1361
- if (key in dst) throw new ConfigError({ ...context, configPath: `${context.configPath}.${section}.${key}`, value: key, reason: "Internal Compose namespace collision" });
1362
- dst[key] = value;
1646
+ function withBuilderNetwork(service) {
1647
+ if (service.network_mode !== void 0) return;
1648
+ service.networks = { ...normalizeNetworks(service.networks), builder: null };
1649
+ }
1650
+ function markOwned(value) {
1651
+ const current = value.labels;
1652
+ const labels = Array.isArray(current) ? Object.fromEntries(current.filter((item) => typeof item === "string").map((item) => {
1653
+ const index = item.indexOf("=");
1654
+ return index < 0 ? [item, ""] : [item.slice(0, index), item.slice(index + 1)];
1655
+ })) : current && typeof current === "object" ? { ...current } : {};
1656
+ labels[BUILDER_OWNER_LABEL] = "true";
1657
+ value.labels = labels;
1658
+ }
1659
+ function selectedOverride(build, name) {
1660
+ let result;
1661
+ for (const layer of build.layers) {
1662
+ const patch = layer.services[name];
1663
+ const value = patch?.["override-compose"];
1664
+ if (typeof value === "string") {
1665
+ const base = layer.origin.configPath.endsWith(`.${name}`) ? layer.origin.configPath : `${layer.origin.configPath}.${name}`;
1666
+ result = { path: value, origin: { ...layer.origin, configPath: `${base}.override-compose` } };
1363
1667
  }
1364
1668
  }
1669
+ return result;
1365
1670
  }
1366
- function getTemplateSeed(stage, meshMode) {
1671
+ function mainSeed(stage2) {
1367
1672
  const base = parse(fs.readFileSync(getDockerComposeTemplate("docker-compose.base.yml"), "utf8"));
1368
- const stageName = stage === "e2e" ? "e2e" : stage;
1369
- const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stageName}.yml`), "utf8"));
1370
- const merged = { ...base, services: { ...base.services ?? {} } };
1371
- for (const [name, svc] of Object.entries(overlay.services ?? {})) merged.services[name] = { ...merged.services[name] ?? {}, ...svc, build: { ...merged.services[name]?.build ?? {}, ...svc.build ?? {} } };
1372
- if (meshMode) delete merged.services.tester;
1373
- return merged;
1374
- }
1375
- function resolveEnv(input, registry, baseContext) {
1376
- const out = {};
1377
- for (const [key, value] of Object.entries(input)) {
1378
- if (value === null) {
1379
- out[key] = null;
1380
- continue;
1381
- }
1382
- const context = { ...baseContext, configPath: `${baseContext.configPath}.${key}` };
1383
- out[key] = interpolateBuilderReferences(value, "build", registry, context).replace(/\$/g, "$$$$");
1384
- }
1385
- return out;
1386
- }
1387
- function addPorts(service, endpointPairs, sourceFile, stage) {
1388
- for (const [ep, hostPort] of endpointPairs) {
1389
- const ports = Array.isArray(service.ports) ? service.ports : [];
1390
- 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" });
1391
- ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
1392
- service.ports = ports;
1393
- }
1394
- }
1395
- function compileServiceComposition(stage, projectDir, options = {}) {
1396
- const root = resolveProjectDir(projectDir), buildPath = path.join(root, "build.json"), raw = getBuildJson(root), effective = resolveBuildStage(raw, stage, buildPath), profile = getExecutionProfile(stage, Boolean(options.full));
1397
- resolveApplicationDockerfile(root, raw.dockerfile ?? "Dockerfile", stage);
1398
- const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1399
- const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1400
- const projectName = deriveProjectName(rawName, stage);
1401
- const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1402
- const namespaced = {};
1403
- for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1404
- const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1405
- const rawDocument = loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1406
- const document = rebaseComposePaths(rawDocument, sourcePath, options.composeOutputDir ?? root);
1407
- validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1408
- if (Object.keys(dep.endpoints).length) {
1409
- 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]) });
1410
- namespaced[key] = { doc: ns.document, raw: rawDocument, map: ns.serviceNameMap, source: sourcePath };
1411
- }
1412
- }
1413
- const materialized = {};
1414
- const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
1415
- let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
1416
- if (profile.infraMode === "integrated") for (const [key, entry] of Object.entries(namespaced)) {
1417
- if (options.suppressDependencies?.has(key)) continue;
1418
- validateMaterializedComposeFiles(entry.raw, entry.source, stage);
1419
- validateMaterializedComposeBuildInputs(entry.raw, entry.source, stage, "service");
1420
- const dep = effective.dependencies[key];
1421
- const item = structuredClone(entry.doc);
1422
- mergeDocument(compose, item, { sourceFile: entry.source, configPath: `dependencies.${key}.compose`, stage, composition: "service" });
1423
- const endpointOwnerMap = /* @__PURE__ */ new Map();
1424
- for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1425
- const endpointOwners = new Set(endpointOwnerMap.values());
1426
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1427
- }
1428
- const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1429
- const depEndpoints = {};
1430
- for (const [key, dep] of Object.entries(effective.dependencies)) {
1431
- depEndpoints[key] = buildStandaloneDependencyEndpoints(key, effective, namespaced[key]?.map ?? /* @__PURE__ */ new Map(), Boolean(materialized[key]));
1432
- if (options.meshMode) for (const ep of Object.values(depEndpoints[key])) {
1433
- ep.effectivelyPublished = false;
1434
- delete ep.publicHost;
1435
- delete ep.publicPort;
1436
- }
1437
- }
1438
- if (options.meshMode) for (const ep of Object.values(appEndpoints)) {
1439
- ep.effectivelyPublished = false;
1440
- delete ep.publicHost;
1441
- delete ep.publicPort;
1442
- }
1443
- const intents = [];
1444
- if (!options.meshMode) {
1445
- for (const [name, e] of Object.entries(effective.app.endpoints).sort(([a], [b]) => a.localeCompare(b))) if (e.publicPort !== void 0) intents.push({ logicalPath: `app.endpoints.${name}`, requested: e.publicPort });
1446
- for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) if (materialized[key]) {
1447
- 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 });
1448
- }
1449
- }
1450
- const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode), { sourceFile: buildPath, composition: "service" });
1451
- for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
1452
- ep.publicHost = PUBLIC_HOST;
1453
- ep.publicPort = allocation.get(ep.logicalPath);
1454
- ep.effectivelyPublished = true;
1455
- }
1456
- for (const [key, eps] of Object.entries(depEndpoints)) for (const [name, ep] of Object.entries(eps)) if (allocation.has(ep.logicalPath)) {
1457
- ep.publicHost = PUBLIC_HOST;
1458
- ep.publicPort = allocation.get(ep.logicalPath);
1459
- ep.effectivelyPublished = true;
1460
- }
1461
- const registry = (ref, context) => {
1462
- if (ref.target === "app") {
1463
- const ep2 = appEndpoints[ref.endpoint];
1464
- if (!ep2) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
1465
- return resolveEndpointProperty(ep2, ref.property, { ...context, referencedObject: ref.raw });
1466
- }
1467
- const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
1468
- if (!ep) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
1469
- return resolveEndpointProperty(ep, ref.property, { ...context, referencedObject: ref.raw });
1470
- };
1471
- for (const [key, dep] of Object.entries(effective.dependencies)) {
1472
- const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, { sourceFile: buildPath, configPath: `dependencies.${key}.env`, stage, composition: "service" });
1473
- for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1474
- }
1475
- const appEnvironmentLayers = [];
1476
- for (const layer of effective.layers) {
1477
- if (Object.keys(layer.appEnv).length) {
1478
- const configPath = layer.stage === "base" ? "app.env" : `${layer.stage}.app.env`;
1479
- assertNoBuilderOwnedEnvKeys(layer.appEnv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { sourceFile: buildPath, configPath, stage, composition: "service" });
1480
- appEnvironmentLayers.push({ kind: "build-json", stage: layer.stage, configPath, values: { ...layer.appEnv } });
1481
- }
1482
- }
1483
- const resolveAppLayers = () => {
1484
- const result = {};
1485
- const laterKeys = new Set(Object.keys(options.externalAppEnv ?? {}));
1486
- for (const [key, layer] of selectAppEnvironmentEntries(appEnvironmentLayers, laterKeys)) {
1487
- if (layer.kind === "build-json") {
1488
- const context = {
1489
- sourceFile: buildPath,
1490
- configPath: layer.configPath,
1491
- stage,
1492
- composition: "service"
1493
- };
1494
- result[key] = resolveEnv({ [key]: layer.values[key] }, registry, context)[key];
1495
- } else {
1496
- result[key] = layer.values[key];
1673
+ const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stage2}.yml`), "utf8"));
1674
+ return { ...base.services.main, ...overlay.services.main, build: { ...base.services.main?.build, ...overlay.services.main?.build } };
1675
+ }
1676
+ function portKey(id, endpoint) {
1677
+ return `${displayNode(id)}.endpoints.${endpoint}`;
1678
+ }
1679
+ function addPort(service, endpoint) {
1680
+ service.ports = [...service.ports ?? [], { target: endpoint.networkPort, published: endpoint.publicPort, host_ip: "127.0.0.1", protocol: "tcp" }];
1681
+ }
1682
+ function resolveJsonEnv(node, graph, endpoints, stage2, composition, shadowed) {
1683
+ const output = {};
1684
+ for (const [key, value] of Object.entries(node.declaration.env)) {
1685
+ if (shadowed.has(key)) continue;
1686
+ const origin = node.envOrigins.get(key) ?? node.origin;
1687
+ output[key] = interpolateBuilderReferences(value, { graph, endpoints, consumer: node.id, origin, stage: stage2, composition }).replace(/\$/g, "$$$$");
1688
+ }
1689
+ return output;
1690
+ }
1691
+ function validateJsonEnv(node, graph, endpoints, stage2, composition, shadowed) {
1692
+ resolveJsonEnv(node, graph, endpoints, stage2, composition, shadowed);
1693
+ }
1694
+ function validateReserved(node, keys, stage2, composition) {
1695
+ for (const key of keys) if (key in node.declaration.env) {
1696
+ const origin = node.envOrigins.get(key) ?? node.origin;
1697
+ assertNoBuilderOwnedEnvKeys({ [key]: node.declaration.env[key] }, [key], { sourceFile: origin.sourceFile, configPath: origin.configPath.replace(/\.env\.[^.]+$/, ".env"), stage: stage2, composition });
1698
+ }
1699
+ }
1700
+ function compileGraphComposition(input) {
1701
+ const profile = executionProfile(input.stage, input.composition, input.full), graph = makeGraph(input), allocator = new GeneratedComposeNameAllocator(["builder"]);
1702
+ const projectName = deriveProjectName(input.name, input.stage, input.projectDir), compose = { name: projectName, services: {}, networks: { builder: { driver: "bridge" } } };
1703
+ const mainServiceNames = /* @__PURE__ */ new Map(), modules = /* @__PURE__ */ new Map(), runtimeServiceNames = [], deferredHealthChecks = [];
1704
+ const mainOverrideEnv = /* @__PURE__ */ new Map();
1705
+ for (const [id, node] of [...graph.nodes].sort(([a], [b]) => a.localeCompare(b))) {
1706
+ if (node.kind === "main") {
1707
+ resolveApplicationDockerfile(node.projectDir, "Dockerfile", input.stage);
1708
+ assertMainDockerfileContract(node.projectDir, profile.mainTarget);
1709
+ const serviceName = allocator.allocate(JSON.stringify([id, "main"]), node.meshRoot ?? "main");
1710
+ mainServiceNames.set(id, serviceName);
1711
+ const service = mainSeed(input.stage);
1712
+ const build = service.build;
1713
+ build.context = path.relative(input.projectDir, node.projectDir).replace(/\\/g, "/") || ".";
1714
+ build.dockerfile = "Dockerfile";
1715
+ build.target = profile.mainTarget;
1716
+ service.build = build;
1717
+ service.env_file = [{ path: path.relative(input.projectDir, path.join(node.projectDir, `.env.${profile.envStage}`)).replace(/\\/g, "/"), required: false }];
1718
+ const selected = selectedOverride(input.instances.get(node.meshRoot ?? ""), "main");
1719
+ if (selected) {
1720
+ const file = resolveInsideProject(selected.origin.projectDir, selected.path, { sourceFile: selected.origin.sourceFile, configPath: selected.origin.configPath, stage: input.stage });
1721
+ const raw = loadComposeDocument(file, { sourceFile: selected.origin.sourceFile, configPath: selected.origin.configPath, stage: input.stage, composition: input.composition });
1722
+ const rebased = rebaseAppOverridePaths(raw, selected.origin.projectDir, input.projectDir);
1723
+ const prepared = validateAndPrepareMainOverride(rebased, { file, stage: input.stage, expectedBuildContext: String(build.context), buildContextBaseDir: input.projectDir, allocator, resourceNamespace: node.meshRoot ?? "main" });
1724
+ validateMaterializedComposeFiles(raw, file, input.stage, { baseDir: selected.origin.projectDir, composition: input.composition });
1725
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, selected.origin, input.stage);
1726
+ mainOverrideEnv.set(id, normalizeComposeEnvironment(prepared.main.environment, `${selected.origin.configPath}.services.main.environment`));
1727
+ const overlay = { ...prepared.main };
1728
+ delete overlay.environment;
1729
+ delete overlay.build;
1730
+ Object.assign(service, mergeMainOverride(service, overlay));
1731
+ if (prepared.main.build && typeof prepared.main.build === "object") Object.assign(service.build, { args: prepared.main.build.args });
1497
1732
  }
1498
- }
1499
- return result;
1500
- };
1501
- const runtimeDotenv = path.join(root, `.env.${profile.envStage}`);
1502
- assertDotenvDoesNotDefineKeys(runtimeDotenv, [EXEC_MODE_KEY, INFRA_MODE_KEY, ...getPrimaryEndpoint(effective.app.endpoints) ? [PORT_KEY] : []], { configPath: `.env.${profile.envStage}`, stage, composition: "service" });
1503
- const internal = { EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
1504
- const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
1505
- const outputDir = options.composeOutputDir ? path.resolve(options.composeOutputDir) : root;
1506
- const serviceContext = path.relative(outputDir, root).replace(/\\/g, "/") || ".";
1507
- appBuild.context = options.meshMode ? serviceContext : ".";
1508
- if (raw.dockerfile) appBuild.dockerfile = raw.dockerfile;
1509
- else delete appBuild.dockerfile;
1510
- appBuild.target = profile.appTarget;
1511
- app.build = appBuild;
1512
- app.env_file = [{ path: options.meshMode ? path.posix.join(serviceContext, `.env.${profile.envStage}`) : `.env.${profile.envStage}`, required: false }];
1513
- app.environment = { ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1514
- if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
1515
- for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]], buildPath, stage);
1516
- for (const [key, dependency] of Object.entries(materialized)) {
1517
- for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
1518
- const endpoint = depEndpoints[key][epName];
1519
- if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]], dependency.composePath, stage);
1520
- }
1521
- for (const owner of dependency.endpointOwners) {
1522
- const svc = compose.services[owner];
1523
- if (!options.meshMode && svc.networks !== void 0) {
1524
- const nets = svc.networks;
1525
- if (Array.isArray(nets)) {
1526
- if (!nets.includes("default")) nets.push("default");
1527
- } else if (nets && typeof nets === "object") nets.default = null;
1733
+ withBuilderNetwork(service);
1734
+ compose.services[serviceName] = service;
1735
+ runtimeServiceNames.push(serviceName);
1736
+ } else {
1737
+ const def = node.declaration;
1738
+ if (def.kind !== "ordinary") continue;
1739
+ const file = resolveInsideProject(node.projectDir, def.compose, { sourceFile: node.origin.sourceFile, configPath: `${node.origin.configPath}.compose`, stage: input.stage });
1740
+ const raw = loadComposeDocument(file, { sourceFile: node.origin.sourceFile, configPath: `${node.origin.configPath}.compose`, stage: input.stage, composition: input.composition });
1741
+ for (const [local, service] of Object.entries(raw.services ?? {})) {
1742
+ const envFiles = Array.isArray(service.env_file) ? service.env_file : service.env_file ? [service.env_file] : [];
1743
+ for (const item of envFiles) {
1744
+ const candidate = typeof item === "string" ? item : item && typeof item === "object" ? item.path : void 0;
1745
+ if (typeof candidate === "string") assertDotenvDoesNotDefineKeys(path.resolve(path.dirname(file), candidate), [EXEC_MODE_KEY, INFRA_MODE_KEY], { configPath: `services.${local}.env_file`, stage: input.stage, composition: input.composition });
1746
+ }
1747
+ }
1748
+ let deferredHealthRepresentative;
1749
+ const representative = validateServiceCompose(displayNode(id), def, raw, { composePath: file, stage: input.stage, composition: input.composition, declarationOrigin: node.origin, healthRequired: input.stage === "e2e" && graph.lifecycle.get(id) !== "prerequisite" || graph.edges.some((edge) => edge.target === id && edge.kind === "dependency"), prerequisite: graph.lifecycle.get(id) === "prerequisite", deferHealth: (name) => {
1750
+ deferredHealthRepresentative = name;
1751
+ } });
1752
+ validateMaterializedComposeFiles(raw, file, input.stage, { composition: input.composition });
1753
+ validateMaterializedComposeBuildInputs(raw, file, input.stage, input.composition);
1754
+ const rebased = rebaseComposePaths(raw, file, input.projectDir), prefix = node.meshRoot ? `svc--${node.meshRoot}--${node.sourceService}` : `svc--${node.sourceService}`;
1755
+ const named = namespaceDependencyCompose({ dependencyKey: displayNode(id), namespacePrefix: prefix, document: rebased, allocator, identityPrefix: id });
1756
+ if (deferredHealthRepresentative) {
1757
+ const serviceName = named.serviceNameMap.get(deferredHealthRepresentative), service = named.document.services[serviceName];
1758
+ const image = typeof service.image === "string" ? service.image : `${projectName}-${serviceName}`;
1759
+ if (service.build === void 0 && service.image === void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${deferredHealthRepresentative}.healthcheck`, stage: input.stage, composition: input.composition, reason: "Required healthcheck has no Compose declaration or inspectable image" });
1760
+ deferredHealthChecks.push({ serviceName, image, sourceFile: file, configPath: `services.${deferredHealthRepresentative}.healthcheck` });
1761
+ }
1762
+ for (const service of Object.values(named.document.services)) withBuilderNetwork(service);
1763
+ const endpointOwnerMap = /* @__PURE__ */ new Map();
1764
+ for (const [endpoint, value] of Object.entries(def.endpoints)) endpointOwnerMap.set(endpoint, named.serviceNameMap.get(value.service));
1765
+ const module = { nodeId: id, sourceFile: file, document: named.document, serviceNameMap: named.serviceNameMap, representative: named.serviceNameMap.get(representative), serviceNames: Object.keys(named.document.services), endpointOwnerMap };
1766
+ modules.set(id, module);
1767
+ mergeDocument(compose, named.document, node.origin, input.stage);
1768
+ runtimeServiceNames.push(...module.serviceNames);
1769
+ }
1770
+ }
1771
+ const endpoints = /* @__PURE__ */ new Map();
1772
+ for (const [id, node] of graph.nodes) {
1773
+ const records = {};
1774
+ for (const [name, definition] of Object.entries(node.declaration.endpoints)) {
1775
+ const owner = node.kind === "main" ? mainServiceNames.get(id) : modules.get(id).endpointOwnerMap.get(name);
1776
+ records[name] = { logicalPath: portKey(id, name), networkHost: owner, networkPort: definition.port, ...definition.scheme ? { scheme: definition.scheme } : {}, effectivelyPublished: false };
1777
+ }
1778
+ endpoints.set(id, records);
1779
+ }
1780
+ const publish = input.mesh ? new Map(Object.entries(input.mesh.services).map(([root, entry]) => [root, entry.publish])) : void 0;
1781
+ const publishOrigins = input.mesh ? new Map(Object.entries(input.mesh.services).flatMap(([root, entry]) => entry.publishOrigin ? [[root, entry.publishOrigin]] : [])) : void 0;
1782
+ const intents = resolvePublicationIntent(graph, input.stage, input.composition, publish, input.mesh?.sourceFile, publishOrigins);
1783
+ for (const item of intents) {
1784
+ const record = endpoints.get(item.nodeId)[item.endpoint];
1785
+ record.effectivelyPublished = true;
1786
+ record.publicHost = "127.0.0.1";
1787
+ record.publicPort = 1;
1788
+ }
1789
+ for (const [id, node] of graph.nodes) {
1790
+ const override = mainOverrideEnv.get(id) ?? {};
1791
+ const shadowed = new Set(node.kind === "main" ? Object.keys(override).filter((key) => node.envOrigins.get(key)?.scope !== "mesh") : []);
1792
+ validateJsonEnv(node, graph, endpoints, input.stage, input.composition, shadowed);
1793
+ }
1794
+ const tester = input.mesh?.tester ?? input.instances.get("")?.services.tester;
1795
+ const testerOrigin = input.mesh ? { sourceFile: input.mesh.sourceFile, configPath: "services.tester", projectDir: input.projectDir, scope: "mesh", layer: "base" } : { sourceFile: input.instances.get("").sourceFile, configPath: "services.tester", projectDir: input.projectDir, scope: "build", layer: "base" };
1796
+ const testerLayers = input.mesh ? input.mesh.testerLayers.map((layer) => ({ entry: layer.services.tester, origin: layer.origin })) : input.instances.get("").layers.map((layer) => ({ entry: layer.services.tester, origin: { ...layer.origin, configPath: `${layer.origin.configPath}.tester` } }));
1797
+ let serviceOrigin = { ...testerOrigin, configPath: `${testerOrigin.configPath}.service` };
1798
+ const testerEnvOrigins = /* @__PURE__ */ new Map();
1799
+ for (const layer of testerLayers) {
1800
+ const entry = layer.entry;
1801
+ if (!entry) continue;
1802
+ if (entry.service !== void 0) serviceOrigin = { ...layer.origin, configPath: `${layer.origin.configPath}.service` };
1803
+ for (const key of Object.keys(entry.env ?? {})) testerEnvOrigins.set(key, { ...layer.origin, configPath: `${layer.origin.configPath}.env.${key}` });
1804
+ }
1805
+ profile.attachTester ? compileTester({ tester, origin: testerOrigin, serviceOrigin, envOrigins: testerEnvOrigins, graph, endpoints, stage: input.stage, composition: input.composition, projectDir: input.projectDir, allocator}) : void 0;
1806
+ const allocations = allocateHostPorts(input.projectDir, input.stage, intents.map((item) => ({ logicalPath: item.logicalPath, requested: item.requestedPort })), Boolean(input.validationMode), { sourceFile: input.mesh?.sourceFile ?? input.instances.get("").sourceFile, composition: input.composition });
1807
+ for (const item of intents) {
1808
+ const record = endpoints.get(item.nodeId)[item.endpoint];
1809
+ record.publicPort = allocations.get(item.logicalPath);
1810
+ const owner = graph.nodes.get(item.nodeId).kind === "main" ? mainServiceNames.get(item.nodeId) : modules.get(item.nodeId).endpointOwnerMap.get(item.endpoint);
1811
+ addPort(compose.services[owner], record);
1812
+ }
1813
+ for (const [id, node] of graph.nodes) {
1814
+ const primary = Object.values(node.declaration.endpoints).find((endpoint) => endpoint.primary);
1815
+ const reserved = node.kind === "main" ? [EXEC_MODE_KEY, INFRA_MODE_KEY, ...primary ? [PORT_KEY] : []] : [EXEC_MODE_KEY, INFRA_MODE_KEY];
1816
+ validateReserved(node, reserved, input.stage, input.composition);
1817
+ if (node.kind === "main") {
1818
+ const service = compose.services[mainServiceNames.get(id)], override = mainOverrideEnv.get(id) ?? {};
1819
+ assertNoBuilderOwnedEnvKeys(override, reserved, { sourceFile: node.origin.sourceFile, configPath: "services.main.override-compose.environment", stage: input.stage, composition: input.composition });
1820
+ assertDotenvDoesNotDefineKeys(path.join(node.projectDir, `.env.${profile.envStage}`), reserved, { configPath: `.env.${profile.envStage}`, stage: input.stage, composition: input.composition });
1821
+ const buildEnv = resolveJsonEnv(node, graph, endpoints, input.stage, input.composition, new Set(Object.keys(override).filter((key) => node.envOrigins.get(key)?.scope !== "mesh")));
1822
+ const sourceEnv = Object.fromEntries(Object.entries(buildEnv).filter(([key]) => node.envOrigins.get(key)?.scope !== "mesh"));
1823
+ const meshEnv = Object.fromEntries(Object.entries(buildEnv).filter(([key]) => node.envOrigins.get(key)?.scope === "mesh"));
1824
+ service.environment = { ...sourceEnv, ...override, ...meshEnv, EXEC_MODE: profile.execMode, INFRA_MODE: profile.infraMode, ...primary ? { PORT: String(primary.port) } : {} };
1825
+ } else {
1826
+ const module = modules.get(id);
1827
+ for (const name of module.serviceNames) {
1828
+ const service = compose.services[name];
1829
+ const defaults = normalizeComposeEnvironment(service.environment, `services.${name}.environment`);
1830
+ assertNoBuilderOwnedEnvKeys(defaults, [EXEC_MODE_KEY, INFRA_MODE_KEY], { sourceFile: module.sourceFile, configPath: `services.${name}.environment`, stage: input.stage, composition: input.composition });
1831
+ service.environment = { ...defaults, ...resolveJsonEnv(node, graph, endpoints, input.stage, input.composition, /* @__PURE__ */ new Set()) };
1528
1832
  }
1529
1833
  }
1530
- for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
1531
1834
  }
1532
- for (const layer of effective.layers) {
1533
- if (!layer.overrideCompose) continue;
1534
- const overridePath = resolveInsideProject(root, layer.overrideCompose, {
1535
- sourceFile: buildPath,
1536
- configPath: `${layer.stage}.override-compose`,
1537
- stage
1538
- });
1539
- const loadedOverride = loadComposeDocument(overridePath, {
1540
- sourceFile: buildPath,
1541
- configPath: `${layer.stage}.override-compose`,
1542
- stage,
1543
- composition: "service"
1544
- });
1545
- const overrideDocument = rebaseAppOverridePaths(loadedOverride, root, outputDir);
1546
- const prepared = validateAndPrepareAppOverride(overrideDocument, {
1547
- file: overridePath,
1548
- stage: layer.stage === "base" ? stage : layer.stage,
1549
- expectedBuildContext: String(appBuild.context),
1550
- buildContextBaseDir: outputDir,
1551
- allocator: nameAllocator,
1552
- resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1553
- });
1554
- validateMaterializedComposeFiles(loadedOverride, overridePath, stage, {
1555
- baseDir: root,
1556
- composition: "service"
1557
- });
1558
- 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" });
1559
- const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, `${layer.stage}.override-compose.services.app.environment`);
1560
- const overrideEnv = rawOverrideEnv;
1561
- 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" });
1562
- const overrideStage = layer.stage === "base" ? stage : layer.stage;
1563
- const stageOrder = { base: 0, dev: 1, prod: 1, test: 1, e2e: 2 };
1564
- let insertAt = appEnvironmentLayers.findIndex((item) => (stageOrder[item.stage] ?? 0) > (stageOrder[overrideStage] ?? 0));
1565
- if (insertAt < 0) insertAt = appEnvironmentLayers.length;
1566
- appEnvironmentLayers.splice(insertAt, 0, { kind: "override-compose", stage: overrideStage, sourceFile: overridePath, configPath: `${layer.stage}.override-compose.services.app.environment`, values: overrideEnv });
1567
- const preparedApp = { ...prepared.app };
1568
- delete preparedApp.environment;
1569
- delete preparedApp.build;
1570
- const merged = mergeAppOverride(app, preparedApp);
1571
- merged.environment = { ...app.environment, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1572
- const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
1573
- if (overrideBuild.args !== void 0) {
1574
- const current = appBuild.args, incoming = overrideBuild.args;
1575
- appBuild.args = current && incoming && typeof current === "object" && typeof incoming === "object" && !Array.isArray(current) && !Array.isArray(incoming) ? { ...current, ...incoming } : incoming;
1576
- }
1577
- merged.build = appBuild;
1578
- merged.env_file = app.env_file;
1579
- merged.depends_on = app.depends_on;
1580
- merged.networks = { ...!options.meshMode ? { default: null } : {}, ...normalizeNetworks(app.networks), ...normalizeNetworks(prepared.app.networks) };
1581
- compose.services.app = merged;
1582
- app = merged;
1583
- }
1584
- if (!options.deferReferenceResolution) {
1585
- const finalEnv = resolveAppLayers();
1586
- app.environment = { ...finalEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1587
- }
1588
- if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
1589
- delete compose.services.app;
1590
- compose.services[options.appServiceName] = app;
1591
- }
1592
- if (profile.infraMode === "integrated") applyDependencyLifecycle(app, materialized, effective);
1593
- if (profile.attachTester && !options.meshMode) {
1594
- const testerDotenvPath = path.join(root, ".env.e2e-tester"), testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY];
1595
- assertDotenvDoesNotDefineKeys(testerDotenvPath, testerBuilderKeys, { configPath: ".env.e2e-tester", stage: "e2e", composition: "service" });
1596
- const testerEnvRaw = effective.tester?.env ?? {};
1597
- assertNoBuilderOwnedEnvKeys(testerEnvRaw, testerBuilderKeys, { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" });
1598
- const testerContext = { sourceFile: buildPath, configPath: "tester.env", stage: "e2e", composition: "service" };
1599
- assertTesterReferencesArePublic(testerEnvRaw, "build", testerContext);
1600
- const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, testerContext);
1601
- 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" } } };
1602
- }
1603
- enforceHealthyDependsOn(compose);
1604
- nameAllocator.assertUnique();
1605
- 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])) };
1835
+ for (const edge of graph.edges) {
1836
+ if (edge.kind === "requirement") continue;
1837
+ const consumer = graph.nodes.get(edge.consumer), target = graph.nodes.get(edge.target);
1838
+ const targetName = target.kind === "main" ? mainServiceNames.get(edge.target) : modules.get(edge.target).representative;
1839
+ const memberNames = consumer.kind === "main" ? [mainServiceNames.get(edge.consumer)] : modules.get(edge.consumer).serviceNames;
1840
+ for (const name of memberNames) addComposeCondition(compose.services[name], targetName, edge.kind === "dependency" ? "service_healthy" : "service_completed_successfully");
1841
+ }
1842
+ let testerServiceName, testerServiceNames = [];
1843
+ if (profile.attachTester) {
1844
+ const built = compileTester({ tester, origin: testerOrigin, serviceOrigin, envOrigins: testerEnvOrigins, graph, endpoints, stage: input.stage, composition: input.composition, projectDir: input.projectDir, allocator});
1845
+ mergeDocument(compose, built.document, testerOrigin, input.stage);
1846
+ testerServiceName = built.runner;
1847
+ testerServiceNames = built.serviceNames;
1848
+ const runner = compose.services[built.runner];
1849
+ for (const [id, node] of graph.nodes) {
1850
+ const target = node.kind === "main" ? mainServiceNames.get(id) : modules.get(id).representative;
1851
+ addComposeCondition(runner, target, graph.lifecycle.get(id) === "prerequisite" ? "service_completed_successfully" : "service_healthy");
1852
+ }
1853
+ }
1854
+ assertComposeLifecycleAcyclic(compose.services, { sourceFile: input.mesh?.sourceFile ?? input.instances.get("").sourceFile, stage: input.stage, composition: input.composition });
1855
+ allocator.assertUnique();
1856
+ for (const service of Object.values(compose.services)) markOwned(service);
1857
+ for (const section of ["networks", "volumes"]) for (const resource of Object.values(compose[section] ?? {})) if (resource && typeof resource === "object" && !Array.isArray(resource) && !resource.external) markOwned(resource);
1858
+ return { compose, projectName, graph, mainServiceNames, modules, endpoints, runtimeServiceNames: unique(runtimeServiceNames), testerServiceNames, ...testerServiceName ? { testerServiceName } : {}, allocations, deferredHealthChecks };
1859
+ }
1860
+
1861
+ // src/core/composition/compileServiceComposition.ts
1862
+ function compileServiceComposition(stage2, projectDir, options = {}) {
1863
+ const root = resolveProjectDir(projectDir), build = resolveBuildStage(getBuildJson(root), stage2, path.join(root, "build.json"));
1864
+ return compileGraphComposition({ stage: stage2, composition: "service", projectDir: root, name: build.name, instances: /* @__PURE__ */ new Map([["", build]]), full: Boolean(options.full), validationMode: Boolean(options.validationMode) });
1606
1865
  }
1607
1866
 
1608
1867
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1615,14 +1874,13 @@ function checkAllEffectiveServiceStages(projectDir) {
1615
1874
  }
1616
1875
 
1617
1876
  // src/core/checkers/checkInfra.ts
1618
- function checkInfra(projectDir = process.cwd()) {
1877
+ function checkInfra(projectDir = process.cwd(), adapters = {}) {
1619
1878
  const absProjectDir = resolveProjectDir(projectDir);
1620
1879
  const buildJson = getBuildJson(absProjectDir);
1621
- checkDockerfile(buildJson, absProjectDir);
1622
- checkDockerfileContract(buildJson, absProjectDir);
1623
- checkYamlFiles(buildJson, absProjectDir);
1880
+ (adapters.dockerfile ?? checkDockerfile)(buildJson, absProjectDir);
1881
+ (adapters.dockerfileContract ?? checkDockerfileContract)(buildJson, absProjectDir);
1624
1882
  checkAllEffectiveServiceStages(absProjectDir);
1625
- console.log(pc15.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
1883
+ console.log(pc9.green("\nAll V3 service infrastructure and contract checks passed.\n"));
1626
1884
  }
1627
1885
  function checkComposeAvailability() {
1628
1886
  const composeCheck = spawnSync(
@@ -1667,7 +1925,7 @@ function checkDependencies() {
1667
1925
  const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
1668
1926
  if (count > 25) {
1669
1927
  console.warn(
1670
- pc15.yellow(
1928
+ pc9.yellow(
1671
1929
  `
1672
1930
  \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.
1673
1931
  To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
@@ -1709,7 +1967,7 @@ Examples:
1709
1967
 
1710
1968
  // src/core/mesh/types.ts
1711
1969
  var MESH_CONFIG_STAGES = ["dev", "prod", "e2e"];
1712
- var MESH_COMMAND_STAGES = ["dev", "prod", "test", "test-e2e"];
1970
+ var MESH_COMMAND_STAGES = ["dev", "prod", "test"];
1713
1971
 
1714
1972
  // src/core/config/meshStageContract.ts
1715
1973
  var REMOVED_MESH_TEST_MESSAGE = "mesh.json.test is no longer supported. A mesh has no test topology. Put service-owned isolated test settings in build.json.test; put global E2E topology settings in mesh.json.e2e. The mesh test command runs independent service tests, then global E2E.";
@@ -1723,8 +1981,8 @@ function assertNoLegacyMeshTest(input, sourceFile) {
1723
1981
  });
1724
1982
  }
1725
1983
  }
1726
- function assertMeshConfigStage(stage, sourceFile) {
1727
- if (typeof stage !== "string" || !MESH_CONFIG_STAGES.includes(stage)) {
1984
+ function assertMeshConfigStage(stage2, sourceFile) {
1985
+ if (typeof stage2 !== "string" || !MESH_CONFIG_STAGES.includes(stage2)) {
1728
1986
  throw new ConfigError({
1729
1987
  sourceFile,
1730
1988
  configPath: "<stage>",
@@ -1733,17 +1991,38 @@ function assertMeshConfigStage(stage, sourceFile) {
1733
1991
  });
1734
1992
  }
1735
1993
  }
1736
- function meshStageOverlayChain(stage) {
1737
- return stage === "e2e" ? ["prod", "e2e"] : [stage];
1994
+ function meshStageOverlayChain(stage2) {
1995
+ return stage2 === "e2e" ? ["prod", "e2e"] : [stage2];
1738
1996
  }
1739
- var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
1740
- var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
1741
- var envSchema2 = z.record(z.string(), z.string());
1742
- 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();
1743
- 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();
1744
- var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1745
- var rootServicesSchema = z.record(serviceNameSchema, meshServiceSchema).refine((services) => Object.keys(services).length >= 1, { message: "must contain at least one root service" });
1746
- 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(), e2e: meshStageSchema.optional() }).strict();
1997
+ var identifier2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN);
1998
+ var nonblank2 = z.string().min(1).refine((value) => value.trim().length > 0, "must not be blank");
1999
+ var meshRequisites = z.record(z.string().regex(/^(?:source\.)?[a-z][a-z0-9-]*$/), z.union([z.enum(["requirement", "dependency", "prerequisite"]), z.literal(false)]));
2000
+ var meshMainOverlay = mainOverlaySchema.extend({ requisites: meshRequisites.optional() }).strict();
2001
+ var meshOrdinaryOverlay = ordinaryOverlaySchema.extend({ requisites: meshRequisites.optional() }).strict();
2002
+ var extendsSchema = z.record(identifier2, z.unknown()).superRefine((value, context) => {
2003
+ for (const [key, entry] of Object.entries(value)) {
2004
+ const parsed = (key === "main" ? meshMainOverlay : key === "tester" ? testerOverlaySchema : meshOrdinaryOverlay).safeParse(entry);
2005
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
2006
+ }
2007
+ });
2008
+ var meshSourceSchema = z.object({ source: nonblank2, extends: extendsSchema.optional(), publish: z.array(z.string()).optional() }).strict();
2009
+ var meshSourceOverlaySchema = meshSourceSchema.partial().strict();
2010
+ var services = (overlay) => z.record(identifier2, z.unknown()).superRefine((value, context) => {
2011
+ if (!overlay) {
2012
+ if (!("tester" in value)) context.addIssue({ code: "custom", path: ["tester"], message: "tester is required" });
2013
+ if (!Object.keys(value).some((key) => key !== "tester" && key !== "main")) context.addIssue({ code: "custom", message: "at least one source is required" });
2014
+ }
2015
+ for (const [key, entry] of Object.entries(value)) {
2016
+ if (key === "main") {
2017
+ context.addIssue({ code: "custom", path: [key], message: "main is reserved as a mesh source name" });
2018
+ continue;
2019
+ }
2020
+ const parsed = (key === "tester" ? overlay ? testerOverlaySchema : testerServiceSchema : overlay ? meshSourceOverlaySchema : meshSourceSchema).safeParse(entry);
2021
+ if (!parsed.success) for (const issue of parsed.error.issues) context.addIssue({ ...issue, path: [key, ...issue.path] });
2022
+ }
2023
+ });
2024
+ var stage = z.object({ services: services(true).optional() }).strict();
2025
+ var meshSchema = z.object({ $schema: z.string().optional(), name: nonblank2, services: services(false), dev: stage.optional(), prod: stage.optional(), e2e: stage.optional() }).strict();
1747
2026
 
1748
2027
  // src/core/mesh/getMeshJson.ts
1749
2028
  function getMeshJson(projectDir = process.cwd()) {
@@ -1767,542 +2046,132 @@ function getMeshJson(projectDir = process.cwd()) {
1767
2046
  const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
1768
2047
  throw new ConfigError({ sourceFile: meshPath, configPath: "<root>", composition: "mesh", reason: `Invalid mesh.json: ${reason}` });
1769
2048
  }
1770
- return result.data;
1771
- }
1772
-
1773
- // src/core/config/resolveMeshStage.ts
1774
- function resolveMeshStage(mesh, stage, sourceFile) {
1775
- assertNoLegacyMeshTest(mesh, sourceFile);
1776
- assertMeshConfigStage(stage, sourceFile);
1777
- 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" });
1778
- const services = {};
1779
- 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 ?? []] };
1780
- for (const overlayStage of meshStageOverlayChain(stage)) for (const [name, patch] of Object.entries(mesh[overlayStage]?.services ?? {})) {
1781
- const prior = services[name] ?? { path: void 0, env: {}, dependencies: {}, dependsOn: [], publish: [] };
1782
- 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) };
1783
- }
1784
- if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1785
- 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" });
1786
- const graph = /* @__PURE__ */ new Map();
1787
- for (const [name, service] of Object.entries(services)) {
1788
- 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" });
1789
- graph.set(name, /* @__PURE__ */ new Set());
1790
- for (const target of service.dependsOn) {
1791
- if (target === name) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Mesh service cannot depend on itself" });
1792
- if (!services[target]) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Unknown mesh lifecycle target" });
1793
- graph.get(name).add(target);
1794
- }
1795
- }
1796
- assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
1797
- const { dev: _dev, prod: _prod, e2e: _e2e, ...base } = mesh;
1798
- return { ...base, services };
1799
- }
1800
- function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
1801
- const out = {};
1802
- for (const [name, svc] of Object.entries(effectiveMesh.services).sort(([a], [b]) => a.localeCompare(b))) {
1803
- const abs = resolveInsideProject(meshDir, svc.path, { sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage });
1804
- if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new ConfigError({ sourceFile: path.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage, composition: "mesh", value: svc.path, reason: "Mesh service directory does not exist" });
1805
- const buildJsonPath = path.join(abs, "build.json"), build = getBuildJson(abs), effectiveBuild = resolveBuildStage(build, stage, buildJsonPath);
1806
- out[name] = { name, path: svc.path, absolutePath: abs, buildJsonPath, effectiveBuild, meshEnv: { ...svc.env ?? {} }, dependencyBindings: { ...svc.dependencies ?? {} }, dependsOn: [...svc.dependsOn ?? []], publish: [...svc.publish ?? []] };
1807
- }
1808
- return out;
1809
- }
1810
-
1811
- // src/core/mesh/v2/substitution.ts
1812
- function buildDependencyBindings(services, stage, meshJsonPath) {
1813
- const out = [];
1814
- for (const service of Object.values(services)) {
1815
- for (const [logicalDependency, providerService] of Object.entries(service.dependencyBindings)) {
1816
- if (!service.effectiveBuild.dependencies[logicalDependency]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: `Unknown logical dependency slot on consumer ${service.name}` });
1817
- if (!services[providerService]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${service.name}.dependencies.${logicalDependency}`, stage, composition: "mesh", value: providerService, reason: "Dependency provider is not an effective top-level mesh service" });
1818
- out.push({ consumerService: service.name, logicalDependency, providerService });
1819
- }
1820
- }
1821
- return out;
1822
- }
1823
- function bindingKey(consumer, dependency) {
1824
- return `${consumer}::${dependency}`;
1825
- }
1826
- function bindingsMap(bindings) {
1827
- return new Map(bindings.map((b) => [bindingKey(b.consumerService, b.logicalDependency), b.providerService]));
1828
- }
1829
-
1830
- // src/core/mesh/v2/publication.ts
1831
- var APP = /^app\.endpoints\.([a-z][a-z0-9-]*)$/;
1832
- var DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/;
1833
- function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1834
- const out = [];
1835
- for (const svc of Object.values(services).sort((a, b) => a.name.localeCompare(b.name))) for (const raw of svc.publish) {
1836
- let m;
1837
- if (m = APP.exec(raw)) {
1838
- const ep = m[1], endpoint = svc.effectiveBuild.app.endpoints[ep];
1839
- if (!endpoint) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published app endpoint does not exist" });
1840
- if (endpoint.publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published endpoint requires publicPort in build.json" });
1841
- out.push({ logicalPath: `${svc.name}.app.endpoints.${ep}`, ownerMeshService: svc.name, target: "app", endpoint: ep });
1842
- continue;
1843
- }
1844
- if (m = DEP.exec(raw)) {
1845
- const dependency = m[1], endpoint = m[2], dep = svc.effectiveBuild.dependencies[dependency];
1846
- if (!dep || !dep.endpoints[endpoint]) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint does not exist" });
1847
- if (!Object.keys(dep.endpoints).length) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Dependency endpoint is inert" });
1848
- if (bindings.has(bindingKey(svc.name, dependency))) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, referencedObject: `${bindings.get(bindingKey(svc.name, dependency))}.publish -> app.endpoints.${endpoint}`, reason: "A substituted dependency endpoint cannot be published by its consumer; publish the provider app endpoint instead" });
1849
- if (dep.endpoints[endpoint].publicPort === void 0) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published dependency endpoint requires publicPort in build.json" });
1850
- out.push({ logicalPath: `${svc.name}.dependencies.${dependency}.endpoints.${endpoint}`, ownerMeshService: svc.name, target: "dependency", dependency, endpoint });
1851
- continue;
1852
- }
1853
- throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Invalid publish target; expected app.endpoints.<name> or dependencies.<name>.endpoints.<name>" });
1854
- }
1855
- return out;
1856
- }
1857
-
1858
- // src/core/mesh/v2/meshReferences.ts
1859
- function resolveMesh(ref, ctx, context) {
1860
- const name = ref.meshService;
1861
- if (!ctx.services[name]) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1862
- const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1863
- 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];
1864
- if (!endpoint) throw new ConfigError({ ...context, referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1865
- return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1866
- }
1867
- function resolveBuild(ref, consumer, ctx, context) {
1868
- const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1869
- 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];
1870
- if (!endpoint) {
1871
- const reason = provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist";
1872
- throw new ConfigError({ ...context, referencedObject: ref.raw, reason });
1873
- }
1874
- try {
1875
- return resolveEndpointProperty(endpoint, ref.property, { ...context, referencedObject: ref.raw });
1876
- } catch (error) {
1877
- if (provider && error instanceof ConfigError) {
1878
- throw new ConfigError({
1879
- ...context,
1880
- referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`,
1881
- reason: error.message
1882
- });
1883
- }
1884
- throw error;
1885
- }
1886
- }
1887
- function interpolate(value, scope, ctx, configPath, consumer) {
1888
- const context = {
1889
- sourceFile: scope === "mesh" ? ctx.meshJsonPath : ctx.services[consumer]?.buildJsonPath ?? ctx.meshJsonPath,
1890
- configPath,
1891
- stage: ctx.stage,
1892
- composition: scope === "mesh" ? "mesh" : "service"
1893
- };
1894
- return interpolateBuilderReferences(value, scope, (ref, refContext) => scope === "mesh" ? resolveMesh(ref, ctx, refContext) : resolveBuild(ref, consumer, ctx, refContext), context).replace(/\$/g, "$$$$");
1895
- }
1896
- function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1897
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", ctx, `${sourcePrefix}.${key}`)]));
1898
- }
1899
- function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1900
- return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", ctx, `${sourcePrefix}.${key}`, consumer)]));
1901
- }
1902
- function assertMeshTesterEnvPublic(env, ctx, configPath = "tester.env") {
1903
- assertTesterReferencesArePublic(env, "mesh", {
1904
- sourceFile: ctx.meshJsonPath,
1905
- configPath,
1906
- stage: ctx.stage,
1907
- composition: "mesh"
1908
- });
1909
- }
1910
-
1911
- // src/core/mesh/v2/lifecycle.ts
1912
- function buildMeshLifecycleEdges(services, bindings, stage, meshJsonPath) {
1913
- const result = [];
1914
- const seen = /* @__PURE__ */ new Set();
1915
- for (const svc of Object.values(services)) for (const provider of [...svc.dependsOn, ...Object.entries(svc.dependencyBindings).map(([dep]) => bindings.get(bindingKey(svc.name, dep))).filter(Boolean)]) {
1916
- if (provider === svc.name) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.dependsOn`, stage, composition: "mesh", referencedObject: provider, reason: "Mesh service cannot depend on itself" });
1917
- const source = svc.dependsOn.includes(provider) ? "dependsOn" : "dependency-binding";
1918
- const id = `${svc.name}\0${provider}`;
1919
- if (!seen.has(id)) {
1920
- seen.add(id);
1921
- result.push({ consumer: svc.name, provider, source });
1922
- }
1923
- }
1924
- const graph = new Map(Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()]));
1925
- for (const edge of result) graph.get(edge.consumer).add(edge.provider);
1926
- assertAcyclicGraph(graph, { sourceFile: meshJsonPath, stage, composition: "mesh" });
1927
- return result;
1928
- }
1929
- function applyMeshLifecycleEdges(services, edges) {
1930
- for (const edge of edges) {
1931
- const consumer = services[edge.consumer];
1932
- const old = consumer.depends_on && typeof consumer.depends_on === "object" && !Array.isArray(consumer.depends_on) ? consumer.depends_on : {};
1933
- old[edge.provider] = { condition: "service_healthy" };
1934
- consumer.depends_on = old;
1935
- }
1936
- }
1937
- function appendEnvFile(existing, next) {
1938
- if (existing === void 0) return [next];
1939
- return Array.isArray(existing) ? [...existing, next] : [existing, next];
1940
- }
1941
- function envFilePaths(value) {
1942
- const entries2 = Array.isArray(value) ? value : [value];
1943
- return entries2.flatMap((entry) => typeof entry === "string" ? [entry] : entry && typeof entry === "object" && typeof entry.path === "string" ? [entry.path] : []);
1944
- }
1945
- function validateServiceReferences(document, sourceFile, stage) {
1946
- for (const [name, service] of Object.entries(document.services)) {
1947
- const refs = [];
1948
- const add = (value) => {
1949
- if (typeof value === "string" && value) refs.push(value);
1950
- };
1951
- if (Array.isArray(service.depends_on)) service.depends_on.forEach(add);
1952
- else if (service.depends_on && typeof service.depends_on === "object") Object.keys(service.depends_on).forEach(add);
1953
- if (Array.isArray(service.links)) service.links.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1954
- if (Array.isArray(service.volumes_from)) service.volumes_from.forEach((value) => add(typeof value === "string" ? value.split(":")[0] : void 0));
1955
- for (const key of ["network_mode", "ipc", "pid"]) {
1956
- const value = service[key];
1957
- if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1958
- }
1959
- 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" });
1960
- }
1961
- }
1962
- function applyTesterBuildTarget(service) {
1963
- if (service.build === void 0) return;
1964
- if (typeof service.build === "string") {
1965
- service.build = { context: service.build, target: "test-e2e" };
1966
- return;
1967
- }
1968
- if (service.build && typeof service.build === "object" && !Array.isArray(service.build)) service.build = { ...service.build, target: "test-e2e" };
1969
- }
1970
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1971
- const meshPath = path.join(meshDir, "mesh.json"), file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage });
1972
- const sourceDocument = loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" });
1973
- const raw = rebaseComposePaths(sourceDocument, file, meshDir);
1974
- 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" });
1975
- validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" });
1976
- validateServiceReferences(raw, file, stage);
1977
- assertComposeLifecycleAcyclic(raw.services, {
1978
- sourceFile: file,
1979
- stage,
1980
- composition: "mesh"
1981
- });
1982
- for (const [serviceName, service] of Object.entries(raw.services)) {
1983
- 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" });
1984
- assertNoServiceBuildContexts(service, `services.${serviceName}`, file);
1985
- }
1986
- const selectedRaw = raw.services[tester.service];
1987
- 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" });
1988
- 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" });
1989
- 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" });
1990
- validateMaterializedComposeFiles(sourceDocument, file, stage, { composition: "mesh" });
1991
- validateMaterializedComposeBuildInputs(sourceDocument, file, stage, "mesh");
1992
- const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1993
- const testerBuilderKeys = [EXEC_MODE_KEY, INFRA_MODE_KEY], rawRunnerEnvironment = normalizeComposeEnvironment(selectedRaw.environment, "tester runner environment");
1994
- assertNoBuilderOwnedEnvKeys(rawRunnerEnvironment, testerBuilderKeys, { sourceFile: file, configPath: `services.${tester.service}.environment`, stage, composition: "mesh" });
1995
- for (const envFile of envFilePaths(selectedRaw.env_file)) assertDotenvDoesNotDefineKeys(path.resolve(meshDir, envFile), testerBuilderKeys, { configPath: `services.${tester.service}.env_file`, stage, composition: "mesh" });
1996
- const meshTesterDotenv = path.join(meshDir, ".env.e2e-tester");
1997
- assertDotenvDoesNotDefineKeys(meshTesterDotenv, testerBuilderKeys, { configPath: ".env.e2e-tester", stage, composition: "mesh" });
1998
- const testerEnv = tester.env ?? {};
1999
- assertNoBuilderOwnedEnvKeys(testerEnv, testerBuilderKeys, { sourceFile: meshPath, configPath: "tester.env", stage, composition: "mesh" });
2000
- assertMeshTesterEnvPublic(testerEnv, meshCtx);
2001
- const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: raw, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
2002
- const runner = ns.serviceNameMap.get(tester.service);
2003
- const runnerSvc = ns.document.services[runner];
2004
- applyTesterBuildTarget(runnerSvc);
2005
- runnerSvc.network_mode = "host";
2006
- delete runnerSvc.networks;
2007
- runnerSvc.env_file = appendEnvFile(runnerSvc.env_file, { path: ".env.e2e-tester", required: false });
2008
- runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(testerEnv, meshCtx, "tester.env"), EXEC_MODE: "e2e" };
2009
- const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
2010
- for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
2011
- runnerSvc.depends_on = depends;
2012
- 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 };
2013
- }
2014
-
2015
- // src/core/mesh/v2/resolveMeshAppEnvironment.ts
2016
- function resolveMeshAppEnvironmentLayers(serviceName, layers, context, laterKeys = /* @__PURE__ */ new Set()) {
2017
- const result = {};
2018
- for (const [key, layer] of selectAppEnvironmentEntries(layers, laterKeys)) {
2019
- if (layer.kind === "build-json") {
2020
- result[key] = resolveServiceBuildEnvThroughMesh(
2021
- serviceName,
2022
- { [key]: layer.values[key] },
2023
- context,
2024
- `services.${serviceName}.${layer.configPath}`
2025
- )[key];
2026
- } else {
2027
- result[key] = layer.values[key];
2028
- }
2029
- }
2030
- return result;
2031
- }
2032
- function validPort(value) {
2033
- if (!/^\d+$/.test(value)) return void 0;
2034
- const port = Number(value);
2035
- return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
2036
- }
2037
- function parsePublishedHostPort(value) {
2038
- if (value && typeof value === "object") {
2039
- const published = value.published;
2040
- if (typeof published === "number" && Number.isInteger(published)) {
2041
- return published >= 1 && published <= 65535 ? published : void 0;
2042
- }
2043
- if (typeof published === "string") return validPort(published);
2044
- return void 0;
2045
- }
2046
- if (typeof value !== "string") return void 0;
2047
- const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
2048
- if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
2049
- if (mapping.startsWith("[")) {
2050
- const close = mapping.indexOf("]");
2051
- if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
2052
- const suffix = mapping.slice(close + 1);
2053
- const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
2054
- return match ? validPort(match[1]) : void 0;
2055
- }
2056
- const parts = mapping.split(":");
2057
- if (parts.length === 2) return validPort(parts[0]);
2058
- if (parts.length >= 3) {
2059
- const hostIp = parts.slice(0, -2).join(":");
2060
- if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
2061
- }
2062
- return void 0;
2063
- }
2064
-
2065
- // src/utils/assertUniqueHostPortMappings.ts
2066
- function assertUniqueHostPortMappings(yamlConfig) {
2067
- const parsed = parse(yamlConfig);
2068
- const owners = /* @__PURE__ */ new Map();
2069
- for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
2070
- for (const port of service?.ports ?? []) {
2071
- const hostPort = parsePublishedHostPort(port);
2072
- if (hostPort === void 0) continue;
2073
- const existing = owners.get(hostPort);
2074
- if (existing) {
2075
- throw new ScriptError(
2076
- `Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
2077
- );
2078
- }
2079
- owners.set(hostPort, serviceName);
2080
- }
2081
- }
2082
- }
2083
-
2084
- // src/core/mesh/v2/compileMeshComposition.ts
2085
- function mergeFragment(target, fragment, owner) {
2086
- for (const key of ["services", "volumes", "networks", "configs", "secrets"]) {
2087
- const incoming = fragment[key];
2088
- if (!incoming) continue;
2089
- const dest = target[key] ??= {};
2090
- for (const [name, value] of Object.entries(incoming)) {
2091
- if (name in dest) throw new ConfigError({ configPath: `${key}.${name}`, referencedObject: owner, reason: "Mesh composition name collision" });
2092
- dest[name] = value;
2093
- }
2094
- }
2095
- }
2096
- function appendPort(service, target, published) {
2097
- const ports = Array.isArray(service.ports) ? service.ports : [];
2098
- ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
2099
- service.ports = ports;
2100
- }
2101
- function buildMeshPortIntents(services, publication) {
2102
- const intents = [];
2103
- for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
2104
- const service = services[name];
2105
- const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
2106
- for (const pub of appPublications) {
2107
- const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
2108
- intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
2109
- }
2110
- const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
2111
- for (const dependency of dependencyNames) {
2112
- const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
2113
- for (const pub of dependencyPublications) {
2114
- const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
2115
- intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
2116
- }
2117
- }
2118
- }
2119
- return intents;
2120
- }
2121
- function ownerFor(pub, fragment) {
2122
- return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
2123
- }
2124
- function setEnv(service, env) {
2125
- const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
2126
- service.environment = { ...current, ...env };
2049
+ return result.data;
2127
2050
  }
2128
- function attachNetworkIfCompatible(service, networkName) {
2129
- if (service.network_mode !== void 0) return;
2130
- service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
2131
- }
2132
- function compileMeshComposition(stage, meshDir, options = {}) {
2133
- 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);
2134
- const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
2135
- const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
2136
- const fragments = {};
2137
- const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
2138
- for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2139
- 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" });
2140
- const suppress = new Set(Object.keys(svc.dependencyBindings));
2141
- 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 });
2142
- fragments[name] = fragment;
2143
- mergeFragment(compose, fragment.compose, name);
2144
- const app = compose.services[name];
2145
- const networks = { mesh: null };
2146
- const localDeps = Object.keys(fragment.endpoints.dependencies).filter((dep) => !bindingMap.has(bindingKey(name, dep)) && Object.keys(fragment.effectiveBuild.dependencies[dep]?.endpoints ?? {}).length > 0);
2147
- if (localDeps.length) {
2148
- const privateName = `mesh--${name}`;
2149
- networks[privateName] = null;
2150
- compose.networks[privateName] = { driver: "bridge" };
2151
- for (const dep of localDeps) {
2152
- for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
2153
- const owner = ep.networkHost;
2154
- const ownerService = compose.services[owner];
2155
- if (ownerService) {
2156
- attachNetworkIfCompatible(ownerService, privateName);
2157
- attachNetworkIfCompatible(ownerService, "mesh");
2158
- }
2159
- }
2160
- for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
2161
- const ownerService = compose.services[generated];
2162
- attachNetworkIfCompatible(ownerService, privateName);
2163
- }
2164
- }
2051
+ var originFor2 = (sourceFile, configPath, layer) => ({ sourceFile, configPath, projectDir: path.dirname(sourceFile), scope: "mesh", layer });
2052
+ function resolveMeshStage(mesh, stage2, sourceFile) {
2053
+ assertMeshConfigStage(stage2, sourceFile);
2054
+ const sources = {};
2055
+ const baseSources = Object.keys(mesh.services).filter((name) => name !== "tester").sort();
2056
+ const testerLayers = [];
2057
+ let tester = structuredClone(mesh.services.tester);
2058
+ testerLayers.push({ stage: "base", services: { tester: structuredClone(tester) }, origin: originFor2(sourceFile, "services.tester", "base") });
2059
+ for (const name of baseSources) {
2060
+ const entry = mesh.services[name];
2061
+ sources[name] = { source: entry.source, publish: [...entry.publish ?? []], publishOrigin: originFor2(sourceFile, `services.${name}.publish`, "base"), extendsLayers: entry.extends ? [{ layer: "base", patches: structuredClone(entry.extends), origin: originFor2(sourceFile, `services.${name}.extends`, "base") }] : [], origin: originFor2(sourceFile, `services.${name}`, "base") };
2062
+ }
2063
+ for (const layer of meshStageOverlayChain(stage2)) for (const [name, patch] of Object.entries(mesh[layer]?.services ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
2064
+ if (name === "tester") {
2065
+ const next2 = patch;
2066
+ if (next2.compose !== void 0 && next2.compose !== tester.compose) throw new ConfigError({ sourceFile, configPath: `${layer}.services.tester.compose`, stage: stage2, composition: "mesh", reason: "compose is immutable; previous services.tester.compose", value: next2.compose });
2067
+ tester = mergeEffectiveObject(tester, next2);
2068
+ testerLayers.push({ stage: layer, services: { tester: structuredClone(next2) }, origin: originFor2(sourceFile, `${layer}.services.tester`, layer) });
2069
+ continue;
2165
2070
  }
2166
- app.networks = { ...normalizeNetworks(app.networks), ...networks };
2167
- }
2168
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode), { sourceFile: meshPath, composition: "mesh" });
2169
- const endpoints = { app: {}, dependencies: {} };
2170
- for (const [name, svc] of Object.entries(services)) {
2171
- endpoints.app[name] = {};
2172
- for (const [epName, ep] of Object.entries(svc.effectiveBuild.app.endpoints)) {
2173
- const host = name;
2174
- const record = { logicalPath: `${name}.app.endpoints.${epName}`, networkHost: host, networkPort: ep.port, ...ep.scheme ? { scheme: ep.scheme } : {}, effectivelyPublished: false };
2175
- endpoints.app[name][epName] = record;
2176
- }
2177
- endpoints.dependencies[name] = {};
2178
- const fragment = fragments[name];
2179
- for (const [depName, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
2180
- if (bindingMap.has(bindingKey(name, depName))) continue;
2181
- endpoints.dependencies[name][depName] = {};
2182
- for (const [epName, def] of Object.entries(dep.endpoints)) {
2183
- const local = fragment.endpoints.dependencies[depName]?.[epName];
2184
- if (!local) continue;
2185
- endpoints.dependencies[name][depName][epName] = { ...local, logicalPath: `${name}.dependencies.${depName}.endpoints.${epName}`, effectivelyPublished: false };
2071
+ const next = patch;
2072
+ const old = sources[name];
2073
+ if (old && next.source !== void 0 && next.source !== old.source) throw new ConfigError({ sourceFile, configPath: `${layer}.services.${name}.source`, stage: stage2, composition: "mesh", reason: `source is immutable; previous ${old.origin.configPath}.source`, value: next.source });
2074
+ if (!old && (!next.source || !next.source.trim())) throw new ConfigError({ sourceFile, configPath: `${layer}.services.${name}.source`, stage: stage2, composition: "mesh", reason: "Stage-introduced source requires source" });
2075
+ const entry = old ?? { source: next.source, publish: [], publishOrigin: originFor2(sourceFile, `${layer}.services.${name}.publish`, layer), extendsLayers: [], origin: originFor2(sourceFile, `${layer}.services.${name}`, layer) };
2076
+ if (next.publish !== void 0) {
2077
+ entry.publish = structuredClone(next.publish);
2078
+ entry.publishOrigin = originFor2(sourceFile, `${layer}.services.${name}.publish`, layer);
2079
+ }
2080
+ if (next.extends) entry.extendsLayers.push({ layer, patches: structuredClone(next.extends), origin: originFor2(sourceFile, `${layer}.services.${name}.extends`, layer) });
2081
+ sources[name] = entry;
2082
+ }
2083
+ return { name: mesh.name, services: sources, tester, testerLayers, sourceFile, projectDir: path.dirname(sourceFile), baseSources, raw: mesh };
2084
+ }
2085
+
2086
+ // src/core/mesh/applyMeshExtends.ts
2087
+ function applyMeshExtends(mesh, builds, stage2) {
2088
+ for (const [root, build] of builds) {
2089
+ const entry = mesh.services[root];
2090
+ for (const layer of entry.extendsLayers) for (const [name, patch] of Object.entries(layer.patches).sort(([a], [b]) => a.localeCompare(b))) {
2091
+ const old = build.services[name];
2092
+ const origin = { ...layer.origin, meshRoot: root, configPath: `${layer.origin.configPath}.${name}` };
2093
+ if (!old) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: origin.configPath, stage: stage2, composition: "mesh", referencedObject: `${root}.source.${name}`, reason: "extends target does not exist" });
2094
+ if (patch.compose !== void 0 && patch.compose !== old.compose) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.compose`, stage: stage2, composition: "mesh", reason: `compose is immutable; previous ${build.origins.get(name)?.configPath}.compose`, value: patch.compose });
2095
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) if (kind === false) {
2096
+ const exists = target.startsWith("source.") ? Boolean(build.services[target.slice(7)]) : Boolean(mesh.services[target]);
2097
+ if (!exists) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.requisites.${target}`, stage: stage2, composition: "mesh", referencedObject: target, reason: "Unknown requisite target" });
2186
2098
  }
2187
- }
2188
- }
2189
- for (const pub of publication) {
2190
- const ep = pub.target === "app" ? endpoints.app[pub.ownerMeshService]?.[pub.endpoint] : endpoints.dependencies[pub.ownerMeshService]?.[pub.dependency]?.[pub.endpoint];
2191
- if (!ep) continue;
2192
- ep.publicHost = PUBLIC_HOST;
2193
- ep.publicPort = ports.get(pub.logicalPath);
2194
- ep.effectivelyPublished = true;
2195
- }
2196
- for (const pub of publication) {
2197
- const fragment = fragments[pub.ownerMeshService], endpoint = pub.target === "app" ? endpoints.app[pub.ownerMeshService][pub.endpoint] : endpoints.dependencies[pub.ownerMeshService][pub.dependency][pub.endpoint];
2198
- const owner = ownerFor(pub, fragment);
2199
- const service = compose.services[owner];
2200
- if (service && endpoint) appendPort(service, endpoint.networkPort, endpoint.publicPort);
2201
- }
2202
- const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
2203
- for (const [name, fragment] of Object.entries(fragments)) {
2204
- const app = compose.services[name];
2205
- const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
2206
- const serviceEnv = resolveMeshAppEnvironmentLayers(name, fragment.appEnvironmentLayers, refContext, new Set(Object.keys(meshEnv)));
2207
- app.environment = { ...serviceEnv, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
2208
- for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
2209
- const logicalBinding = bindingMap.get(bindingKey(name, depName));
2210
- if (logicalBinding) continue;
2211
- const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
2212
- for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
2213
- const service = compose.services[serviceName];
2214
- if (service) setEnv(service, resolvedDep);
2099
+ const canonicalPatch = structuredClone(patch);
2100
+ if (canonicalPatch.requisites) {
2101
+ canonicalPatch.requisites = Object.fromEntries(Object.entries(canonicalPatch.requisites).map(([target, kind]) => [target.startsWith("source.") ? target.slice(7) : `@mesh:${target}`, kind]));
2215
2102
  }
2216
- }
2217
- }
2218
- const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
2219
- applyMeshLifecycleEdges(compose.services, edges);
2220
- for (const [name, svc] of Object.entries(services)) for (const [sourceDep, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
2221
- if (bindingMap.has(bindingKey(name, sourceDep))) continue;
2222
- for (const rawTarget of dep.dependsOn) {
2223
- const targetKey = rawTarget.slice("dependencies.".length);
2224
- const provider = bindingMap.get(bindingKey(name, targetKey));
2225
- if (!provider) continue;
2226
- const localEndpoints = endpoints.dependencies[name]?.[sourceDep] ?? {};
2227
- for (const ep of Object.values(localEndpoints)) {
2228
- const localOwner = ep.networkHost, localSvc = compose.services[localOwner];
2229
- if (!localSvc) continue;
2230
- const ds = localSvc.depends_on && typeof localSvc.depends_on === "object" && !Array.isArray(localSvc.depends_on) ? localSvc.depends_on : {};
2231
- ds[provider] = { condition: "service_healthy" };
2232
- localSvc.depends_on = ds;
2233
- const net2 = localSvc.networks && typeof localSvc.networks === "object" && !Array.isArray(localSvc.networks) ? localSvc.networks : {};
2234
- net2.mesh = null;
2235
- localSvc.networks = net2;
2103
+ const merged = applyServiceOverlay(old, canonicalPatch);
2104
+ if (name !== "main" && name !== "tester") {
2105
+ const ordinary = merged;
2106
+ const primary = Object.values(ordinary.endpoints ?? {}).find((endpoint) => endpoint.primary);
2107
+ if (primary?.service && ordinary.service && ordinary.service !== primary.service) throw new ConfigError({ sourceFile: mesh.sourceFile, configPath: `${origin.configPath}.service`, stage: stage2, composition: "mesh", referencedObject: `${root}.source.${name}`, reason: "top-level service must equal primary endpoint owner", value: ordinary.service });
2236
2108
  }
2109
+ build.services[name] = merged;
2110
+ const env2 = build.envOrigins.get(name) ?? /* @__PURE__ */ new Map();
2111
+ for (const key of Object.keys(patch.env ?? {})) env2.set(key, { ...origin, configPath: `${origin.configPath}.env.${key}` });
2112
+ build.envOrigins.set(name, env2);
2113
+ const edges = build.requisiteOrigins.get(name) ?? /* @__PURE__ */ new Map();
2114
+ for (const [target, kind] of Object.entries(patch.requisites ?? {})) {
2115
+ const canonical = target.startsWith("source.") ? target.slice(7) : `@mesh:${target}`;
2116
+ if (kind === false) edges.delete(canonical);
2117
+ else edges.set(canonical, { ...origin, configPath: `${origin.configPath}.requisites.${target}` });
2118
+ }
2119
+ build.requisiteOrigins.set(name, edges);
2120
+ build.layers.push({ stage: layer.layer, services: { [name]: structuredClone(patch) }, origin });
2237
2121
  }
2238
2122
  }
2239
- const fullGraph = new Map(Object.keys(compose.services).map((name) => [name, /* @__PURE__ */ new Set()]));
2240
- for (const [serviceName, service] of Object.entries(compose.services)) {
2241
- const dependencies = service.depends_on;
2242
- if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) for (const target of Object.keys(dependencies)) {
2243
- if (fullGraph.has(target)) fullGraph.get(serviceName).add(target);
2244
- }
2245
- }
2246
- assertAcyclicGraph(fullGraph, { sourceFile: meshPath, stage, composition: "mesh" });
2247
- let testerServiceName;
2248
- if (stage === "e2e") {
2249
- 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? }" });
2250
- const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
2251
- if (built) {
2252
- 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 } : {} };
2253
- mergeFragment(compose, fragment, "mesh tester");
2254
- testerServiceName = built.runnerServiceName;
2255
- }
2123
+ }
2124
+ function loadMeshSources(mesh, stage2) {
2125
+ const result = /* @__PURE__ */ new Map();
2126
+ for (const [root, entry] of Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b))) {
2127
+ const projectDir = resolveInsideProject(mesh.projectDir, entry.source, { sourceFile: mesh.sourceFile, configPath: `${entry.origin.configPath}.source`, stage: stage2 });
2128
+ result.set(root, resolveBuildStage(getBuildJson(projectDir), stage2, path.join(projectDir, "build.json")));
2256
2129
  }
2257
- enforceHealthyDependsOn(compose);
2258
- nameAllocator.assertUnique();
2259
- const yaml = stringify(compose);
2260
- assertUniqueHostPortMappings(yaml);
2261
- return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
2130
+ return result;
2131
+ }
2132
+
2133
+ // src/core/mesh/compileMeshComposition.ts
2134
+ function compileMeshComposition(stage2, projectDir, options = {}) {
2135
+ const root = resolveProjectDir(projectDir);
2136
+ const mesh = resolveMeshStage(getMeshJson(root), stage2, path.join(root, "mesh.json"));
2137
+ const builds = loadMeshSources(mesh, stage2);
2138
+ applyMeshExtends(mesh, builds, stage2);
2139
+ return compileGraphComposition({ stage: stage2, composition: "mesh", projectDir: root, name: mesh.name, instances: builds, mesh, validationMode: Boolean(options.validationMode) });
2262
2140
  }
2263
2141
 
2264
2142
  // src/core/mesh/checkers/checkMeshServices.ts
2265
- function checkMeshServices(mesh, meshDir) {
2266
- const root = resolveProjectDir(meshDir);
2267
- const meshPath = path.join(root, "mesh.json");
2268
- const checked = /* @__PURE__ */ new Set();
2269
- for (const stage of MESH_CONFIG_STAGES) {
2270
- const effective = resolveMeshStage(mesh, stage, meshPath);
2271
- const services = loadEffectiveMeshServices(root, effective, stage);
2272
- for (const [name, svc] of Object.entries(services)) {
2273
- if (!checked.has(svc.absolutePath)) {
2274
- console.log(pc15.cyan(`
2275
- \u{1F50D} Checking mesh service ${name}...`));
2276
- checkInfra(svc.absolutePath);
2277
- checked.add(svc.absolutePath);
2143
+ function checkMeshServices(mesh, meshDir, policy = checkDockerfileContract) {
2144
+ const root = resolveProjectDir(meshDir), checked = /* @__PURE__ */ new Set();
2145
+ for (const [layer, services2] of [["", mesh.services], ["dev.", mesh.dev?.services], ["prod.", mesh.prod?.services], ["e2e.", mesh.e2e?.services]]) {
2146
+ if (!services2) continue;
2147
+ for (const [name, entry] of Object.entries(services2)) {
2148
+ if (name === "tester") continue;
2149
+ const source = entry.source;
2150
+ if (!source) continue;
2151
+ const dir = resolveInsideProject(root, source, { sourceFile: path.join(root, "mesh.json"), configPath: `${layer}services.${name}.source` });
2152
+ if (!checked.has(dir)) {
2153
+ policy(getBuildJson(dir), dir);
2154
+ checked.add(dir);
2278
2155
  }
2279
2156
  }
2280
- compileMeshComposition(stage, root, {
2281
- validationMode: true,
2282
- allowMissingTester: true
2283
- });
2284
2157
  }
2158
+ for (const stage2 of MESH_CONFIG_STAGES) compileMeshComposition(stage2, root, { validationMode: true });
2285
2159
  }
2286
- function checkMeshTester(mesh, meshDir, options = {}) {
2287
- const root = resolveProjectDir(meshDir);
2288
- if (!mesh.tester) {
2289
- if (options.required) throw new ConfigError({ sourceFile: path.join(root, "mesh.json"), configPath: "tester", stage: "e2e", composition: "mesh", reason: "Global mesh E2E requires root tester" });
2290
- return;
2291
- }
2292
- const file = resolveInsideProject(root, mesh.tester.compose, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e" });
2293
- loadComposeDocument(file, { sourceFile: path.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e", composition: "mesh" });
2294
- compileMeshComposition("e2e", root, { validationMode: true });
2160
+
2161
+ // src/core/mesh/checkers/checkMeshTester.ts
2162
+ function checkMeshTester(_mesh, meshDir) {
2163
+ compileMeshComposition("e2e", resolveProjectDir(meshDir), { validationMode: true });
2295
2164
  }
2296
2165
 
2297
2166
  // src/core/mesh/checkers/checkMesh.ts
2298
2167
  function checkMesh(meshDir = process.cwd(), options = {}) {
2299
2168
  const absMeshDir = resolveProjectDir(meshDir);
2300
2169
  const mesh = getMeshJson(absMeshDir);
2301
- checkMeshServices(mesh, absMeshDir);
2302
- checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
2170
+ checkMeshServices(mesh, absMeshDir, options.dockerfileContract);
2171
+ checkMeshTester(mesh, absMeshDir);
2303
2172
  console.log(
2304
- pc15.bold(
2305
- pc15.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
2173
+ pc9.bold(
2174
+ pc9.green("\nAll V3 mesh infrastructure, services, and contract checks passed.\n")
2306
2175
  )
2307
2176
  );
2308
2177
  }
@@ -2341,7 +2210,7 @@ Examples:
2341
2210
  }
2342
2211
  });
2343
2212
  };
2344
- var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2213
+ var compileEnvironment = (stage2, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage2, projectDir, options).compose);
2345
2214
  var activeComposeSet = /* @__PURE__ */ new Set();
2346
2215
  var signalHandlersRegistered = false;
2347
2216
  var activeChildProcess = null;
@@ -2369,8 +2238,15 @@ function registerActiveCompose(yamlConfig, projectDir, options = {}) {
2369
2238
  ensureSignalHandlers();
2370
2239
  return () => {
2371
2240
  activeComposeSet.delete(entry);
2241
+ if (activeComposeSet.size === 0 && activeChildProcess === null) releaseSignalHandlers();
2372
2242
  };
2373
2243
  }
2244
+ function releaseSignalHandlers() {
2245
+ for (const [sig, listener] of registeredListeners) process.removeListener(sig, listener);
2246
+ registeredListeners.length = 0;
2247
+ signalHandlersRegistered = false;
2248
+ isShuttingDown = false;
2249
+ }
2374
2250
  function ensureSignalHandlers() {
2375
2251
  if (signalHandlersRegistered) return;
2376
2252
  signalHandlersRegistered = true;
@@ -2432,9 +2308,11 @@ function ensureSignalHandlers() {
2432
2308
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2433
2309
  for (const sig of SIGNALS) {
2434
2310
  const listener = () => handleSignal(sig);
2311
+ registeredListeners.push([sig, listener]);
2435
2312
  process.on(sig, listener);
2436
2313
  }
2437
2314
  }
2315
+ var registeredListeners = [];
2438
2316
 
2439
2317
  // src/core/teardownCompose.ts
2440
2318
  function runSpawn(executable, args, cwd, input, silent = false, timeoutMs = 6e4) {
@@ -2496,8 +2374,8 @@ async function teardownCompose(yamlConfig, projectDir, options = {}) {
2496
2374
  }
2497
2375
  const inputData = options.projectName ? void 0 : yamlConfig;
2498
2376
  if (!removeVolumes) {
2499
- const services = yamlConfig.trim() ? anonymousVolumeServices(parse(yamlConfig)?.services ?? {}) : options.anonymousVolumeServices ?? [];
2500
- if (services.length) await runSpawn("docker", [...baseArgs, "rm", "-s", "-f", "-v", ...services], absProjectDir, inputData, true, 15e3);
2377
+ const services2 = yamlConfig.trim() ? anonymousVolumeServices(parse(yamlConfig)?.services ?? {}) : options.anonymousVolumeServices ?? [];
2378
+ if (services2.length) await runSpawn("docker", [...baseArgs, "rm", "-s", "-f", "-v", ...services2], absProjectDir, inputData, true, 15e3);
2501
2379
  }
2502
2380
  const downArgs = [...baseArgs, "down"];
2503
2381
  if (removeVolumes) {
@@ -2559,14 +2437,19 @@ function writeRunState(projectDir, state) {
2559
2437
  }
2560
2438
  const fullState = {
2561
2439
  ...state,
2440
+ version: 3,
2562
2441
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2563
2442
  };
2564
- writeFileSync(
2565
- path.resolve(builderDir, "run.state"),
2566
- JSON.stringify(fullState, null, 2),
2567
- "utf-8"
2568
- );
2569
- } catch {
2443
+ const target = path.resolve(builderDir, "run.state");
2444
+ const temporary = path.resolve(builderDir, `run.state.${process.pid}.tmp`);
2445
+ try {
2446
+ writeFileSync(temporary, JSON.stringify(fullState, null, 2), "utf-8");
2447
+ renameSync(temporary, target);
2448
+ } finally {
2449
+ if (existsSync(temporary)) unlinkSync(temporary);
2450
+ }
2451
+ } catch (error) {
2452
+ throw new Error(`Failed to persist Builder run state in ${projectDir}`, { cause: error });
2570
2453
  }
2571
2454
  }
2572
2455
  function readRunState(projectDir) {
@@ -2574,9 +2457,15 @@ function readRunState(projectDir) {
2574
2457
  const statePath = getRunStatePath(projectDir);
2575
2458
  if (!existsSync(statePath)) return null;
2576
2459
  const content = readFileSync(statePath, "utf-8");
2577
- return JSON.parse(content);
2578
- } catch {
2579
- return null;
2460
+ const value = JSON.parse(content);
2461
+ if (!value || typeof value !== "object" || !("projectName" in value) || typeof value.projectName !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value.projectName) || !("stage" in value) || typeof value.stage !== "string" || !("projectDir" in value) || typeof value.projectDir !== "string") {
2462
+ throw new Error("Saved run state is malformed");
2463
+ }
2464
+ if ("version" in value && value.version !== 2 && value.version !== 3) throw new Error("Saved run state version is unsupported");
2465
+ if (path.resolve(value.projectDir) !== resolveProjectDir(projectDir)) throw new Error("Saved run state belongs to another project directory");
2466
+ return value;
2467
+ } catch (error) {
2468
+ throw new Error(`Cannot read saved Builder run state in ${projectDir}; inspect .builder/run.state before cleanup`, { cause: error });
2580
2469
  }
2581
2470
  }
2582
2471
  function clearRunState(projectDir) {
@@ -2585,10 +2474,11 @@ function clearRunState(projectDir) {
2585
2474
  if (existsSync(statePath)) {
2586
2475
  unlinkSync(statePath);
2587
2476
  }
2588
- } catch {
2477
+ } catch (error) {
2478
+ throw new Error(`Failed to clear Builder run state in ${projectDir}`, { cause: error });
2589
2479
  }
2590
2480
  }
2591
- function projectNamesForServiceStage(projectDir, stage) {
2481
+ function projectNamesForServiceStage(projectDir, stage2) {
2592
2482
  const absDir = resolveProjectDir(projectDir);
2593
2483
  let rawName;
2594
2484
  try {
@@ -2597,7 +2487,7 @@ function projectNamesForServiceStage(projectDir, stage) {
2597
2487
  } catch {
2598
2488
  rawName = path.basename(absDir);
2599
2489
  }
2600
- const s = stage.toLowerCase();
2490
+ const s = stage2.toLowerCase();
2601
2491
  if (s === "dev") {
2602
2492
  return [deriveProjectName(rawName, "dev")];
2603
2493
  }
@@ -2618,14 +2508,14 @@ function projectNamesForServiceStage(projectDir, stage) {
2618
2508
  }
2619
2509
  return [deriveProjectName(rawName, s)];
2620
2510
  }
2621
- function projectNamesForMeshStage(meshDir, stage) {
2511
+ function projectNamesForMeshStage(meshDir, stage2) {
2622
2512
  const absDir = resolveProjectDir(meshDir);
2623
2513
  let rawMeshName = path.basename(absDir);
2624
2514
  try {
2625
2515
  rawMeshName = getMeshJson(absDir).name || rawMeshName;
2626
2516
  } catch {
2627
2517
  }
2628
- const s = stage.toLowerCase();
2518
+ const s = stage2.toLowerCase();
2629
2519
  if (s === "test" || s === "test-e2e") {
2630
2520
  return [deriveProjectName(rawMeshName, "e2e")];
2631
2521
  }
@@ -2635,36 +2525,39 @@ function projectNamesForMeshStage(meshDir, stage) {
2635
2525
  // src/commands/service/commands/down/handler.ts
2636
2526
  async function handleServiceDown(rawStage = "dev", options = {}) {
2637
2527
  const projectDir = resolveProjectDir(options.projectDir);
2638
- const stage = (rawStage || "dev").toLowerCase();
2528
+ const stage2 = (rawStage || "dev").toLowerCase();
2639
2529
  const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
2640
- if (!validStages.includes(stage)) {
2530
+ if (!validStages.includes(stage2)) {
2641
2531
  throw new ScriptError(
2642
2532
  `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
2643
2533
  );
2644
2534
  }
2645
2535
  console.log(
2646
- pc15.cyan(`
2647
- \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
2536
+ pc9.cyan(`
2537
+ \u{1F9F9} Stopping and tearing down service environment [${stage2}]...`)
2648
2538
  );
2649
2539
  if (options.debug) {
2650
2540
  try {
2651
- let env = "dev";
2652
- if (stage === "prod") env = "prod";
2653
- else if (stage === "test" || stage === "test-unit") env = "test";
2654
- else if (stage === "test-e2e") env = "e2e";
2655
- const finalYamlConfig = compileEnvironment(env, projectDir);
2541
+ let env2 = "dev";
2542
+ if (stage2 === "prod") env2 = "prod";
2543
+ else if (stage2 === "test" || stage2 === "test-unit") env2 = "test";
2544
+ else if (stage2 === "test-e2e") env2 = "e2e";
2545
+ const finalYamlConfig = compileEnvironment(env2, projectDir);
2656
2546
  console.log(
2657
- pc15.yellow("Final merged YAML configuration:\n"),
2547
+ pc9.yellow("Final merged YAML configuration:\n"),
2658
2548
  redactYamlSecrets(finalYamlConfig)
2659
2549
  );
2660
2550
  } catch {
2661
2551
  }
2662
2552
  }
2663
2553
  const runState = readRunState(projectDir);
2664
- const candidateProjects = projectNamesForServiceStage(projectDir, stage);
2665
- if (runState?.projectName) {
2666
- candidateProjects.unshift(runState.projectName);
2554
+ if (runState && stage2 !== "test" && runState.stage !== stage2) {
2555
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use builder service down ${runState.stage} -C ${projectDir}`);
2556
+ }
2557
+ if (runState && stage2 === "test" && !["test", "test-unit", "test-e2e"].includes(runState.stage)) {
2558
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use its matching down command`);
2667
2559
  }
2560
+ const candidateProjects = runState?.projectName ? [runState.projectName] : projectNamesForServiceStage(projectDir, stage2);
2668
2561
  const uniqueProjects = Array.from(new Set(candidateProjects));
2669
2562
  for (const proj of uniqueProjects) {
2670
2563
  await teardownCompose("", projectDir, {
@@ -2675,13 +2568,13 @@ async function handleServiceDown(rawStage = "dev", options = {}) {
2675
2568
  }
2676
2569
  clearRunState(projectDir);
2677
2570
  console.log(
2678
- pc15.green(`\u2705 Service environment [${stage}] stopped and removed.
2571
+ pc9.green(`\u2705 Service environment [${stage2}] stopped and removed.
2679
2572
  `)
2680
2573
  );
2681
2574
  return 0;
2682
2575
  }
2683
- function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
2684
- const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
2576
+ function compileMeshEnvironment(stage2, rawMeshDir = process.cwd(), options = {}) {
2577
+ const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage2, meshDir, options), yaml = stringify(compiled.compose);
2685
2578
  if (options.validateWithDocker !== false) {
2686
2579
  const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
2687
2580
  if (result.error || result.status !== 0) throw new ScriptError(`Generated mesh Compose configuration is invalid: ${result.error?.message ?? result.stderr ?? result.stdout}`, { cause: result.error });
@@ -2693,9 +2586,9 @@ function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {})
2693
2586
  function rootServiceDirsForCleanup(meshDir) {
2694
2587
  try {
2695
2588
  const mesh = getMeshJson(meshDir);
2696
- const dirs = Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b)).map(([name, service]) => resolveInsideProject(meshDir, service.path, {
2589
+ const dirs = Object.entries(mesh.services).sort(([a], [b]) => a.localeCompare(b)).filter(([name]) => name !== "tester").map(([name, service]) => resolveInsideProject(meshDir, service.source, {
2697
2590
  sourceFile: path.join(meshDir, "mesh.json"),
2698
- configPath: `services.${name}.path`
2591
+ configPath: `services.${name}.source`
2699
2592
  }));
2700
2593
  return [...new Set(dirs)];
2701
2594
  } catch {
@@ -2703,34 +2596,41 @@ function rootServiceDirsForCleanup(meshDir) {
2703
2596
  }
2704
2597
  }
2705
2598
  async function handleMeshDown(rawStage = "dev", options = {}) {
2706
- const stage = (rawStage || "dev").toLowerCase();
2599
+ const stage2 = (rawStage || "dev").toLowerCase();
2707
2600
  const meshDir = resolveProjectDir(options.projectDir);
2708
- if (stage === "test-unit") {
2601
+ if (stage2 === "test-unit") {
2709
2602
  throw new ScriptError(
2710
2603
  "mesh down test-unit is no longer supported because meshes have no test topology. Use builder service down test-unit -C <service> for service recovery, or builder mesh down test for the complete test pipeline."
2711
2604
  );
2712
2605
  }
2713
- if (!MESH_COMMAND_STAGES.includes(stage)) {
2606
+ if (!MESH_COMMAND_STAGES.includes(stage2)) {
2714
2607
  throw new ScriptError(
2715
2608
  `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
2716
2609
  );
2717
2610
  }
2718
2611
  console.log(
2719
- pc15.cyan(`
2720
- \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
2612
+ pc9.cyan(`
2613
+ \u{1F9F9} Stopping and tearing down global mesh environment [${stage2}]...`)
2721
2614
  );
2722
2615
  if (options.debug) {
2723
2616
  try {
2724
- const mode = stage === "dev" ? "dev" : stage === "test" || stage === "test-e2e" ? "e2e" : "prod";
2617
+ const mode = stage2 === "dev" ? "dev" : stage2 === "test" || stage2 === "test-e2e" ? "e2e" : "prod";
2725
2618
  const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2726
2619
  console.log(
2727
- pc15.yellow("\nFinal merged Mesh YAML configuration:\n"),
2620
+ pc9.yellow("\nFinal merged Mesh YAML configuration:\n"),
2728
2621
  redactYamlSecrets(yaml)
2729
2622
  );
2730
2623
  } catch {
2731
2624
  }
2732
2625
  }
2733
- if (stage === "test") {
2626
+ const runState = readRunState(meshDir);
2627
+ if (runState && stage2 !== "test" && runState.stage !== stage2) {
2628
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use builder mesh down ${runState.stage} -C ${meshDir}`);
2629
+ }
2630
+ if (runState && stage2 === "test" && !["test", "test-e2e"].includes(runState.stage)) {
2631
+ throw new ScriptError(`Saved runtime is for ${runState.stage}; use its matching down command`);
2632
+ }
2633
+ if (stage2 === "test") {
2734
2634
  for (const serviceDir of rootServiceDirsForCleanup(meshDir)) {
2735
2635
  const status = await handleServiceDown("test", {
2736
2636
  projectDir: serviceDir,
@@ -2740,11 +2640,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2740
2640
  if (status !== 0) return status;
2741
2641
  }
2742
2642
  }
2743
- const runState = readRunState(meshDir);
2744
- const candidateProjects = projectNamesForMeshStage(meshDir, stage);
2745
- if (runState?.projectName) {
2746
- candidateProjects.unshift(runState.projectName);
2747
- }
2643
+ const candidateProjects = runState?.projectName ? [runState.projectName] : projectNamesForMeshStage(meshDir, stage2);
2748
2644
  const uniqueProjects = Array.from(new Set(candidateProjects));
2749
2645
  for (const proj of uniqueProjects) {
2750
2646
  await teardownCompose("", meshDir, {
@@ -2755,7 +2651,7 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2755
2651
  }
2756
2652
  clearRunState(meshDir);
2757
2653
  console.log(
2758
- pc15.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
2654
+ pc9.green(`\u2705 Global mesh environment [${stage2}] stopped and removed.
2759
2655
  `)
2760
2656
  );
2761
2657
  return 0;
@@ -2780,8 +2676,8 @@ Examples:
2780
2676
  $ builder mesh down prod
2781
2677
  $ builder mesh down -v`
2782
2678
  ).action(
2783
- async (stage = "dev", options = {}) => {
2784
- const exitCode = await handleMeshDown(stage, {
2679
+ async (stage2 = "dev", options = {}) => {
2680
+ const exitCode = await handleMeshDown(stage2, {
2785
2681
  projectDir: options.projectDir,
2786
2682
  volumes: options.volumes,
2787
2683
  debug: options.debug
@@ -2792,36 +2688,62 @@ Examples:
2792
2688
  }
2793
2689
  );
2794
2690
  };
2795
-
2796
- // src/core/runWithCleanup.ts
2797
- async function runWithCleanup(run, cleanup) {
2798
- let executionFailed = false;
2799
- let executionError;
2691
+ function inspectImage(image, projectDir) {
2692
+ const result = spawnSync("docker", ["image", "inspect", "--format", "{{json .Config}}", image], { cwd: projectDir, encoding: "utf8" });
2693
+ if (result.error || result.status !== 0) throw new Error(`Could not inspect image ${image}: ${result.error?.message ?? result.stderr?.trim() ?? "unknown Docker error"}`);
2800
2694
  try {
2801
- const status = await run();
2802
- if (status !== 0) {
2803
- executionFailed = true;
2804
- executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2805
- }
2806
- return status;
2807
- } catch (error) {
2808
- executionFailed = true;
2809
- executionError = error;
2810
- throw error;
2811
- } finally {
2695
+ return { Config: JSON.parse(result.stdout) };
2696
+ } catch {
2697
+ throw new Error(`Docker returned invalid image metadata for ${image}`);
2698
+ }
2699
+ }
2700
+ function inspectRequiredHealth(checks, projectDir, inspect = inspectImage, stage2 = "prod", composition = "service") {
2701
+ for (const check of checks) {
2702
+ let metadata;
2812
2703
  try {
2813
- await cleanup();
2814
- } catch (cleanupError) {
2815
- if (executionFailed) {
2816
- throw new AggregateError(
2817
- [executionError, cleanupError],
2818
- `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2819
- );
2820
- }
2821
- throw cleanupError;
2704
+ metadata = inspect(check.image, projectDir);
2705
+ } catch (error) {
2706
+ throw new ConfigError({ sourceFile: check.sourceFile, configPath: check.configPath, stage: stage2, composition, reason: `Required image health metadata unavailable for ${check.serviceName}: ${error instanceof Error ? error.message : String(error)}` });
2707
+ }
2708
+ const inherited = metadata.Config?.Healthcheck;
2709
+ const command = inherited && typeof inherited === "object" && !Array.isArray(inherited) ? inherited.Test : void 0;
2710
+ if (!isEnabledValidComposeHealthcheck({ test: command })) throw new ConfigError({ sourceFile: check.sourceFile, configPath: check.configPath, stage: stage2, composition, reason: `Required image healthcheck is absent or disabled for ${check.serviceName}` });
2711
+ }
2712
+ }
2713
+ function validPort(value) {
2714
+ if (!/^\d+$/.test(value)) return void 0;
2715
+ const port2 = Number(value);
2716
+ return Number.isInteger(port2) && port2 >= 1 && port2 <= 65535 ? port2 : void 0;
2717
+ }
2718
+ function parsePublishedHostPort(value) {
2719
+ if (value && typeof value === "object") {
2720
+ const published = value.published;
2721
+ if (typeof published === "number" && Number.isInteger(published)) {
2722
+ return published >= 1 && published <= 65535 ? published : void 0;
2822
2723
  }
2724
+ if (typeof published === "string") return validPort(published);
2725
+ return void 0;
2726
+ }
2727
+ if (typeof value !== "string") return void 0;
2728
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
2729
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
2730
+ if (mapping.startsWith("[")) {
2731
+ const close = mapping.indexOf("]");
2732
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
2733
+ const suffix = mapping.slice(close + 1);
2734
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
2735
+ return match ? validPort(match[1]) : void 0;
2736
+ }
2737
+ const parts = mapping.split(":");
2738
+ if (parts.length === 2) return validPort(parts[0]);
2739
+ if (parts.length >= 3) {
2740
+ const hostIp = parts.slice(0, -2).join(":");
2741
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
2823
2742
  }
2743
+ return void 0;
2824
2744
  }
2745
+
2746
+ // src/utils/checkPortCollision.ts
2825
2747
  function extractHostPorts(yamlConfig) {
2826
2748
  const ports = [];
2827
2749
  try {
@@ -2840,7 +2762,7 @@ function extractHostPorts(yamlConfig) {
2840
2762
  }
2841
2763
  return ports;
2842
2764
  }
2843
- async function isPortInUse(port) {
2765
+ async function isPortInUse(port2) {
2844
2766
  return new Promise((resolve) => {
2845
2767
  const server = net.createServer();
2846
2768
  server.once("error", (err) => {
@@ -2853,16 +2775,46 @@ async function isPortInUse(port) {
2853
2775
  server.once("listening", () => {
2854
2776
  server.close(() => resolve(false));
2855
2777
  });
2856
- server.listen(port, "0.0.0.0");
2778
+ server.listen(port2, "0.0.0.0");
2857
2779
  });
2858
2780
  }
2859
2781
  async function checkHostPortCollisions(ports) {
2860
- for (const port of ports) {
2861
- if (port > 0 && port < 65536) {
2862
- const inUse = await isPortInUse(port);
2782
+ for (const port2 of ports) {
2783
+ if (port2 > 0 && port2 < 65536) {
2784
+ const inUse = await isPortInUse(port2);
2863
2785
  if (inUse) {
2864
- throw new ScriptError(`Host port ${port} is already in use. Builder does not remap fixed public ports.`);
2786
+ throw new ScriptError(`Host port ${port2} is already in use. Builder does not remap fixed public ports.`);
2787
+ }
2788
+ }
2789
+ }
2790
+ }
2791
+
2792
+ // src/core/runWithCleanup.ts
2793
+ async function runWithCleanup(run, cleanup) {
2794
+ let executionFailed = false;
2795
+ let executionError;
2796
+ try {
2797
+ const status = await run();
2798
+ if (status !== 0) {
2799
+ executionFailed = true;
2800
+ executionError = new ScriptError(`Compose execution exited with code ${status}`, { exitCode: status });
2801
+ }
2802
+ return status;
2803
+ } catch (error) {
2804
+ executionFailed = true;
2805
+ executionError = error;
2806
+ throw error;
2807
+ } finally {
2808
+ try {
2809
+ await cleanup();
2810
+ } catch (cleanupError) {
2811
+ if (executionFailed) {
2812
+ throw new AggregateError(
2813
+ [executionError, cleanupError],
2814
+ `Compose execution failed (${errorMessage(executionError)}); cleanup also failed (${errorMessage(cleanupError)}). Saved run state was retained`
2815
+ );
2865
2816
  }
2817
+ throw cleanupError;
2866
2818
  }
2867
2819
  }
2868
2820
  }
@@ -2874,7 +2826,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2874
2826
  return new Promise((resolve, reject) => {
2875
2827
  let child;
2876
2828
  try {
2877
- child = spawn(
2829
+ child = (options.spawnProcess ?? spawn)(
2878
2830
  "docker",
2879
2831
  ["compose", "--project-directory", absProjectDir, "-f", "-", ...args],
2880
2832
  {
@@ -2891,6 +2843,14 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2891
2843
  );
2892
2844
  }
2893
2845
  setActiveChild(child);
2846
+ let timer;
2847
+ if (options.timeoutMs) {
2848
+ timer = setTimeout(() => {
2849
+ child.kill("SIGTERM");
2850
+ reject(new ScriptError(`Compose readiness deadline exceeded after ${options.timeoutMs}ms`));
2851
+ }, options.timeoutMs);
2852
+ timer.unref();
2853
+ }
2894
2854
  child.stdin?.on("error", () => {
2895
2855
  });
2896
2856
  if (child.stdin) {
@@ -2898,6 +2858,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2898
2858
  child.stdin.end();
2899
2859
  }
2900
2860
  child.on("error", (err) => {
2861
+ if (timer) clearTimeout(timer);
2901
2862
  setActiveChild(null);
2902
2863
  unregister();
2903
2864
  reject(
@@ -2907,6 +2868,7 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2907
2868
  );
2908
2869
  });
2909
2870
  child.on("close", (code, signal) => {
2871
+ if (timer) clearTimeout(timer);
2910
2872
  setActiveChild(null);
2911
2873
  unregister();
2912
2874
  if (signal) {
@@ -2919,233 +2881,149 @@ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2919
2881
  });
2920
2882
  }
2921
2883
 
2922
- // src/core/mesh/runners/runMeshDev.ts
2923
- async function runMeshDev(options = {}) {
2924
- const meshDir = resolveProjectDir(options.projectDir);
2925
- console.log(pc15.cyan(`
2926
- \u{1F680} Starting Global DEV Mesh Environment...`));
2927
- const { yaml } = compileMeshEnvironment("dev", meshDir);
2928
- const parsed = parse(yaml);
2929
- const projectName = parsed?.name || "mesh-dev";
2930
- if (options.debug) {
2931
- console.log(
2932
- pc15.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2933
- redactYamlSecrets(yaml)
2934
- );
2884
+ // src/core/runners/runLongLived.ts
2885
+ async function runLongLived(stage2, projectDir, options, compile, composition, adapters = {}) {
2886
+ const compiled = compile(Boolean(options.dryRun)), yaml = stringify(compiled.compose);
2887
+ if (options.debug) console.log(redactYamlSecrets(yaml));
2888
+ if (options.dryRun) return 0;
2889
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2890
+ persistHostPortAllocations(projectDir, compiled.allocations);
2891
+ try {
2892
+ writeRunState(projectDir, { projectName: compiled.projectName, stage: stage2, configStage: stage2, workflow: stage2, composition, projectDir, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: [], allocatedEndpointKeys: [...compiled.allocations.keys()], anonymousVolumeServices: anonymousVolumeServices(compiled.compose.services) });
2893
+ } catch (error) {
2894
+ removeHostPortAllocations(projectDir, [...compiled.allocations.keys()]);
2895
+ throw error;
2935
2896
  }
2936
- if (options.dryRun) {
2937
- console.log(pc15.green("Dry run complete. Compose was not started."));
2938
- return 0;
2939
- }
2940
- const hostPorts = extractHostPorts(yaml);
2941
- await checkHostPortCollisions(hostPorts);
2942
- writeRunState(meshDir, {
2943
- projectName,
2944
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2945
- stage: "dev",
2946
- projectDir: meshDir
2897
+ let succeeded = false;
2898
+ return runWithCleanup(async () => {
2899
+ const built = compiled.runtimeServiceNames.filter((name) => compiled.compose.services[name]?.build !== void 0);
2900
+ const images = compiled.runtimeServiceNames.filter((name) => compiled.compose.services[name]?.build === void 0 && compiled.compose.services[name]?.image !== void 0);
2901
+ if (built.length) {
2902
+ const result = await (adapters.compose ?? runCompose)(["build", ...built], yaml, projectDir, { removeVolumes: false });
2903
+ if (result !== 0) return result;
2904
+ }
2905
+ if (images.length) {
2906
+ const result = await (adapters.compose ?? runCompose)(["pull", "--policy", "missing", ...images], yaml, projectDir, { removeVolumes: false });
2907
+ if (result !== 0) return result;
2908
+ }
2909
+ inspectRequiredHealth(compiled.deferredHealthChecks, projectDir, adapters.inspectImage, stage2, composition);
2910
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2911
+ const status = await (adapters.compose ?? runCompose)(["up", "--no-build", ...options.detach ? ["--detach"] : [], ...compiled.runtimeServiceNames], yaml, projectDir, { removeVolumes: false });
2912
+ succeeded = status === 0;
2913
+ return status;
2914
+ }, async () => {
2915
+ if (options.detach && succeeded) return;
2916
+ await (adapters.teardown ?? teardownCompose)(yaml, projectDir, { removeVolumes: false });
2917
+ removeHostPortAllocations(projectDir, [...compiled.allocations.keys()]);
2918
+ clearRunState(projectDir);
2947
2919
  });
2948
- const upArgs = ["up", "--build"];
2949
- if (options.detach) {
2950
- upArgs.push("-d");
2951
- }
2952
- const status = await runWithCleanup(
2953
- () => runCompose(upArgs, yaml, meshDir, {
2954
- removeVolumes: false
2955
- }),
2956
- async () => {
2957
- if (!options.detach) {
2958
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2959
- clearRunState(meshDir);
2960
- }
2961
- }
2962
- );
2963
- return status;
2964
2920
  }
2965
- async function runMeshProd(options = {}) {
2966
- const meshDir = resolveProjectDir(options.projectDir);
2967
- console.log(pc15.cyan(`
2968
- \u{1F3ED} Starting Global PROD Mesh Environment...`));
2969
- const { yaml } = compileMeshEnvironment("prod", meshDir);
2970
- const parsed = parse(yaml);
2971
- const projectName = parsed?.name || "mesh-prod";
2972
- if (options.debug) {
2973
- console.log(
2974
- pc15.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2975
- redactYamlSecrets(yaml)
2976
- );
2977
- }
2978
- if (options.dryRun) {
2979
- console.log(pc15.green("Dry run complete. Compose was not started."));
2980
- return 0;
2981
- }
2982
- const hostPorts = extractHostPorts(yaml);
2983
- await checkHostPortCollisions(hostPorts);
2984
- writeRunState(meshDir, {
2985
- projectName,
2986
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
2987
- stage: "prod",
2988
- projectDir: meshDir
2921
+
2922
+ // src/core/mesh/runners/runMeshDev.ts
2923
+ var runMeshDev = (options = {}) => {
2924
+ const root = resolveProjectDir(options.projectDir);
2925
+ return runLongLived("dev", root, options, (validationMode) => compileMeshComposition("dev", root, { validationMode }), "mesh");
2926
+ };
2927
+
2928
+ // src/core/mesh/runners/runMeshProd.ts
2929
+ var runMeshProd = (options = {}) => {
2930
+ const root = resolveProjectDir(options.projectDir);
2931
+ return runLongLived("prod", root, options, (validationMode) => compileMeshComposition("prod", root, { validationMode }), "mesh");
2932
+ };
2933
+ async function runTestUnit(options, adapters = {}) {
2934
+ const compiled = compileServiceComposition("test", options.projectDir, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
2935
+ const main = compiled.mainServiceNames.get(nodeId(void 0, "main"));
2936
+ if (options.debug) console.log(redactYamlSecrets(yaml));
2937
+ if (options.dryRun) return 0;
2938
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2939
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true, silent: true });
2940
+ persistHostPortAllocations(options.projectDir, compiled.allocations);
2941
+ writeRunState(options.projectDir, { projectName: compiled.projectName, stage: "test-unit", configStage: "test", workflow: "test", composition: "service", projectDir: options.projectDir, runtimeServiceNames: [main], testerServiceNames: [], allocatedEndpointKeys: [...compiled.allocations.keys()] });
2942
+ return runWithCleanup(() => (adapters.compose ?? runCompose)(["up", "--build", "--abort-on-container-exit", "--exit-code-from", main, main], yaml, options.projectDir, { removeVolumes: true }), async () => {
2943
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true });
2944
+ removeHostPortAllocations(options.projectDir, [...compiled.allocations.keys()]);
2945
+ clearRunState(options.projectDir);
2989
2946
  });
2990
- const upArgs = ["up", "--build"];
2991
- if (options.detach) {
2992
- upArgs.push("-d");
2993
- }
2994
- const status = await runWithCleanup(
2995
- () => runCompose(upArgs, yaml, meshDir, {
2996
- removeVolumes: false
2997
- }),
2998
- async () => {
2999
- if (!options.detach) {
3000
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
3001
- clearRunState(meshDir);
3002
- }
3003
- }
3004
- );
3005
- return status;
3006
2947
  }
3007
- var runTestUnit = async (options) => {
3008
- if (!options.skipBanner) {
3009
- console.log(pc15.bold(pc15.blue(`
3010
- ========================================`)));
3011
- console.log(pc15.bold(pc15.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
3012
- console.log(pc15.bold(pc15.blue(`========================================
3013
- `)));
3014
- }
3015
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
3016
- silenceWarnings: options.silenceWarnings
3017
- });
3018
- const parsed = parse(finalYamlConfig);
3019
- const projectName = parsed?.name || "test";
3020
- if (options.debug) {
3021
- console.log(
3022
- pc15.yellow("Final merged YAML configuration:\n"),
3023
- redactYamlSecrets(finalYamlConfig)
3024
- );
3025
- }
3026
- if (options.dryRun) {
3027
- console.log(pc15.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
3028
- return 0;
2948
+ function inspectRunnerExit(yaml, projectDir, runner) {
2949
+ const ps = spawnSync("docker", ["compose", "--project-directory", projectDir, "-f", "-", "ps", "-aq", runner], { cwd: projectDir, encoding: "utf8", input: yaml });
2950
+ const id = ps.stdout?.trim();
2951
+ if (ps.status !== 0 || !id) return void 0;
2952
+ const inspected = spawnSync("docker", ["inspect", "--format", "{{.State.ExitCode}}", id], { cwd: projectDir, encoding: "utf8" });
2953
+ const code = Number(inspected.stdout?.trim());
2954
+ return inspected.status === 0 && Number.isInteger(code) ? code : void 0;
2955
+ }
2956
+ async function runFiniteTester(compiled, projectDir, adapters = {}) {
2957
+ const compose = adapters.compose ?? runCompose;
2958
+ if (!compiled.testerServiceName) throw new Error("Finite tester composition has no selected runner");
2959
+ const yaml = stringify(compiled.compose);
2960
+ const members = [.../* @__PURE__ */ new Set([...compiled.runtimeServiceNames, ...compiled.testerServiceNames])];
2961
+ const built = members.filter((name) => compiled.compose.services[name]?.build !== void 0);
2962
+ const images = members.filter((name) => compiled.compose.services[name]?.build === void 0 && compiled.compose.services[name]?.image !== void 0);
2963
+ if (built.length) {
2964
+ const buildStatus = await compose(["build", ...built], yaml, projectDir, { removeVolumes: true });
2965
+ if (buildStatus !== 0) return buildStatus;
2966
+ }
2967
+ if (images.length) {
2968
+ const pullStatus = await compose(["pull", "--policy", "missing", ...images], yaml, projectDir, { removeVolumes: true });
2969
+ if (pullStatus !== 0) return pullStatus;
2970
+ }
2971
+ inspectRequiredHealth(compiled.deferredHealthChecks ?? [], projectDir, adapters.inspectImage, "e2e", [...compiled.graph.nodes.values()].some((node) => node.meshRoot !== void 0) ? "mesh" : "service");
2972
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
2973
+ let startStatus;
2974
+ try {
2975
+ startStatus = await compose(["up", "--no-build", "--detach", ...members], yaml, projectDir, { removeVolumes: true, timeoutMs: 12e4 });
2976
+ } catch (error) {
2977
+ throw new Error(`Tester startup failed while waiting for ${members.join(", ")}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
3029
2978
  }
3030
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3031
- await teardownCompose(finalYamlConfig, options.projectDir, {
3032
- removeVolumes: true,
3033
- silent: true
3034
- });
3035
- writeRunState(options.projectDir, {
3036
- projectName,
3037
- stage: "test-unit",
3038
- projectDir: options.projectDir
3039
- });
3040
- const status = await runWithCleanup(
3041
- () => runCompose(
3042
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
3043
- finalYamlConfig,
3044
- options.projectDir,
3045
- { removeVolumes: true }
3046
- ),
3047
- async () => {
3048
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3049
- clearRunState(options.projectDir);
2979
+ if (startStatus !== 0) {
2980
+ try {
2981
+ await compose(["logs", "--no-color"], yaml, projectDir, { removeVolumes: true });
2982
+ } catch (error) {
2983
+ console.warn("Could not collect startup logs", error);
3050
2984
  }
3051
- );
3052
- if (status === 0) {
3053
- console.log(pc15.bold(pc15.green(`
3054
- \u2705 Unit tests passed successfully.
3055
- `)));
3056
- } else {
3057
- console.error(pc15.red(`
3058
- \u274C Unit tests failed with exit code ${status}.
3059
- `));
2985
+ return startStatus;
2986
+ }
2987
+ const waited = await compose(["wait", compiled.testerServiceName], yaml, projectDir, { removeVolumes: true });
2988
+ const inspected = (adapters.inspectRunnerExit ?? inspectRunnerExit)(yaml, projectDir, compiled.testerServiceName);
2989
+ const status = inspected ?? (waited === 0 ? 1 : waited);
2990
+ try {
2991
+ await compose(["logs", "--no-color"], yaml, projectDir, { removeVolumes: true });
2992
+ } catch (error) {
2993
+ console.warn("Could not collect tester logs", error);
3060
2994
  }
3061
2995
  return status;
3062
- };
3063
-
3064
- // src/core/runners/runFiniteTester.ts
3065
- async function runFiniteTester(yaml, projectDir, testerServiceName) {
3066
- const startStatus = await runCompose(
3067
- ["up", "--build", "--detach"],
3068
- yaml,
3069
- projectDir,
3070
- { removeVolumes: true }
3071
- );
3072
- if (startStatus !== 0) return startStatus;
3073
- const testerStatus = await runCompose(
3074
- ["wait", testerServiceName],
3075
- yaml,
3076
- projectDir,
3077
- { removeVolumes: true }
3078
- );
3079
- await runCompose(["logs", "--no-color"], yaml, projectDir, {
3080
- removeVolumes: true
3081
- });
3082
- return testerStatus;
3083
2996
  }
3084
2997
 
3085
2998
  // src/core/runners/runTestE2e.ts
3086
- var runTestE2e = async (options) => {
3087
- if (!options.skipBanner) {
3088
- console.log(pc15.bold(pc15.blue(`
3089
- ========================================`)));
3090
- console.log(pc15.bold(pc15.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
3091
- console.log(pc15.bold(pc15.blue(`========================================
3092
- `)));
3093
- }
3094
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
3095
- silenceWarnings: options.silenceWarnings
3096
- });
3097
- const parsed = parse(finalYamlConfig);
3098
- const projectName = parsed?.name || "e2e";
3099
- if (options.debug) {
3100
- console.log(
3101
- pc15.yellow("Final merged YAML configuration:\n"),
3102
- redactYamlSecrets(finalYamlConfig)
3103
- );
3104
- }
3105
- if (options.dryRun) {
3106
- console.log(pc15.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
3107
- return 0;
3108
- }
3109
- await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
3110
- await teardownCompose(finalYamlConfig, options.projectDir, {
3111
- removeVolumes: true,
3112
- silent: true
2999
+ async function runTestE2e(options, adapters = {}) {
3000
+ const compiled = compileServiceComposition("e2e", options.projectDir, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
3001
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3002
+ if (options.dryRun) return 0;
3003
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
3004
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true, silent: true });
3005
+ persistHostPortAllocations(options.projectDir, compiled.allocations);
3006
+ writeRunState(options.projectDir, { projectName: compiled.projectName, stage: "test-e2e", configStage: "e2e", workflow: "test", composition: "service", projectDir: options.projectDir, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: compiled.testerServiceNames, allocatedEndpointKeys: [...compiled.allocations.keys()] });
3007
+ return runWithCleanup(() => runFiniteTester(compiled, options.projectDir, adapters.finite), async () => {
3008
+ await (adapters.teardown ?? teardownCompose)(yaml, options.projectDir, { removeVolumes: true });
3009
+ removeHostPortAllocations(options.projectDir, [...compiled.allocations.keys()]);
3010
+ clearRunState(options.projectDir);
3113
3011
  });
3114
- writeRunState(options.projectDir, {
3115
- projectName,
3116
- stage: "test-e2e",
3117
- projectDir: options.projectDir
3118
- });
3119
- const status = await runWithCleanup(
3120
- () => runFiniteTester(finalYamlConfig, options.projectDir, "tester"),
3121
- async () => {
3122
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3123
- clearRunState(options.projectDir);
3124
- }
3125
- );
3126
- if (status === 0) {
3127
- console.log(pc15.bold(pc15.green(`
3128
- \u2705 E2E tests passed successfully.
3129
- `)));
3130
- } else {
3131
- console.error(pc15.red(`
3132
- \u274C E2E tests failed with exit code ${status}.
3133
- `));
3134
- }
3135
- return status;
3136
- };
3012
+ }
3137
3013
 
3138
3014
  // src/core/runners/runTest.ts
3139
- var runTest = async (options) => {
3140
- console.log(pc15.bold(pc15.blue(`
3015
+ var runTest = async (options, adapters = {}) => {
3016
+ compileServiceComposition("test", options.projectDir, { validationMode: true });
3017
+ compileServiceComposition("e2e", options.projectDir, { validationMode: true });
3018
+ console.log(pc9.bold(pc9.blue(`
3141
3019
  ========================================`)));
3142
- console.log(pc15.bold(pc15.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3143
- console.log(pc15.bold(pc15.blue(`========================================
3020
+ console.log(pc9.bold(pc9.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3021
+ console.log(pc9.bold(pc9.blue(`========================================
3144
3022
  `)));
3145
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3023
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true }, adapters.unit);
3146
3024
  if (unitStatus !== 0) {
3147
3025
  console.error(
3148
- pc15.red(
3026
+ pc9.red(
3149
3027
  `
3150
3028
  \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3151
3029
  `
@@ -3154,29 +3032,29 @@ var runTest = async (options) => {
3154
3032
  return unitStatus;
3155
3033
  }
3156
3034
  console.log(
3157
- pc15.bold(pc15.green(`
3035
+ pc9.bold(pc9.green(`
3158
3036
  \u2705 [1/2] Unit tests passed successfully.
3159
3037
  `))
3160
3038
  );
3161
- console.log(pc15.bold(pc15.blue(`========================================`)));
3162
- console.log(pc15.bold(pc15.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3163
- console.log(pc15.bold(pc15.blue(`========================================
3039
+ console.log(pc9.bold(pc9.blue(`========================================`)));
3040
+ console.log(pc9.bold(pc9.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3041
+ console.log(pc9.bold(pc9.blue(`========================================
3164
3042
  `)));
3165
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3043
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true }, adapters.e2e);
3166
3044
  if (e2eStatus !== 0) {
3167
3045
  console.error(
3168
- pc15.red(`
3046
+ pc9.red(`
3169
3047
  \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3170
3048
  `)
3171
3049
  );
3172
3050
  return e2eStatus;
3173
3051
  }
3174
- console.log(pc15.bold(pc15.green(`
3052
+ console.log(pc9.bold(pc9.green(`
3175
3053
  \u2705 [2/2] E2E tests passed successfully.
3176
3054
  `)));
3177
3055
  console.log(
3178
- pc15.bold(
3179
- pc15.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3056
+ pc9.bold(
3057
+ pc9.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3180
3058
  `)
3181
3059
  )
3182
3060
  );
@@ -3184,88 +3062,81 @@ var runTest = async (options) => {
3184
3062
  };
3185
3063
 
3186
3064
  // src/core/mesh/runners/runMeshServiceTests.ts
3187
- async function runMeshServiceTests(options = {}) {
3065
+ async function runMeshServiceTests(options = {}, runtime = {}) {
3188
3066
  const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), mesh = getMeshJson(meshDir);
3189
- const rootServices = Object.entries(mesh.services).sort(([left], [right]) => left.localeCompare(right));
3067
+ const rootServices = Object.entries(mesh.services).filter(([name]) => name !== "tester").sort(([left], [right]) => left.localeCompare(right));
3190
3068
  for (const [serviceName, service] of rootServices) {
3191
- const serviceDir = resolveInsideProject(meshDir, service.path, { sourceFile: meshPath, configPath: `services.${serviceName}.path`, stage: "test" });
3192
- console.log(pc15.bold(pc15.cyan(`
3069
+ const serviceDir = resolveInsideProject(meshDir, service.source, { sourceFile: meshPath, configPath: `services.${serviceName}.source`, stage: "test" });
3070
+ console.log(pc9.bold(pc9.cyan(`
3193
3071
  -> Running full standalone test lifecycle for [${serviceName}]
3194
3072
  `)));
3195
- const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} });
3073
+ const status = await runTest({ projectDir: serviceDir, debug: Boolean(options.debug), detach: false, skipBanner: true, silenceWarnings: false, ...options.dryRun !== void 0 ? { dryRun: options.dryRun } : {} }, runtime);
3196
3074
  if (status !== 0) return status;
3197
3075
  }
3198
3076
  return 0;
3199
3077
  }
3200
- async function runMeshTestE2e(options = {}) {
3201
- const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
3202
- if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
3203
- const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
3204
- if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
3205
- if (options.debug) console.log(pc15.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
3206
- if (options.dryRun) {
3207
- console.log(pc15.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
3208
- return 0;
3209
- }
3210
- await checkHostPortCollisions(extractHostPorts(yaml));
3211
- const projectName = parse(yaml)?.name || "mesh-e2e";
3212
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3213
- writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
3214
- const status = await runWithCleanup(() => runFiniteTester(yaml, meshDir, testerServiceName), async () => {
3215
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
3216
- clearRunState(meshDir);
3078
+ async function runMeshTestE2e(options = {}, adapters = {}) {
3079
+ const root = resolveProjectDir(options.projectDir), compiled = compileMeshComposition("e2e", root, { validationMode: Boolean(options.dryRun) }), yaml = stringify(compiled.compose);
3080
+ if (options.debug) console.log(redactYamlSecrets(yaml));
3081
+ if (options.dryRun) return 0;
3082
+ await (adapters.checkPorts ?? checkHostPortCollisions)(extractHostPorts(yaml));
3083
+ await (adapters.teardown ?? teardownCompose)(yaml, root, { removeVolumes: true, silent: true });
3084
+ persistHostPortAllocations(root, compiled.allocations);
3085
+ writeRunState(root, { projectName: compiled.projectName, stage: "test-e2e", configStage: "e2e", workflow: "test", composition: "mesh", projectDir: root, runtimeServiceNames: compiled.runtimeServiceNames, testerServiceNames: compiled.testerServiceNames, allocatedEndpointKeys: [...compiled.allocations.keys()] });
3086
+ return runWithCleanup(() => runFiniteTester(compiled, root, adapters.finite), async () => {
3087
+ await (adapters.teardown ?? teardownCompose)(yaml, root, { removeVolumes: true });
3088
+ removeHostPortAllocations(root, [...compiled.allocations.keys()]);
3089
+ clearRunState(root);
3217
3090
  });
3218
- return status;
3219
3091
  }
3220
3092
 
3221
3093
  // src/core/mesh/runners/runMeshTest.ts
3222
- async function runMeshTest(options = {}) {
3223
- console.log(pc15.bold(pc15.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3224
- console.log(pc15.bold(pc15.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3225
- const serviceStatus = await runMeshServiceTests(options);
3094
+ async function runMeshTest(options = {}, runtime = {}) {
3095
+ compileMeshComposition("e2e", resolveProjectDir(options.projectDir), { validationMode: true });
3096
+ console.log(pc9.bold(pc9.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
3097
+ console.log(pc9.bold(pc9.blue("[1/2] ROOT SERVICE TEST LIFECYCLES")));
3098
+ const serviceStatus = await runMeshServiceTests(options, runtime.source);
3226
3099
  if (serviceStatus !== 0) return serviceStatus;
3227
- console.log(pc15.bold(pc15.blue("[2/2] GLOBAL MESH E2E")));
3228
- return runMeshTestE2e(options);
3100
+ console.log(pc9.bold(pc9.blue("[2/2] GLOBAL MESH E2E")));
3101
+ return runMeshTestE2e(options, runtime.global);
3229
3102
  }
3230
3103
 
3231
3104
  // src/commands/mesh/commands/up/handler.ts
3232
3105
  async function handleMeshUp(rawStage = "dev", options = {}) {
3233
- const stage = (rawStage || "dev").toLowerCase();
3234
- if (stage === "test-unit") {
3106
+ const stage2 = (rawStage || "dev").toLowerCase();
3107
+ if (["test-unit", "test-e2e", "e2e"].includes(stage2)) {
3235
3108
  throw new ScriptError(
3236
- "mesh up test-unit is no longer supported because meshes have no test topology. Use builder service up test-unit -C <service> for isolated tests, or builder mesh up test for the complete test pipeline."
3109
+ `mesh up ${stage2} is not a public target. Use builder service up test-unit -C <service> for isolated tests, or builder mesh up test for the complete test pipeline.`
3237
3110
  );
3238
3111
  }
3239
- if (!MESH_COMMAND_STAGES.includes(stage)) {
3112
+ if (!MESH_COMMAND_STAGES.includes(stage2)) {
3240
3113
  throw new ScriptError(
3241
3114
  `Unknown mesh stage: "${rawStage}". Supported stages: ${MESH_COMMAND_STAGES.join(", ")}`
3242
3115
  );
3243
3116
  }
3244
3117
  const projectDir = resolveProjectDir(options.projectDir);
3118
+ if (options.detach && stage2 === "test") throw new ScriptError("--detach applies only to mesh dev/prod; mesh test is finite");
3245
3119
  const runOptions = { ...options, projectDir };
3246
- if (!options.skipChecks) {
3120
+ if (!options.skipChecks && !options.dryRun) {
3247
3121
  checkMesh(projectDir, {
3248
- requireTester: stage === "test" || stage === "test-e2e"
3249
- });
3122
+ });
3250
3123
  }
3251
- switch (stage) {
3124
+ switch (stage2) {
3252
3125
  case "dev":
3253
3126
  return runMeshDev(runOptions);
3254
3127
  case "prod":
3255
3128
  return runMeshProd(runOptions);
3256
3129
  case "test":
3257
3130
  return runMeshTest(runOptions);
3258
- case "test-e2e":
3259
- return runMeshTestE2e(runOptions);
3260
3131
  default:
3261
- throw new ScriptError(`Unsupported mesh command: ${stage}`);
3132
+ throw new ScriptError(`Unsupported mesh command: ${stage2}`);
3262
3133
  }
3263
3134
  }
3264
3135
 
3265
3136
  // src/commands/mesh/commands/up/command.ts
3266
3137
  var registerMeshUpCommand = (cmd) => {
3267
3138
  cmd.command("up [stage]").description(
3268
- "Start, build, or test the mesh environment (dev, prod, test, test-e2e)"
3139
+ "Start or test the mesh environment (dev, prod, test)"
3269
3140
  ).option("--debug", "Output the merged Docker Compose YAML configuration").option("-d, --detach", "Run containers in the background").option(
3270
3141
  "--dry-run",
3271
3142
  "Compile configuration and validate checks without starting containers"
@@ -3285,14 +3156,12 @@ Examples:
3285
3156
  $ builder mesh up dev
3286
3157
  $ builder mesh up prod
3287
3158
  $ builder mesh up test
3288
- $ builder mesh up test-e2e
3289
-
3290
- Mesh JSON overlays: dev, prod, e2e. test-e2e uses base -> prod -> e2e.
3159
+ Mesh JSON overlays: dev, prod, e2e. The test workflow uses base -> prod -> e2e internally.
3291
3160
  The test command runs each root service test lifecycle (unit, then service E2E) before global E2E.
3292
3161
  For a service\u2019s isolated tests: builder service up test-unit -C <service>.`
3293
3162
  ).action(
3294
- async (stage = "dev", options = {}) => {
3295
- const exitCode = await handleMeshUp(stage, {
3163
+ async (stage2 = "dev", options = {}) => {
3164
+ const exitCode = await handleMeshUp(stage2, {
3296
3165
  projectDir: options.projectDir,
3297
3166
  debug: options.debug,
3298
3167
  detach: options.detach,
@@ -3309,49 +3178,38 @@ For a service\u2019s isolated tests: builder service up test-unit -C <service>.`
3309
3178
  // src/commands/mesh/command.ts
3310
3179
  var registerMeshCommand = (program) => {
3311
3180
  const meshCmd = program.command("mesh").description("Manage and orchestrate multi-service mesh environments");
3312
- meshCmd.hook("preAction", () => {
3181
+ meshCmd.hook("preAction", (_thisCommand, actionCommand) => {
3182
+ if (actionCommand.name() === "up") {
3183
+ const options = actionCommand.opts(), stage2 = actionCommand.args[0]?.toLowerCase();
3184
+ if (options.dryRun || stage2 && !["dev", "prod", "test"].includes(stage2)) return;
3185
+ }
3313
3186
  checkDependencies();
3314
3187
  });
3315
3188
  registerMeshUpCommand(meshCmd);
3316
3189
  registerMeshDownCommand(meshCmd);
3317
3190
  registerMeshCheckCommand(meshCmd);
3318
3191
  };
3319
- async function handlePrune(options = {}) {
3320
- console.log(pc15.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3321
- const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
3322
- stdio: "inherit",
3323
- encoding: "utf-8"
3324
- });
3325
- if (rmContainers.error) {
3326
- throw new ScriptError(`Failed to prune containers: ${rmContainers.error.message}`, {
3327
- cause: rmContainers.error
3328
- });
3329
- }
3330
- const rmNetworks = spawnSync("docker", ["network", "prune", "-f"], {
3331
- stdio: "inherit",
3332
- encoding: "utf-8"
3333
- });
3334
- if (rmNetworks.error) {
3335
- throw new ScriptError(`Failed to prune networks: ${rmNetworks.error.message}`, {
3336
- cause: rmNetworks.error
3337
- });
3338
- }
3339
- if (options.volumes) {
3340
- console.log(pc15.cyan("\u{1F9F9} Pruning dangling volumes..."));
3341
- spawnSync("docker", ["volume", "prune", "-f"], {
3342
- stdio: "inherit",
3343
- encoding: "utf-8"
3344
- });
3192
+ async function handlePrune(options = {}, spawn3 = spawnSync) {
3193
+ const filter = `label=${BUILDER_OWNER_LABEL}=true`;
3194
+ for (const kind of ["container", "network", ...options.volumes ? ["volume"] : []]) {
3195
+ const args = [kind, "prune", "-f", "--filter", filter];
3196
+ if (options.dryRun) {
3197
+ console.log(`docker ${args.join(" ")}`);
3198
+ continue;
3199
+ }
3200
+ const result = spawn3("docker", args, { stdio: "inherit", encoding: "utf-8" });
3201
+ if (result.error || result.status !== 0) throw new ScriptError(`Failed to prune Builder ${kind}s: ${result.error?.message ?? result.stderr ?? `exit code ${result.status}`}`);
3345
3202
  }
3346
- console.log(pc15.green("\u2705 Docker environment pruned successfully.\n"));
3203
+ if (!options.dryRun) console.log(pc9.green("Builder-owned Docker resources pruned."));
3347
3204
  return 0;
3348
3205
  }
3349
3206
 
3350
3207
  // src/commands/prune/command.ts
3351
3208
  var registerPruneCommand = (cmd) => {
3352
- cmd.command("prune").description("Remove stopped containers, unused networks, and dangling resources").option("-v, --volumes", "Also prune dangling anonymous volumes").action(async (options = {}) => {
3209
+ cmd.command("prune").description("Remove stopped Builder-owned containers, networks, and dangling resources").option("-v, --volumes", "Also prune dangling anonymous volumes").option("--dry-run", "Print scoped prune commands without running Docker").action(async (options = {}) => {
3353
3210
  const exitCode = await handlePrune({
3354
- volumes: Boolean(options.volumes)
3211
+ volumes: Boolean(options.volumes),
3212
+ dryRun: Boolean(options.dryRun)
3355
3213
  });
3356
3214
  if (exitCode !== 0) {
3357
3215
  process.exit(exitCode);
@@ -3381,8 +3239,8 @@ Examples:
3381
3239
  $ builder service down prod
3382
3240
  $ builder service down -v`
3383
3241
  ).action(
3384
- async (stage = "dev", options = {}) => {
3385
- const exitCode = await handleServiceDown(stage, {
3242
+ async (stage2 = "dev", options = {}) => {
3243
+ const exitCode = await handleServiceDown(stage2, {
3386
3244
  projectDir: options.projectDir,
3387
3245
  volumes: options.volumes,
3388
3246
  debug: options.debug
@@ -3393,105 +3251,20 @@ Examples:
3393
3251
  }
3394
3252
  );
3395
3253
  };
3396
- var runDev = async (options) => {
3397
- console.log(
3398
- pc15.cyan(
3399
- options.full ? `\u{1F680} Starting DEV environment (full / integrated)...` : `\u{1F680} Starting DEV environment...`
3400
- )
3401
- );
3402
- const finalYamlConfig = compileEnvironment("dev", options.projectDir, {
3403
- silenceWarnings: options.silenceWarnings,
3404
- full: options.full
3405
- });
3406
- const parsed = parse(finalYamlConfig);
3407
- const projectName = parsed?.name || "dev";
3408
- if (options.debug) {
3409
- console.log(
3410
- pc15.yellow("Final merged YAML configuration:\n"),
3411
- redactYamlSecrets(finalYamlConfig)
3412
- );
3413
- }
3414
- if (options.dryRun) {
3415
- console.log(pc15.green("Dry run complete. Compose was not started."));
3416
- return 0;
3417
- }
3418
- const hostPorts = extractHostPorts(finalYamlConfig);
3419
- await checkHostPortCollisions(hostPorts);
3420
- writeRunState(options.projectDir, {
3421
- projectName,
3422
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3423
- stage: "dev",
3424
- projectDir: options.projectDir
3425
- });
3426
- const upArgs = ["up", "--build"];
3427
- if (options.detach) {
3428
- upArgs.push("-d");
3429
- }
3430
- const status = await runWithCleanup(
3431
- () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
3432
- removeVolumes: false
3433
- }),
3434
- async () => {
3435
- if (!options.detach) {
3436
- await teardownCompose(finalYamlConfig, options.projectDir, {
3437
- removeVolumes: false
3438
- });
3439
- clearRunState(options.projectDir);
3440
- }
3441
- }
3442
- );
3443
- return status;
3444
- };
3445
- var runProd = async (options) => {
3446
- console.log(pc15.cyan(`\u{1F3ED} Starting PROD environment...`));
3447
- const finalYamlConfig = compileEnvironment("prod", options.projectDir, {
3448
- silenceWarnings: options.silenceWarnings
3449
- });
3450
- const parsed = parse(finalYamlConfig);
3451
- const projectName = parsed?.name || "prod";
3452
- if (options.debug) {
3453
- console.log(
3454
- pc15.yellow("Final merged YAML configuration:\n"),
3455
- redactYamlSecrets(finalYamlConfig)
3456
- );
3457
- }
3458
- if (options.dryRun) {
3459
- console.log(pc15.green("Dry run complete. Compose was not started."));
3460
- return 0;
3461
- }
3462
- const hostPorts = extractHostPorts(finalYamlConfig);
3463
- await checkHostPortCollisions(hostPorts);
3464
- writeRunState(options.projectDir, {
3465
- projectName,
3466
- anonymousVolumeServices: anonymousVolumeServices(parsed?.services ?? {}),
3467
- stage: "prod",
3468
- projectDir: options.projectDir
3469
- });
3470
- const upArgs = ["up", "--build"];
3471
- if (options.detach) {
3472
- upArgs.push("-d");
3473
- }
3474
- const status = await runWithCleanup(
3475
- () => runCompose(upArgs, finalYamlConfig, options.projectDir, {
3476
- removeVolumes: false
3477
- }),
3478
- async () => {
3479
- if (!options.detach) {
3480
- await teardownCompose(finalYamlConfig, options.projectDir, {
3481
- removeVolumes: false
3482
- });
3483
- clearRunState(options.projectDir);
3484
- }
3485
- }
3486
- );
3487
- return status;
3488
- };
3254
+
3255
+ // src/core/runners/runDev.ts
3256
+ var runDev = (options) => runLongLived("dev", options.projectDir, options, (validationMode) => compileServiceComposition("dev", options.projectDir, { full: options.full, validationMode }), "service");
3257
+
3258
+ // src/core/runners/runProd.ts
3259
+ var runProd = (options) => runLongLived("prod", options.projectDir, options, (validationMode) => compileServiceComposition("prod", options.projectDir, { validationMode }), "service");
3489
3260
 
3490
3261
  // src/commands/service/commands/up/handler.ts
3491
3262
  async function handleServiceUp(rawStage, options = {}) {
3492
3263
  const projectDir = resolveProjectDir(options.projectDir);
3493
- const stage = (rawStage || "dev").toLowerCase();
3264
+ const stage2 = (rawStage || "dev").toLowerCase();
3494
3265
  const isFull = Boolean(options.full);
3266
+ if (isFull && stage2 !== "dev") throw new ScriptError("--full applies only to service dev");
3267
+ if (options.detach && !["dev", "prod"].includes(stage2)) throw new ScriptError("--detach applies only to dev/prod; tests are finite");
3495
3268
  const runOptions = {
3496
3269
  projectDir,
3497
3270
  debug: Boolean(options.debug),
@@ -3500,19 +3273,19 @@ async function handleServiceUp(rawStage, options = {}) {
3500
3273
  silenceWarnings: Boolean(options.silenceWarnings),
3501
3274
  full: isFull
3502
3275
  };
3503
- if (stage === "dev") {
3276
+ if (stage2 === "dev") {
3504
3277
  return await runDev(runOptions);
3505
3278
  }
3506
- if (stage === "prod") {
3279
+ if (stage2 === "prod") {
3507
3280
  return await runProd(runOptions);
3508
3281
  }
3509
- if (stage === "test-unit") {
3282
+ if (stage2 === "test-unit") {
3510
3283
  return await runTestUnit(runOptions);
3511
3284
  }
3512
- if (stage === "test-e2e") {
3285
+ if (stage2 === "test-e2e") {
3513
3286
  return await runTestE2e(runOptions);
3514
3287
  }
3515
- if (stage === "test") {
3288
+ if (stage2 === "test") {
3516
3289
  return await runTest(runOptions);
3517
3290
  }
3518
3291
  throw new ScriptError(
@@ -3535,7 +3308,7 @@ var registerUpCommand = (cmd) => {
3535
3308
  "Silence non-critical warnings like URL templating hints"
3536
3309
  ).option(
3537
3310
  "--full",
3538
- "Run dev with all declared local dependencies integrated"
3311
+ "Run dev with the full effective requisite graph"
3539
3312
  ).option(
3540
3313
  "-C, --project-dir <dir>",
3541
3314
  "Service project directory (defaults to cwd)"
@@ -3551,10 +3324,11 @@ Examples:
3551
3324
  $ builder service up test-e2e
3552
3325
 
3553
3326
  JSON overlays: test-unit uses build.json test; test-e2e uses build.json e2e.
3327
+ These convenience workflow names do not select Dockerfile targets. Main targets are dev, test, and prod.
3554
3328
  The test command runs unit tests before E2E.`
3555
3329
  ).action(
3556
- async (stage = "dev", options = {}) => {
3557
- const exitCode = await handleServiceUp(stage, {
3330
+ async (stage2 = "dev", options = {}) => {
3331
+ const exitCode = await handleServiceUp(stage2, {
3558
3332
  projectDir: options.projectDir,
3559
3333
  debug: options.debug,
3560
3334
  detach: options.detach,
@@ -3569,28 +3343,22 @@ The test command runs unit tests before E2E.`
3569
3343
  }
3570
3344
  );
3571
3345
  };
3572
- function compileApplicationEnv(stage, projectDir, options = {}) {
3346
+ function resolveComposeConfig(yaml, dir) {
3347
+ const result = spawnSync("docker", ["compose", "--project-directory", dir, "-f", "-", "config", "--format", "json"], { cwd: dir, encoding: "utf-8", input: yaml });
3348
+ if (result.error || result.status !== 0) throw new ScriptError(`Failed to resolve application environment: ${result.error?.message || result.stderr || result.stdout}`);
3349
+ return JSON.parse(result.stdout);
3350
+ }
3351
+ function compileApplicationEnv(stage2, projectDir, options = {}, resolver = resolveComposeConfig) {
3573
3352
  const dir = resolveProjectDir(projectDir);
3574
- const yaml = compileEnvironment(stage, dir, options);
3575
- const result = spawnSync("docker", [
3576
- "compose",
3577
- "--project-directory",
3578
- dir,
3579
- "-f",
3580
- "-",
3581
- "config",
3582
- "--format",
3583
- "json"
3584
- ], { cwd: dir, encoding: "utf-8", input: yaml });
3585
- if (result.error || result.status !== 0) {
3586
- throw new ScriptError(`Failed to resolve ${stage} application environment: ${result.error?.message || result.stderr || result.stdout}`);
3587
- }
3588
- const config = JSON.parse(result.stdout);
3589
- if (!config.services?.app) {
3590
- throw new ScriptError(`The ${stage} configuration has no application service ('app').`);
3353
+ const compiled = compileServiceComposition(stage2, dir, { validationMode: true, ...options });
3354
+ const main = compiled.mainServiceNames.get(nodeId(void 0, "main"));
3355
+ const yaml = stringify(compiled.compose);
3356
+ const config = resolver(yaml, dir);
3357
+ if (!main || !config.services?.[main]) {
3358
+ throw new ScriptError(`The ${stage2} configuration has no main service.`);
3591
3359
  }
3592
3360
  const environment = {};
3593
- for (const [key, value] of Object.entries(config.services.app.environment ?? {})) {
3361
+ for (const [key, value] of Object.entries(config.services[main].environment ?? {})) {
3594
3362
  if (value !== null && value !== void 0) {
3595
3363
  environment[key] = String(value).replace(/\$\$/g, "$");
3596
3364
  }
@@ -3612,8 +3380,8 @@ function serializeApplicationEnv(environment) {
3612
3380
  // src/commands/service/commands/export/handler.ts
3613
3381
  var STAGES = ["dev", "prod", "test", "e2e"];
3614
3382
  async function handleExportEnv(rawStage, options = {}) {
3615
- const stage = rawStage?.toLowerCase();
3616
- if (stage !== void 0 && !STAGES.includes(stage)) {
3383
+ const stage2 = rawStage?.toLowerCase();
3384
+ if (stage2 !== void 0 && !STAGES.includes(stage2)) {
3617
3385
  throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3618
3386
  }
3619
3387
  const projectDir = resolveProjectDir(options.projectDir);
@@ -3627,10 +3395,10 @@ async function handleExportEnv(rawStage, options = {}) {
3627
3395
  );
3628
3396
  }
3629
3397
  };
3630
- const stages = stage === void 0 ? STAGES : [stage];
3631
- const snapshots = stages.map((stage2) => ({
3632
- stage: stage2,
3633
- content: serializeApplicationEnv(compileApplicationEnv(stage2, projectDir, options))
3398
+ const stages = stage2 === void 0 ? STAGES : [stage2];
3399
+ const snapshots = stages.map((stage3) => ({
3400
+ stage: stage3,
3401
+ content: serializeApplicationEnv(compileApplicationEnv(stage3, projectDir, options))
3634
3402
  }));
3635
3403
  let reader;
3636
3404
  const ask = async (question) => {
@@ -3667,7 +3435,7 @@ async function handleExportEnv(rawStage, options = {}) {
3667
3435
  throw error;
3668
3436
  }
3669
3437
  files.push(filename);
3670
- console.log(pc15.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3438
+ console.log(pc9.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3671
3439
  break;
3672
3440
  }
3673
3441
  }
@@ -3685,8 +3453,8 @@ Examples:
3685
3453
  $ builder service export env
3686
3454
  $ builder service export env dev
3687
3455
  $ builder service export env e2e -C ./services/backend
3688
- $ builder service export env dev --full`).action(async (stage, options) => {
3689
- await handleExportEnv(stage, {
3456
+ $ builder service export env dev --full`).action(async (stage2, options) => {
3457
+ await handleExportEnv(stage2, {
3690
3458
  projectDir: options.projectDir,
3691
3459
  full: Boolean(options.full),
3692
3460
  silenceWarnings: options.silenceWarnings
@@ -3698,6 +3466,10 @@ Examples:
3698
3466
  var registerServiceCommand = (cmd) => {
3699
3467
  const service = cmd.command("service").description("Manage and run services");
3700
3468
  service.hook("preAction", async (_thisCommand, actionCommand) => {
3469
+ if (actionCommand.name() === "up") {
3470
+ const options = actionCommand.opts(), stageArg = actionCommand.args[0]?.toLowerCase();
3471
+ if (options.dryRun || stageArg && !SERVICE_STAGES.includes(stageArg)) return;
3472
+ }
3701
3473
  if (actionCommand.name() === "env" && actionCommand.parent?.name() === "export") {
3702
3474
  checkComposeAvailability();
3703
3475
  return;
@@ -3705,10 +3477,7 @@ var registerServiceCommand = (cmd) => {
3705
3477
  checkDependencies();
3706
3478
  if (actionCommand.name() === "up") {
3707
3479
  const options = actionCommand.opts();
3708
- const stageArg = actionCommand.args[0]?.toLowerCase();
3709
- if (stageArg && !SERVICE_STAGES.includes(stageArg)) {
3710
- return;
3711
- }
3480
+ actionCommand.args[0]?.toLowerCase();
3712
3481
  const projectDir = resolveProjectDir(options.projectDir);
3713
3482
  if (!options.skipChecks) {
3714
3483
  checkInfra(projectDir);
@@ -3743,10 +3512,10 @@ async function runCli(argv = process.argv) {
3743
3512
  (arg) => arg === "-h" || arg === "--help" || arg === "-V" || arg === "--version"
3744
3513
  );
3745
3514
  if (!isHelpOrVersion && argv.length > 2) {
3746
- console.log(pc15.dim(`builder v${version}`));
3515
+ console.log(pc9.dim(`builder v${version}`));
3747
3516
  }
3748
3517
  if (argv.length <= 2) {
3749
- console.log(pc15.dim(`builder v${version}
3518
+ console.log(pc9.dim(`builder v${version}
3750
3519
  `));
3751
3520
  cli.outputHelp();
3752
3521
  return;
@@ -3769,20 +3538,20 @@ async function runCli(argv = process.argv) {
3769
3538
  if (err instanceof ScriptError) {
3770
3539
  exitCode = err.exitCode;
3771
3540
  const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3772
- console.error(pc15.red(`
3541
+ console.error(pc9.red(`
3773
3542
  ${formatted}
3774
3543
  `));
3775
3544
  if (isVerbose && err.stack) {
3776
- console.error(pc15.dim(err.stack));
3545
+ console.error(pc9.dim(err.stack));
3777
3546
  }
3778
3547
  } else {
3779
3548
  const message = errorMessage(err);
3780
3549
  const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3781
- console.error(pc15.red(`
3550
+ console.error(pc9.red(`
3782
3551
  ${formatted}
3783
3552
  `));
3784
3553
  if (isVerbose && err instanceof Error && err.stack) {
3785
- console.error(pc15.dim(err.stack));
3554
+ console.error(pc9.dim(err.stack));
3786
3555
  }
3787
3556
  }
3788
3557
  if (process.env.VITEST) {