@solid-stack/builder 2.1.0 → 3.0.0

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