@solid-stack/builder 2.2.0 → 3.1.0

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