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