@solid-stack/builder 1.1.8 → 2.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 (144) hide show
  1. package/README.md +62 -170
  2. package/dist/bin.js +1713 -2507
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -1
  5. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  6. package/dist/commands/service/commands/export/command.d.ts.map +1 -1
  7. package/dist/commands/service/commands/up/command.d.ts.map +1 -1
  8. package/dist/core/buildSchema.d.ts +1029 -101
  9. package/dist/core/buildSchema.d.ts.map +1 -1
  10. package/dist/core/checkers/checkDockerfile.d.ts.map +1 -1
  11. package/dist/core/checkers/checkDockerfileContract.d.ts +1 -1
  12. package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
  13. package/dist/core/checkers/checkEffectiveServiceStages.d.ts +2 -0
  14. package/dist/core/checkers/checkEffectiveServiceStages.d.ts.map +1 -0
  15. package/dist/core/checkers/checkYamlFiles.d.ts +1 -1
  16. package/dist/core/checkers/checkYamlFiles.d.ts.map +1 -1
  17. package/dist/core/checkers/getDeclaredYamlFiles.d.ts +3 -1
  18. package/dist/core/checkers/getDeclaredYamlFiles.d.ts.map +1 -1
  19. package/dist/core/compileEnvironment.d.ts +1 -1
  20. package/dist/core/compileEnvironment.d.ts.map +1 -1
  21. package/dist/core/composition/compileServiceComposition.d.ts +18 -0
  22. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -0
  23. package/dist/core/composition/composeEnvironment.d.ts +4 -0
  24. package/dist/core/composition/composeEnvironment.d.ts.map +1 -0
  25. package/dist/core/composition/composePaths.d.ts +3 -0
  26. package/dist/core/composition/composePaths.d.ts.map +1 -0
  27. package/dist/core/composition/dependencyLifecycle.d.ts +4 -0
  28. package/dist/core/composition/dependencyLifecycle.d.ts.map +1 -0
  29. package/dist/core/composition/loadCompose.d.ts +8 -0
  30. package/dist/core/composition/loadCompose.d.ts.map +1 -0
  31. package/dist/core/composition/namespaceDependencyCompose.d.ts +15 -0
  32. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -0
  33. package/dist/core/composition/serviceEndpoints.d.ts +5 -0
  34. package/dist/core/composition/serviceEndpoints.d.ts.map +1 -0
  35. package/dist/core/composition/types.d.ts +64 -0
  36. package/dist/core/composition/types.d.ts.map +1 -0
  37. package/dist/core/composition/validateDependencyCompose.d.ts +8 -0
  38. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -0
  39. package/dist/core/composition/validateOverrideCompose.d.ts +11 -0
  40. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -0
  41. package/dist/core/config/constants.d.ts +13 -0
  42. package/dist/core/config/constants.d.ts.map +1 -0
  43. package/dist/core/config/endpointProperties.d.ts +16 -0
  44. package/dist/core/config/endpointProperties.d.ts.map +1 -0
  45. package/dist/core/config/hostPorts.d.ts +10 -0
  46. package/dist/core/config/hostPorts.d.ts.map +1 -0
  47. package/dist/core/config/lifecycleGraph.d.ts +7 -0
  48. package/dist/core/config/lifecycleGraph.d.ts.map +1 -0
  49. package/dist/core/config/pathSafety.d.ts +6 -0
  50. package/dist/core/config/pathSafety.d.ts.map +1 -0
  51. package/dist/core/config/references.d.ts +15 -0
  52. package/dist/core/config/references.d.ts.map +1 -0
  53. package/dist/core/config/resolveBuildStage.d.ts +4 -0
  54. package/dist/core/config/resolveBuildStage.d.ts.map +1 -0
  55. package/dist/core/config/resolveMeshStage.d.ts +4 -0
  56. package/dist/core/config/resolveMeshStage.d.ts.map +1 -0
  57. package/dist/core/config/stageMerge.d.ts +4 -0
  58. package/dist/core/config/stageMerge.d.ts.map +1 -0
  59. package/dist/core/config/types.d.ts +44 -0
  60. package/dist/core/config/types.d.ts.map +1 -0
  61. package/dist/core/mesh/MeshRunOptions.d.ts +0 -1
  62. package/dist/core/mesh/MeshRunOptions.d.ts.map +1 -1
  63. package/dist/core/mesh/checkers/checkMeshJson.d.ts +1 -1
  64. package/dist/core/mesh/checkers/checkMeshJson.d.ts.map +1 -1
  65. package/dist/core/mesh/checkers/checkMeshServices.d.ts +1 -1
  66. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  67. package/dist/core/mesh/checkers/checkMeshTester.d.ts +1 -1
  68. package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
  69. package/dist/core/mesh/compileMeshEnvironment.d.ts +1 -3
  70. package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
  71. package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
  72. package/dist/core/mesh/meshSchema.d.ts +267 -334
  73. package/dist/core/mesh/meshSchema.d.ts.map +1 -1
  74. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  75. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  76. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  77. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  78. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  79. package/dist/core/mesh/types.d.ts +34 -40
  80. package/dist/core/mesh/types.d.ts.map +1 -1
  81. package/dist/core/mesh/v2/compileMeshComposition.d.ts +6 -0
  82. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -0
  83. package/dist/core/mesh/v2/compileMeshTester.d.ts +14 -0
  84. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -0
  85. package/dist/core/mesh/v2/lifecycle.d.ts +10 -0
  86. package/dist/core/mesh/v2/lifecycle.d.ts.map +1 -0
  87. package/dist/core/mesh/v2/loadMeshServices.d.ts +5 -0
  88. package/dist/core/mesh/v2/loadMeshServices.d.ts.map +1 -0
  89. package/dist/core/mesh/v2/meshReferences.d.ts +15 -0
  90. package/dist/core/mesh/v2/meshReferences.d.ts.map +1 -0
  91. package/dist/core/mesh/v2/publication.d.ts +3 -0
  92. package/dist/core/mesh/v2/publication.d.ts.map +1 -0
  93. package/dist/core/mesh/v2/substitution.d.ts +5 -0
  94. package/dist/core/mesh/v2/substitution.d.ts.map +1 -0
  95. package/dist/core/mesh/v2/types.d.ts +40 -0
  96. package/dist/core/mesh/v2/types.d.ts.map +1 -0
  97. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  98. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  99. package/dist/core/templates.d.ts +1 -0
  100. package/dist/core/templates.d.ts.map +1 -1
  101. package/dist/errors/ConfigError.d.ts +15 -0
  102. package/dist/errors/ConfigError.d.ts.map +1 -0
  103. package/dist/errors/PortConflictError.d.ts +8 -0
  104. package/dist/errors/PortConflictError.d.ts.map +1 -0
  105. package/dist/index.d.ts +2 -0
  106. package/dist/index.d.ts.map +1 -1
  107. package/dist/index.js +1715 -2545
  108. package/dist/index.js.map +1 -1
  109. package/dist/templates/docker/docker-compose.base.yml +4 -4
  110. package/dist/templates/docker/docker-compose.dev.yml +1 -5
  111. package/dist/templates/docker/docker-compose.e2e.yml +9 -8
  112. package/dist/templates/docker/docker-compose.prod.yml +1 -6
  113. package/dist/templates/docker/docker-compose.test.yml +3 -8
  114. package/dist/templates/policy/dockerfile/dockerfile.rego +64 -0
  115. package/dist/types/index.d.ts +60 -46
  116. package/dist/types/index.d.ts.map +1 -1
  117. package/dist/utils/assertUniqueHostPortMappings.d.ts +3 -0
  118. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -0
  119. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  120. package/dist/utils/getBuildJson.d.ts.map +1 -1
  121. package/dist/utils/runState.d.ts.map +1 -1
  122. package/package.json +4 -2
  123. package/schemas/build-schema.json +623 -96
  124. package/schemas/mesh-schema.json +225 -133
  125. package/templates/docker/docker-compose.base.yml +4 -4
  126. package/templates/docker/docker-compose.dev.yml +1 -5
  127. package/templates/docker/docker-compose.e2e.yml +9 -8
  128. package/templates/docker/docker-compose.prod.yml +1 -6
  129. package/templates/docker/docker-compose.test.yml +3 -8
  130. package/templates/policy/dockerfile/dockerfile.rego +64 -0
  131. package/dist/core/checkers/checkComposeContract.d.ts +0 -3
  132. package/dist/core/checkers/checkComposeContract.d.ts.map +0 -1
  133. package/dist/templates/docker/docker-compose.standalone.yml +0 -5
  134. package/dist/utils/extractBuildDeps.d.ts +0 -3
  135. package/dist/utils/extractBuildDeps.d.ts.map +0 -1
  136. package/dist/utils/extractOverrides.d.ts +0 -3
  137. package/dist/utils/extractOverrides.d.ts.map +0 -1
  138. package/dist/utils/ymlMods/addDependenciesToAppService.d.ts +0 -3
  139. package/dist/utils/ymlMods/addDependenciesToAppService.d.ts.map +0 -1
  140. package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts +0 -2
  141. package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts.map +0 -1
  142. package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts +0 -3
  143. package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts.map +0 -1
  144. package/templates/docker/docker-compose.standalone.yml +0 -5
package/dist/index.js CHANGED
@@ -1,25 +1,19 @@
1
1
  import { Command, Argument } from 'commander';
2
2
  import pc22 from 'picocolors';
3
- import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, statSync } from 'fs';
4
- import path13 from 'path';
5
- import { spawnSync, spawn } from 'child_process';
6
- import { parse, stringify, parseAllDocuments } from 'yaml';
3
+ import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync, unlinkSync } from 'fs';
4
+ import path4 from 'path';
7
5
  import { z } from 'zod';
8
- import 'crypto';
6
+ import { spawnSync, spawn } from 'child_process';
7
+ import { fileURLToPath } from 'url';
8
+ import { stringify, parse, parseAllDocuments } from 'yaml';
9
+ import crypto from 'crypto';
9
10
  import os from 'os';
10
11
  import net from 'net';
11
- import { fileURLToPath } from 'url';
12
12
  import { createInterface } from 'readline/promises';
13
13
  import { createRequire } from 'module';
14
14
 
15
15
  // src/types/index.ts
16
- var SERVICE_STAGES = [
17
- "dev",
18
- "prod",
19
- "test",
20
- "test-unit",
21
- "test-e2e"
22
- ];
16
+ var SERVICE_STAGES = ["dev", "prod", "test", "test-unit", "test-e2e"];
23
17
 
24
18
  // src/errors/ScriptError.ts
25
19
  var ScriptError = class extends Error {
@@ -39,6 +33,43 @@ var NotFoundError = class extends ScriptError {
39
33
  }
40
34
  };
41
35
 
36
+ // src/errors/ConfigError.ts
37
+ var ConfigError = class extends ScriptError {
38
+ context;
39
+ constructor(context, options) {
40
+ const details = [context.sourceFile ? `source=${context.sourceFile}` : void 0, context.configPath ? `path=${context.configPath}` : void 0, context.stage ? `stage=${context.stage}` : void 0, context.composition ? `composition=${context.composition}` : void 0, context.referencedObject ? `reference=${context.referencedObject}` : void 0, context.value !== void 0 ? `value=${JSON.stringify(context.value)}` : void 0].filter(Boolean);
41
+ super(`${context.reason}${details.length ? ` (${details.join(", ")})` : ""}`, options);
42
+ this.name = "ConfigError";
43
+ this.context = context;
44
+ }
45
+ };
46
+
47
+ // src/core/config/constants.ts
48
+ var BUILDER_IDENTIFIER_PATTERN = /^[a-z][a-z0-9-]*$/;
49
+ var ENDPOINT_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
50
+ var DEPENDENCY_REFERENCE_PATTERN = /^dependencies\.([a-z][a-z0-9-]*)$/;
51
+ var ENDPOINT_PROPERTIES = ["network_host", "network_port", "network_address", "network_url", "public_host", "public_port", "public_address", "public_url"];
52
+ var PUBLIC_ENDPOINT_PROPERTIES = /* @__PURE__ */ new Set(["public_host", "public_port", "public_address", "public_url"]);
53
+ var RESERVED_MESH_SERVICE_NAMES = /* @__PURE__ */ new Set(["app", "dependencies", "tester", "services", "dev", "prod", "test", "e2e"]);
54
+ var PUBLIC_HOST = "127.0.0.1";
55
+ var AUTO_PORT_CACHE_VERSION = 1;
56
+ var AUTO_PORT_CACHE_RELATIVE_PATH = ".builder/ports-v2.json";
57
+ var AUTO_PORT_SCAN_START = 2e4;
58
+
59
+ // src/core/buildSchema.ts
60
+ var identifierSchema = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
61
+ var envSchema = z.record(z.string(), z.string());
62
+ var portSchema = z.number().int().min(1).max(65535);
63
+ var publicPortSchema = z.union([portSchema, z.literal("AUTO")]);
64
+ var appEndpointSchema = z.object({ port: portSchema, publicPort: publicPortSchema.optional(), primary: z.boolean().optional(), scheme: z.string().regex(ENDPOINT_SCHEME_PATTERN).optional() }).strict();
65
+ var dependencyEndpointSchema = appEndpointSchema.extend({ service: z.string().min(1) }).strict();
66
+ var dependencySchema = z.object({ compose: z.string().min(1), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
67
+ var appStageEndpointSchema = appEndpointSchema.partial().strict();
68
+ var dependencyStageEndpointSchema = dependencyEndpointSchema.partial().strict();
69
+ var dependencyStageSchema = z.object({ compose: z.string().min(1).optional(), env: envSchema.optional(), endpoints: z.record(identifierSchema, dependencyStageEndpointSchema).optional(), dependsOn: z.array(z.string()).optional() }).strict();
70
+ var buildStageSchema = z.object({ "override-compose": z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appStageEndpointSchema).optional() }).strict().optional(), dependencies: z.record(identifierSchema, dependencyStageSchema).optional() }).strict();
71
+ var buildJsonSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), dockerfile: z.string().min(1).optional(), app: z.object({ env: envSchema.optional(), endpoints: z.record(identifierSchema, appEndpointSchema).optional() }).strict(), dependencies: z.record(identifierSchema, dependencySchema).optional(), tester: z.object({ env: envSchema.optional() }).strict().optional(), dev: buildStageSchema.optional(), prod: buildStageSchema.optional(), test: buildStageSchema.optional(), e2e: buildStageSchema.optional() }).strict();
72
+
42
73
  // src/utils/errorMessage.ts
43
74
  function errorMessage(err) {
44
75
  if (err instanceof Error) {
@@ -50,96 +81,37 @@ function errorMessage(err) {
50
81
  return String(err);
51
82
  }
52
83
  function resolveProjectDir(projectDir) {
53
- return path13.resolve(projectDir ?? process.cwd());
54
- }
55
- function toComposePath(baseDir, targetPath) {
56
- const absBase = path13.resolve(baseDir);
57
- const absTarget = path13.resolve(absBase, targetPath);
58
- let rel = path13.relative(absBase, absTarget);
59
- if (!rel || rel === ".") {
60
- return ".";
61
- }
62
- rel = rel.replace(/\\/g, "/");
63
- if (path13.isAbsolute(rel) || /^[a-zA-Z]:\//.test(rel)) {
64
- return rel;
65
- }
66
- if (rel.startsWith("./") || rel.startsWith("../") || rel.startsWith("/")) {
67
- return rel;
68
- }
69
- return `./${rel}`;
70
- }
71
- function isBindMount(source) {
72
- if (!source) return false;
73
- if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~")) {
74
- return true;
75
- }
76
- if (/^[a-zA-Z]:[\\/]/.test(source)) {
77
- return true;
78
- }
79
- return false;
84
+ return path4.resolve(projectDir ?? process.cwd());
80
85
  }
81
86
  function isPathInside(parentDir, childPath) {
82
- const absParent = path13.resolve(parentDir);
83
- const absChild = path13.resolve(absParent, childPath);
84
- const rel = path13.relative(absParent, absChild);
85
- return rel !== ".." && !rel.startsWith(".." + path13.sep) && !rel.startsWith("../") && !path13.isAbsolute(rel);
86
- }
87
-
88
- // src/utils/ymlMods/normalizeDependsOn.ts
89
- function normalizeDependsOn(service) {
90
- if (!service || typeof service !== "object" || !service.depends_on) {
91
- return;
92
- }
93
- if (Array.isArray(service.depends_on)) {
94
- const obj = {};
95
- for (const dep of service.depends_on) {
96
- if (typeof dep === "string") {
97
- obj[dep] = { condition: "service_started" };
98
- }
99
- }
100
- service.depends_on = obj;
101
- }
87
+ const absParent = path4.resolve(parentDir);
88
+ const absChild = path4.resolve(absParent, childPath);
89
+ const rel = path4.relative(absParent, absChild);
90
+ return rel !== ".." && !rel.startsWith(".." + path4.sep) && !rel.startsWith("../") && !path4.isAbsolute(rel);
102
91
  }
103
92
 
104
93
  // src/utils/getBuildJson.ts
105
94
  var getBuildJson = (projectDir = process.cwd()) => {
106
- const absProjectDir = resolveProjectDir(projectDir);
107
- const buildJsonPath = path13.join(absProjectDir, "build.json");
108
- if (!existsSync(buildJsonPath)) {
109
- throw new NotFoundError(
110
- `Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`
111
- );
112
- }
95
+ const absProjectDir = resolveProjectDir(projectDir), buildJsonPath = path4.join(absProjectDir, "build.json");
96
+ if (!existsSync(buildJsonPath)) throw new NotFoundError(`Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`);
113
97
  let rawData;
114
98
  try {
115
99
  rawData = readFileSync(buildJsonPath, "utf-8");
116
100
  } catch (error) {
117
- throw new ScriptError(
118
- `Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`
119
- );
101
+ throw new ScriptError(`Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`);
120
102
  }
121
- let buildJson;
103
+ let parsed;
122
104
  try {
123
- buildJson = JSON.parse(rawData);
105
+ parsed = JSON.parse(rawData);
124
106
  } catch (error) {
125
- throw new ScriptError(
126
- `Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`
127
- );
128
- }
129
- if (!buildJson || typeof buildJson !== "object" || Array.isArray(buildJson)) {
130
- throw new ScriptError(
131
- `Invalid build.json at ${buildJsonPath}: root must be a JSON object.`
132
- );
107
+ throw new ScriptError(`Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`);
133
108
  }
134
- const typedBuildJson = buildJson;
135
- if (typedBuildJson.services && typeof typedBuildJson.services === "object") {
136
- for (const serviceConfig of Object.values(typedBuildJson.services)) {
137
- if (serviceConfig && typeof serviceConfig === "object") {
138
- normalizeDependsOn(serviceConfig);
139
- }
140
- }
109
+ const result = buildJsonSchema.safeParse(parsed);
110
+ if (!result.success) {
111
+ const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
112
+ throw new ConfigError({ sourceFile: buildJsonPath, configPath: "<root>", composition: "service", reason: `Invalid build.json: ${reason}` });
141
113
  }
142
- return typedBuildJson;
114
+ return result.data;
143
115
  };
144
116
 
145
117
  // src/core/checkers/constants.ts
@@ -185,22 +157,14 @@ ${ctx.detail}`);
185
157
  // src/core/checkers/checkDockerfile.ts
186
158
  function checkDockerfile(buildJson, projectDir) {
187
159
  const dockerfileRel = buildJson.dockerfile || "Dockerfile";
188
- const dockerfilePath = path13.resolve(projectDir, dockerfileRel);
160
+ const dockerfilePath = path4.resolve(projectDir, dockerfileRel);
189
161
  if (!isPathInside(projectDir, dockerfilePath)) {
190
162
  throw new ScriptError(
191
163
  `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
192
164
  );
193
165
  }
194
166
  if (!existsSync(dockerfilePath)) {
195
- if (buildJson.dockerfile) {
196
- throw new ScriptError(
197
- `Dockerfile declared in build.json not found at: ${dockerfilePath}`
198
- );
199
- }
200
- console.log(
201
- pc22.yellow(`\u26A0\uFE0F No ${dockerfileRel} found in project directory. Skipping Dockerfile checks.`)
202
- );
203
- return;
167
+ throw new ConfigError({ sourceFile: path4.join(projectDir, "build.json"), configPath: "dockerfile", value: dockerfileRel, composition: "service", reason: `Application Dockerfile not found at ${dockerfilePath}` });
204
168
  }
205
169
  const content = readFileSync(dockerfilePath, "utf-8");
206
170
  console.log(pc22.cyan(`
@@ -212,171 +176,846 @@ function checkDockerfile(buildJson, projectDir) {
212
176
  { stepName: "Dockerfile Linting", targetFile: dockerfileRel, input: content }
213
177
  );
214
178
  }
215
- function checkDockerfileContract(buildJson, projectDir) {
216
- const absProjectDir = resolveProjectDir(projectDir);
217
- const dockerfileRel = buildJson.dockerfile || "Dockerfile";
218
- const dockerfilePath = path13.resolve(absProjectDir, dockerfileRel);
219
- const policyRel = buildJson.policy?.dockerfile || buildJson.policies?.dockerfile || "policy/dockerfile";
220
- const policyDir = path13.resolve(absProjectDir, policyRel);
221
- if (!isPathInside(absProjectDir, dockerfilePath)) {
222
- throw new ScriptError(
223
- `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
224
- );
179
+ var cachedTemplatesDir = null;
180
+ var lastEnvTemplatesDir = void 0;
181
+ function getTemplatesDir() {
182
+ const envVal = process.env.BUILDER_TEMPLATES_DIR;
183
+ if (envVal !== lastEnvTemplatesDir) {
184
+ cachedTemplatesDir = null;
185
+ lastEnvTemplatesDir = envVal;
225
186
  }
226
- if (!existsSync(dockerfilePath) || !existsSync(policyDir)) {
227
- return;
187
+ if (envVal) {
188
+ const envDir = path4.resolve(envVal);
189
+ if (!fs.existsSync(envDir) || !fs.existsSync(path4.join(envDir, "docker"))) {
190
+ throw new ScriptError(
191
+ `BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
192
+ );
193
+ }
194
+ return envDir;
228
195
  }
229
- console.log(pc22.cyan(`
230
- \u{1F50D} Validating Dockerfile Contract (${policyRel})...`));
231
- runStep(
232
- "docker",
233
- [
234
- "run",
235
- "--rm",
236
- "--network",
237
- "none",
238
- "--mount",
239
- `type=bind,src=${absProjectDir},dst=/project,readonly`,
240
- "-w",
241
- "/project",
242
- CONFTEST_IMAGE,
243
- "test",
244
- dockerfileRel,
245
- "-p",
246
- `${policyRel}/`
247
- ],
248
- absProjectDir,
249
- { stepName: "Dockerfile Contract", targetFile: dockerfileRel }
196
+ if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
197
+ return cachedTemplatesDir;
198
+ }
199
+ const currentDir = typeof __dirname !== "undefined" ? __dirname : path4.dirname(fileURLToPath(import.meta.url));
200
+ const candidates = [
201
+ // When executing compiled output in dist/ (e.g. dist/templates)
202
+ path4.resolve(currentDir, "templates"),
203
+ path4.resolve(currentDir, "../templates"),
204
+ // When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
205
+ path4.resolve(currentDir, "../../templates"),
206
+ // Fallback relative to cwd
207
+ path4.resolve(process.cwd(), "templates")
208
+ ];
209
+ for (const cand of candidates) {
210
+ if (fs.existsSync(cand) && fs.existsSync(path4.join(cand, "docker"))) {
211
+ cachedTemplatesDir = cand;
212
+ return cand;
213
+ }
214
+ }
215
+ throw new ScriptError(
216
+ `Templates directory not found. Searched candidates:
217
+ ${candidates.join("\n")}`
250
218
  );
251
219
  }
252
- function getDeclaredYamlFiles(buildJson, projectDir) {
220
+ function getDockerComposeTemplate(filename) {
221
+ const templatesDir = getTemplatesDir();
222
+ const filePath = path4.join(templatesDir, "docker", filename);
223
+ if (!fs.existsSync(filePath)) {
224
+ throw new ScriptError(`Docker compose template not found: ${filePath}`);
225
+ }
226
+ return filePath;
227
+ }
228
+ function getDockerfilePolicyDir() {
229
+ const policyDir = path4.join(getTemplatesDir(), "policy", "dockerfile");
230
+ if (!fs.existsSync(path4.join(policyDir, "dockerfile.rego"))) throw new ScriptError(`Builder Dockerfile policy not found: ${policyDir}`);
231
+ return policyDir;
232
+ }
233
+
234
+ // src/core/checkers/checkDockerfileContract.ts
235
+ function checkDockerfileContract(build, projectDir) {
236
+ const root = resolveProjectDir(projectDir);
237
+ const relative = build.dockerfile ?? "Dockerfile";
238
+ const dockerfile = path4.resolve(root, relative);
239
+ if (!isPathInside(root, dockerfile) || !existsSync(dockerfile)) throw new ConfigError({ sourceFile: path4.join(root, "build.json"), configPath: "dockerfile", value: relative, composition: "service", reason: "Application Dockerfile missing or outside project" });
240
+ const policyDir = getDockerfilePolicyDir();
241
+ console.log(pc22.cyan(`
242
+ \u{1F50D} Validating Builder Dockerfile contract (${relative})...`));
243
+ 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 });
244
+ }
245
+ function resolveInsideProject(projectDir, relativePath, context) {
246
+ if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
247
+ const resolved = path4.resolve(projectDir, relativePath);
248
+ if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
249
+ return resolved;
250
+ }
251
+ function loadComposeDocument(absolutePath, context) {
252
+ const fail = (reason, value) => {
253
+ throw new ConfigError({ ...context, sourceFile: absolutePath, ...{} , reason });
254
+ };
255
+ if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) fail("Compose file does not exist or is not a regular file");
256
+ let text = "";
257
+ try {
258
+ text = readFileSync(absolutePath, "utf8");
259
+ } catch (e) {
260
+ fail(`Failed to read Compose file: ${String(e)}`);
261
+ }
262
+ let docs = [];
263
+ try {
264
+ docs = parseAllDocuments(text, { prettyErrors: true });
265
+ } catch (e) {
266
+ fail(`Invalid Compose YAML: ${String(e)}`);
267
+ }
268
+ if (docs.length !== 1) fail("Compose file must contain exactly one YAML document");
269
+ const errors = docs[0].errors;
270
+ if (errors.length) fail(`Invalid Compose YAML: ${errors.map((e) => e.message).join("; ")}`);
271
+ let parsed;
272
+ try {
273
+ parsed = parse(text);
274
+ } catch (e) {
275
+ fail(`Invalid Compose YAML: ${String(e)}`);
276
+ }
277
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) fail("Compose root must be an object");
278
+ return parsed;
279
+ }
280
+ function getDeclaredYamlFiles(build, projectDir) {
253
281
  const files = [];
254
282
  const seen = /* @__PURE__ */ new Set();
255
- const addFile = (relPath, source) => {
256
- const normalized = path13.normalize(relPath);
257
- if (seen.has(normalized)) return;
258
- seen.add(normalized);
259
- files.push({
260
- relativePath: relPath,
261
- absolutePath: path13.resolve(projectDir, relPath),
262
- source
263
- });
283
+ const add = (relativePath, source, kind, stage) => {
284
+ const absolutePath = path4.resolve(projectDir, relativePath);
285
+ if (seen.has(absolutePath)) return;
286
+ seen.add(absolutePath);
287
+ files.push({ relativePath, absolutePath, source, kind, ...stage ? { stage } : {} });
264
288
  };
265
- if (buildJson.dependencies && typeof buildJson.dependencies === "object") {
266
- for (const [depName, dep] of Object.entries(buildJson.dependencies)) {
267
- if (dep && typeof dep === "object" && typeof dep.path === "string") {
268
- addFile(dep.path, `dependency "${depName}"`);
269
- }
289
+ for (const [name, dep] of Object.entries(build.dependencies ?? {})) add(dep.compose, `dependencies.${name}.compose`, "dependency-compose");
290
+ for (const stage of ["dev", "prod", "test", "e2e"]) {
291
+ const overlay = build[stage];
292
+ if (overlay?.["override-compose"]) add(overlay["override-compose"], `${stage}.override-compose`, "override-compose", stage);
293
+ for (const [name, dep] of Object.entries(overlay?.dependencies ?? {})) if (dep.compose) add(dep.compose, `${stage}.dependencies.${name}.compose`, "dependency-compose", stage);
294
+ }
295
+ return files;
296
+ }
297
+
298
+ // src/core/checkers/checkYamlFiles.ts
299
+ function checkYamlFiles(build, projectDir) {
300
+ const root = resolveProjectDir(projectDir);
301
+ const files = getDeclaredYamlFiles(build, root);
302
+ if (files.length) console.log(pc22.cyan(`
303
+ \u{1F50D} Validating ${files.length} declared V2 Compose file(s)...`));
304
+ for (const file of files) {
305
+ const absolutePath = resolveInsideProject(root, file.relativePath, { sourceFile: `${root}/build.json`, configPath: file.source, ...file.stage ? { stage: file.stage } : {} });
306
+ loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
307
+ }
308
+ }
309
+
310
+ // src/core/config/endpointProperties.ts
311
+ function resolveEndpointProperty(endpoint, property, context) {
312
+ const published = () => {
313
+ if (!endpoint.effectivelyPublished || endpoint.publicHost === void 0 || endpoint.publicPort === void 0) throw new ConfigError({ ...context, configPath: context.configPath, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires effective publication` });
314
+ };
315
+ const scheme = () => {
316
+ if (!endpoint.scheme) throw new ConfigError({ ...context, referencedObject: endpoint.logicalPath, reason: `Endpoint property ${property} requires an endpoint scheme` });
317
+ return endpoint.scheme;
318
+ };
319
+ switch (property) {
320
+ case "network_host":
321
+ return endpoint.networkHost;
322
+ case "network_port":
323
+ return String(endpoint.networkPort);
324
+ case "network_address":
325
+ return `${endpoint.networkHost}:${endpoint.networkPort}`;
326
+ case "network_url":
327
+ return `${scheme()}://${endpoint.networkHost}:${endpoint.networkPort}`;
328
+ case "public_host":
329
+ published();
330
+ return endpoint.publicHost;
331
+ case "public_port":
332
+ published();
333
+ return String(endpoint.publicPort);
334
+ case "public_address":
335
+ published();
336
+ return `${endpoint.publicHost}:${endpoint.publicPort}`;
337
+ case "public_url":
338
+ published();
339
+ return `${scheme()}://${endpoint.publicHost}:${endpoint.publicPort}`;
340
+ }
341
+ }
342
+ function assertPrimaryEndpointInvariant(endpoints, context) {
343
+ const primaries = Object.entries(endpoints).filter(([, e]) => e.primary === true);
344
+ 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}` });
345
+ }
346
+ function getPrimaryEndpoint(endpoints) {
347
+ return Object.entries(endpoints).find(([, endpoint]) => endpoint.primary === true);
348
+ }
349
+
350
+ // src/core/config/lifecycleGraph.ts
351
+ function assertAcyclicGraph(graph, context) {
352
+ const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), stack = [];
353
+ const visit = (node) => {
354
+ if (visiting.has(node)) {
355
+ const start = stack.indexOf(node);
356
+ const cycle = [...stack.slice(start), node];
357
+ throw new ConfigError({ ...context, configPath: "dependsOn", referencedObject: cycle.join(" -> "), reason: `Lifecycle cycle detected: ${cycle.join(" -> ")}` });
358
+ }
359
+ if (visited.has(node)) return;
360
+ visiting.add(node);
361
+ stack.push(node);
362
+ for (const next of graph.get(node) ?? []) visit(next);
363
+ stack.pop();
364
+ visiting.delete(node);
365
+ visited.add(node);
366
+ };
367
+ for (const node of graph.keys()) visit(node);
368
+ }
369
+
370
+ // src/core/config/stageMerge.ts
371
+ function unionStable(base = [], overlay = []) {
372
+ return [.../* @__PURE__ */ new Set([...base, ...overlay])];
373
+ }
374
+ function mergeStringMap(base, overlay) {
375
+ return { ...base ?? {}, ...overlay ?? {} };
376
+ }
377
+
378
+ // src/core/config/resolveBuildStage.ts
379
+ function resolveBuildStage(build, stage, sourceFile) {
380
+ const overlay = build[stage] ?? {};
381
+ const appEndpoints = structuredClone(build.app.endpoints ?? {});
382
+ for (const [name, endpoint] of Object.entries(overlay.app?.endpoints ?? {})) appEndpoints[name] = { ...appEndpoints[name] ?? {}, ...endpoint };
383
+ const dependencies = {};
384
+ for (const [name, dep] of Object.entries(build.dependencies ?? {})) dependencies[name] = { ...dep, env: { ...dep.env ?? {} }, endpoints: structuredClone(dep.endpoints ?? {}), dependsOn: [...dep.dependsOn ?? []] };
385
+ for (const [name, patch] of Object.entries(overlay.dependencies ?? {})) {
386
+ const prior = dependencies[name] ?? { compose: void 0, env: {}, endpoints: {}, dependsOn: [] };
387
+ prior.compose = patch.compose ?? prior.compose;
388
+ prior.env = mergeStringMap(prior.env, patch.env);
389
+ for (const [ep, epPatch] of Object.entries(patch.endpoints ?? {})) prior.endpoints[ep] = { ...prior.endpoints[ep] ?? {}, ...epPatch };
390
+ prior.dependsOn = unionStable(prior.dependsOn, patch.dependsOn);
391
+ dependencies[name] = prior;
392
+ }
393
+ const effective = { ...build, app: { env: mergeStringMap(build.app.env, overlay.app?.env), endpoints: appEndpoints }, dependencies, tester: build.tester ? { env: { ...build.tester.env ?? {} } } : void 0, overrideCompose: overlay["override-compose"] };
394
+ delete effective.dev;
395
+ delete effective.prod;
396
+ delete effective.test;
397
+ delete effective.e2e;
398
+ const context = (configPath, value, reason, referencedObject) => new ConfigError({ sourceFile, configPath, stage, composition: "service", value, ...referencedObject ? { referencedObject } : {}, reason });
399
+ 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");
400
+ assertPrimaryEndpointInvariant(appEndpoints, { sourceFile, configPath: "app.endpoints", stage });
401
+ const graph = /* @__PURE__ */ new Map();
402
+ for (const [name, dep] of Object.entries(dependencies)) {
403
+ if (typeof dep.compose !== "string" || !dep.compose.trim()) throw context(`dependencies.${name}.compose`, dep.compose, "Effective dependency requires compose");
404
+ const endpoints = Object.entries(dep.endpoints);
405
+ for (const [epName, ep] of endpoints) if (!ep.service || !Number.isInteger(ep.port) || ep.port < 1 || ep.port > 65535) throw context(`dependencies.${name}.endpoints.${epName}`, ep, "Effective dependency endpoint requires service and port");
406
+ assertPrimaryEndpointInvariant(dep.endpoints, { sourceFile, configPath: `dependencies.${name}.endpoints`, stage });
407
+ const node = `dependencies.${name}`;
408
+ graph.set(node, /* @__PURE__ */ new Set());
409
+ for (const ref of dep.dependsOn) {
410
+ const match = DEPENDENCY_REFERENCE_PATTERN.exec(ref);
411
+ if (!match) throw context(`dependencies.${name}.dependsOn`, ref, "Expected dependencies.<name> lifecycle reference", ref);
412
+ const targetName = match[1];
413
+ if (targetName === name) throw context(`dependencies.${name}.dependsOn`, ref, "Dependency cannot depend on itself", ref);
414
+ const target = dependencies[targetName];
415
+ if (!target) throw context(`dependencies.${name}.dependsOn`, ref, "Unknown dependency", ref);
416
+ if (!Object.keys(target.endpoints).length) throw context(`dependencies.${name}.dependsOn`, ref, "Lifecycle target is inert and has no endpoints", ref);
417
+ graph.get(node).add(`dependencies.${targetName}`);
418
+ }
419
+ }
420
+ assertAcyclicGraph(graph, { sourceFile, stage, composition: "service" });
421
+ return effective;
422
+ }
423
+
424
+ // src/core/config/references.ts
425
+ var BUILD_APP = /^app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
426
+ var BUILD_DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
427
+ var MESH_APP = /^([a-z][a-z0-9-]*)\.app\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
428
+ var MESH_DEP = /^([a-z][a-z0-9-]*)\.dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)\.([a-z_]+)$/;
429
+ function parse2(raw, scope, sourcePath) {
430
+ let m;
431
+ if (scope === "build" && (m = BUILD_APP.exec(raw))) return valid({ raw, scope, target: "app", endpoint: m[1], property: m[2] }, sourcePath);
432
+ if (scope === "build" && (m = BUILD_DEP.exec(raw))) return valid({ raw, scope, target: "dependency", dependency: m[1], endpoint: m[2], property: m[3] }, sourcePath);
433
+ if (scope === "mesh" && (m = MESH_APP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "app", endpoint: m[2], property: m[3] }, sourcePath);
434
+ if (scope === "mesh" && (m = MESH_DEP.exec(raw))) return valid({ raw, scope, meshService: m[1], target: "dependency", dependency: m[2], endpoint: m[3], property: m[4] }, sourcePath);
435
+ throw new ConfigError({ configPath: sourcePath, value: raw, reason: `Invalid ${scope} endpoint reference` });
436
+ }
437
+ function valid(ref, sourcePath) {
438
+ if (!ENDPOINT_PROPERTIES.includes(ref.property)) throw new ConfigError({ configPath: sourcePath, value: ref.property, reason: "Unknown endpoint property" });
439
+ return ref;
440
+ }
441
+ function collectBuilderReferences(value, scope, sourcePath) {
442
+ const protectedValue = value.replace(/\$\$/g, "\0DOLLAR\0"), refs2 = [];
443
+ for (const match of protectedValue.matchAll(/\$\{([^}]*)\}/g)) refs2.push(parse2(match[1], scope, sourcePath));
444
+ return refs2;
445
+ }
446
+ function interpolateBuilderReferences(value, scope, resolve) {
447
+ const sentinel = "\0DOLLAR\0";
448
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (whole, body) => resolve(parse2(body, scope, "environment"))).replaceAll(sentinel, "$");
449
+ }
450
+ function assertTesterReferencesArePublic(env, scope, sourcePrefix) {
451
+ for (const [key, value] of Object.entries(env)) for (const ref of collectBuilderReferences(value, scope, `${sourcePrefix}.${key}`)) if (!PUBLIC_ENDPOINT_PROPERTIES.has(ref.property)) throw new ConfigError({ configPath: `${sourcePrefix}.${key}`, value: ref.raw, reason: "Tester references may use only public endpoint properties" });
452
+ }
453
+
454
+ // src/errors/PortConflictError.ts
455
+ var PortConflictError = class extends ConfigError {
456
+ port;
457
+ firstOwner;
458
+ secondOwner;
459
+ constructor(port, firstOwner, secondOwner, stage) {
460
+ super({ sourceFile: "Builder effective composition", configPath: "publicPort", value: port, stage, reason: `Host port ${port} is claimed by both ${firstOwner} and ${secondOwner}. Builder does not remap fixed public ports.` });
461
+ this.name = "PortConflictError";
462
+ this.port = port;
463
+ this.firstOwner = firstOwner;
464
+ this.secondOwner = secondOwner;
465
+ }
466
+ };
467
+
468
+ // src/core/config/hostPorts.ts
469
+ function isHostPortAvailableSync(port) {
470
+ 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)));`;
471
+ const result = spawnSync(process.execPath, ["-e", script], { stdio: "ignore", timeout: 3e3 });
472
+ return result.status === 0;
473
+ }
474
+ function allocateHostPorts(projectDir, stage, intentsInDeterministicOrder, validationMode = false) {
475
+ const reserved = /* @__PURE__ */ new Map(), allocated = /* @__PURE__ */ new Map();
476
+ for (const intent of intentsInDeterministicOrder) if (typeof intent.requested === "number") {
477
+ const owner = reserved.get(intent.requested);
478
+ if (owner) throw new PortConflictError(intent.requested, owner, intent.logicalPath, stage);
479
+ reserved.set(intent.requested, intent.logicalPath);
480
+ allocated.set(intent.logicalPath, intent.requested);
481
+ }
482
+ if (validationMode) {
483
+ let placeholder = 6e4;
484
+ for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
485
+ while (reserved.has(placeholder)) placeholder--;
486
+ if (placeholder < 1) throw new ConfigError({ configPath: intent.logicalPath, stage, reason: "No validation placeholder port is available" });
487
+ reserved.set(placeholder, intent.logicalPath);
488
+ allocated.set(intent.logicalPath, placeholder--);
489
+ }
490
+ return allocated;
491
+ }
492
+ const cachePath = path4.join(projectDir, AUTO_PORT_CACHE_RELATIVE_PATH);
493
+ let cached = {};
494
+ try {
495
+ if (existsSync(cachePath)) {
496
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
497
+ if (parsed && typeof parsed === "object" && parsed.version === AUTO_PORT_CACHE_VERSION && parsed.allocations && typeof parsed.allocations === "object") cached = parsed.allocations;
270
498
  }
499
+ } catch {
500
+ cached = {};
271
501
  }
272
- if (buildJson.overrides && typeof buildJson.overrides === "object") {
273
- for (const [stage, ovr] of Object.entries(buildJson.overrides)) {
274
- if (ovr && typeof ovr === "object" && typeof ovr.path === "string") {
275
- addFile(ovr.path, `override "${stage}"`);
276
- }
502
+ const nextCache = { ...cached };
503
+ for (const intent of intentsInDeterministicOrder) if (intent.requested === "AUTO") {
504
+ const prior = cached[intent.logicalPath];
505
+ let selected = typeof prior === "number" && Number.isInteger(prior) && prior >= 1 && prior <= 65535 && !reserved.has(prior) && isHostPortAvailableSync(prior) ? prior : void 0;
506
+ if (selected === void 0) {
507
+ 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));
508
+ selected = scan.find((p) => !reserved.has(p) && isHostPortAvailableSync(p));
277
509
  }
510
+ if (selected === void 0) throw new ConfigError({ sourceFile: "Builder effective composition", configPath: intent.logicalPath, stage, reason: "No available host port could be allocated" });
511
+ reserved.set(selected, intent.logicalPath);
512
+ allocated.set(intent.logicalPath, selected);
513
+ nextCache[intent.logicalPath] = selected;
278
514
  }
279
- if (Array.isArray(buildJson.composeFiles)) {
280
- for (const item of buildJson.composeFiles) {
281
- if (typeof item === "string") {
282
- addFile(item, "composeFiles");
283
- }
515
+ if (intentsInDeterministicOrder.some((i) => i.requested === "AUTO")) {
516
+ mkdirSync(path4.dirname(cachePath), { recursive: true });
517
+ const temp = `${cachePath}.${process.pid}.tmp`;
518
+ writeFileSync(temp, JSON.stringify({ version: AUTO_PORT_CACHE_VERSION, allocations: nextCache }, null, 2));
519
+ renameSync(temp, cachePath);
520
+ }
521
+ return allocated;
522
+ }
523
+ function normalizeProjectName(name, projectDir) {
524
+ let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
525
+ if (!normalized || !/^[a-z0-9]/.test(normalized)) {
526
+ if (projectDir) {
527
+ const hash = crypto.createHash("sha1").update(path4.resolve(projectDir)).digest("hex").slice(0, 7);
528
+ return `project-${hash}`;
284
529
  }
530
+ return "project";
285
531
  }
286
- return files;
532
+ return normalized;
287
533
  }
288
-
289
- // src/core/checkers/checkYamlFiles.ts
290
- function checkYamlFiles(buildJson, projectDir) {
291
- const absProjectDir = resolveProjectDir(projectDir);
292
- const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
293
- if (declaredFiles.length === 0) {
294
- return;
534
+ function deriveProjectName(name, stage, projectDir, options = {}) {
535
+ let base = normalizeProjectName(name, projectDir);
536
+ if (options.hash && projectDir) {
537
+ const hash = crypto.createHash("sha1").update(path4.resolve(projectDir)).digest("hex").slice(0, 7);
538
+ base = `${base}-${hash}`;
295
539
  }
296
- console.log(
297
- pc22.cyan(
298
- `
299
- \u{1F50D} Validating Declared YAML Files (${declaredFiles.length} file${declaredFiles.length === 1 ? "" : "s"})...`
300
- )
301
- );
302
- const errors = [];
303
- for (const file of declaredFiles) {
304
- if (!existsSync(file.absolutePath)) {
305
- errors.push(
306
- `File "${file.relativePath}" declared in build.json (${file.source}) does not exist (expected at ${file.absolutePath}).`
307
- );
308
- continue;
309
- }
310
- try {
311
- const content = readFileSync(file.absolutePath, "utf-8");
312
- const docs = parseAllDocuments(content);
313
- const docErrors = docs.flatMap((doc) => doc.errors);
314
- if (docErrors.length > 0) {
315
- const errorText = docErrors.map((e) => e.message).join("\n");
316
- errors.push(
317
- `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${errorText}`
318
- );
540
+ if (!stage) {
541
+ return base;
542
+ }
543
+ const s = stage.toLowerCase();
544
+ if (s === "dev") {
545
+ return base;
546
+ }
547
+ if (s === "prod") {
548
+ return `${base}-prod`;
549
+ }
550
+ if (s === "test" || s === "test-unit") {
551
+ return `${base}-test`;
552
+ }
553
+ if (s === "e2e" || s === "test-e2e") {
554
+ return `${base}-e2e`;
555
+ }
556
+ return `${base}-${s}`;
557
+ }
558
+ var posix = (p) => p.replace(/\\/g, "/");
559
+ function rebase(p, base, out) {
560
+ if (path4.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p)) return posix(path4.normalize(p));
561
+ const abs = path4.resolve(base, p);
562
+ const rel = path4.relative(out, abs);
563
+ const result = posix(isPathInside(out, rel) ? rel || "." : abs);
564
+ return result !== "." && !result.startsWith(".") && !path4.isAbsolute(result) ? `./${result}` : result;
565
+ }
566
+ function volumeShort(v, base, out) {
567
+ const parts = v.split(":");
568
+ if (parts.length < 2) return v;
569
+ const source = parts[0];
570
+ if (source === "" || source.startsWith("/") || source.startsWith("~") || /^[A-Za-z]:[\\/]/.test(source)) return v;
571
+ if (source.startsWith(".") || source.includes("/") || source.includes("\\")) parts[0] = rebase(source, base, out);
572
+ return parts.join(":");
573
+ }
574
+ function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
575
+ const doc = structuredClone(document), base = path4.dirname(composeFilePath), out = path4.resolve(outputProjectDir);
576
+ for (const svc of Object.values(doc.services ?? {})) {
577
+ if (typeof svc.build === "string") svc.build = rebase(svc.build, base, out);
578
+ else if (svc.build && typeof svc.build === "object") {
579
+ const b = svc.build;
580
+ const context = typeof b.context === "string" ? b.context : ".";
581
+ b.context = rebase(context, base, out);
582
+ }
583
+ if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
584
+ else if (Array.isArray(svc.env_file)) svc.env_file = svc.env_file.map((v) => typeof v === "string" ? rebase(v, base, out) : v && typeof v === "object" && typeof v.path === "string" ? { ...v, path: rebase(v.path, base, out) } : v);
585
+ if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => typeof v === "string" ? volumeShort(v, base, out) : v && typeof v === "object" && v.type === "bind" && typeof v.source === "string" ? { ...v, source: rebase(v.source, base, out) } : v);
586
+ }
587
+ for (const kind of ["configs", "secrets"]) for (const def of Object.values(doc[kind] ?? {})) if (def && typeof def === "object" && typeof def.file === "string") def.file = rebase(def.file, base, out);
588
+ return doc;
589
+ }
590
+
591
+ // src/core/composition/composeEnvironment.ts
592
+ function normalizeComposeEnvironment(value, context) {
593
+ const result = {};
594
+ if (value == null) return result;
595
+ if (Array.isArray(value)) {
596
+ for (const item of value) {
597
+ if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
598
+ const at = item.indexOf("=");
599
+ if (at < 0) {
600
+ result[item] = process.env[item] ?? "";
601
+ continue;
319
602
  }
320
- } catch (err) {
321
- const msg = errorMessage(err);
322
- errors.push(
323
- `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${msg}`
324
- );
603
+ result[item.slice(0, at)] = item.slice(at + 1);
325
604
  }
605
+ return result;
326
606
  }
327
- if (errors.length > 0) {
328
- throw new ScriptError(errors.join("\n"));
607
+ if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
608
+ for (const [key, val] of Object.entries(value)) {
609
+ if (val === null || val === void 0) continue;
610
+ if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
611
+ result[key] = String(val);
329
612
  }
613
+ return result;
330
614
  }
331
- function checkComposeContract(buildJson, projectDir) {
332
- const absProjectDir = resolveProjectDir(projectDir);
333
- const policyRel = buildJson.policy?.compose || buildJson.policies?.compose;
334
- if (!policyRel) {
335
- return;
615
+ function mergeComposeEnvironment(service, overlay) {
616
+ service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
617
+ }
618
+
619
+ // src/core/composition/namespaceDependencyCompose.ts
620
+ var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
621
+ function namespaceDependencyCompose(options) {
622
+ const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
623
+ const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
624
+ const serviceNameMap = make("", Object.keys(doc.services ?? {}));
625
+ for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
626
+ const volumeNameMap = make("volume", Object.keys(doc.volumes ?? {})), networkNameMap = make("network", Object.keys(doc.networks ?? {})), configNameMap = make("config", Object.keys(doc.configs ?? {})), secretNameMap = make("secret", Object.keys(doc.secrets ?? {}));
627
+ const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
628
+ const rewriteResourceRefs = (svc) => {
629
+ if (Array.isArray(svc.depends_on)) {
630
+ svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
631
+ } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
632
+ if (Array.isArray(svc.links)) svc.links = svc.links.map((v) => {
633
+ if (typeof v !== "string") return v;
634
+ const [name, ...rest] = v.split(":");
635
+ return [serviceNameMap.get(name) ?? name, ...rest].join(":");
636
+ });
637
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) {
638
+ const key = svc.network_mode.slice(8);
639
+ svc.network_mode = `service:${serviceNameMap.get(key) ?? key}`;
640
+ }
641
+ if (Array.isArray(svc.volumes_from)) svc.volumes_from = svc.volumes_from.map((v) => typeof v === "string" ? v.replace(/^([^:]+)(.*)$/, (all, n, rest) => `${serviceNameMap.get(n) ?? n}${rest}`) : v);
642
+ if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => {
643
+ if (typeof v !== "string") return v;
644
+ const [src, ...rest] = v.split(":");
645
+ const mapped = volumeNameMap.get(src);
646
+ return mapped ? [mapped, ...rest].join(":") : v;
647
+ });
648
+ if (svc.volumes && Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => v && typeof v === "object" && v.type === "volume" ? { ...v, source: volumeNameMap.get(v.source) ?? v.source } : v);
649
+ if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
650
+ else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
651
+ for (const key of ["configs", "secrets"]) if (Array.isArray(svc[key])) svc[key] = svc[key].map((v) => typeof v === "string" ? (key === "configs" ? configNameMap : secretNameMap).get(v) ?? v : v && typeof v === "object" ? { ...v, source: (key === "configs" ? configNameMap : secretNameMap).get(v.source) ?? v.source } : v);
652
+ };
653
+ for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
654
+ doc.services = rewriteKeys(doc.services, serviceNameMap);
655
+ if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
656
+ if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
657
+ if (doc.configs) doc.configs = rewriteKeys(doc.configs, configNameMap);
658
+ if (doc.secrets) doc.secrets = rewriteKeys(doc.secrets, secretNameMap);
659
+ return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
660
+ }
661
+
662
+ // src/core/composition/validateDependencyCompose.ts
663
+ function validateDependencyCompose(dependencyKey, dependency, document, context) {
664
+ const fail = (configPath, reason, value) => {
665
+ throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
666
+ };
667
+ if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
668
+ const services = document.services ?? {};
669
+ for (const [name, svc] of Object.entries(services)) {
670
+ if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
671
+ if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
672
+ if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
673
+ if (svc.container_name !== void 0) fail(`services.${name}.container_name`, `fixed container_name is forbidden`);
674
+ for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
675
+ const source = typeof v === "string" ? v.split(":")[0] : v && typeof v === "object" ? v.source : void 0;
676
+ if (typeof source === "string" && source.replaceAll("\\", "/") === "/") fail(`services.${name}.volumes`, `host root bind mounts are forbidden`, v);
677
+ }
678
+ const internalRefs = [];
679
+ if (Array.isArray(svc.depends_on)) {
680
+ for (const ref of svc.depends_on) if (typeof ref === "string") internalRefs.push(["depends_on", ref]);
681
+ } else if (svc.depends_on && typeof svc.depends_on === "object") {
682
+ for (const ref of Object.keys(svc.depends_on)) internalRefs.push(["depends_on", ref]);
683
+ }
684
+ if (Array.isArray(svc.links)) {
685
+ for (const ref of svc.links) if (typeof ref === "string") internalRefs.push(["links", ref.split(":")[0]]);
686
+ }
687
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) internalRefs.push(["network_mode", svc.network_mode.slice(8)]);
688
+ if (Array.isArray(svc.volumes_from)) {
689
+ for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
690
+ }
691
+ 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);
336
692
  }
337
- const policyDir = path13.resolve(absProjectDir, policyRel);
338
- if (!existsSync(policyDir)) {
339
- return;
693
+ if (!Object.keys(dependency.endpoints).length) return;
694
+ if (!Object.keys(services).length) fail("services", "endpoint-bearing dependency Compose must define services");
695
+ const owners = /* @__PURE__ */ new Set();
696
+ for (const [endpoint, definition] of Object.entries(dependency.endpoints)) {
697
+ const owner = definition.service;
698
+ if (!services[owner]) fail(`endpoints.${endpoint}.service`, `declared endpoint owner "${owner}" does not exist`, owner);
699
+ owners.add(owner);
340
700
  }
341
- const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
342
- const existingFiles = declaredFiles.filter((f) => existsSync(f.absolutePath));
343
- if (existingFiles.length === 0) {
344
- return;
701
+ for (const owner of owners) {
702
+ if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
703
+ const health = services[owner].healthcheck;
704
+ if (!health || health.disable === true || !health.test || typeof health.test === "string" && !health.test.trim() || Array.isArray(health.test) && (!health.test.length || health.test[0] === "NONE" || health.test.every((v) => typeof v === "string" && !v.trim()))) fail(`services.${owner}.healthcheck`, `endpoint owner requires an enabled, non-empty healthcheck`);
345
705
  }
346
- for (const f of existingFiles) {
347
- if (!isPathInside(absProjectDir, f.absolutePath)) {
348
- throw new ScriptError(
349
- `Security error: Compose file path "${f.relativePath}" escapes the project directory.`
350
- );
706
+ }
707
+
708
+ // src/core/composition/validateOverrideCompose.ts
709
+ function validateAndPrepareAppOverride(document, context) {
710
+ const fail = (path20, reason, value) => {
711
+ throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...{} , reason });
712
+ };
713
+ const keys = Object.keys(document.services ?? {});
714
+ if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
715
+ const app = structuredClone(document.services.app);
716
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
717
+ if (app.healthcheck && typeof app.healthcheck === "object") {
718
+ const health = app.healthcheck;
719
+ for (const key of Object.keys(health)) if (!["interval", "timeout", "retries", "start_period", "start_interval"].includes(key)) fail(`services.app.healthcheck.${key}`, "override may set only healthcheck timing fields");
720
+ }
721
+ if (app.build && typeof app.build === "object") {
722
+ const b = app.build;
723
+ for (const k of ["target", "dockerfile"]) if (b[k] !== void 0) fail(`services.app.build.${k}`, "override cannot change Builder-owned build configuration");
724
+ if (b.context !== void 0 && b.context !== "." && b.context !== context.expectedBuildContext) fail("services.app.build.context", "override cannot change app build context");
725
+ }
726
+ const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
727
+ for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
728
+ app.environment = env;
729
+ const resourceKeys = ["volumes", "networks", "configs", "secrets"];
730
+ const resources = {};
731
+ for (const kind of resourceKeys) {
732
+ const defs = document[kind] ?? {};
733
+ const refs2 = /* @__PURE__ */ new Set();
734
+ const refsVal = app[kind];
735
+ if (Array.isArray(refsVal)) for (const v of refsVal) {
736
+ if (typeof v === "string") refs2.add(v);
737
+ else if (v && typeof v === "object" && typeof v.source === "string") refs2.add(v.source);
738
+ }
739
+ else if (refsVal && typeof refsVal === "object") for (const [k, v] of Object.entries(refsVal)) {
740
+ refs2.add(k);
741
+ if (v && typeof v === "object" && typeof v.source === "string") refs2.add(v.source);
742
+ }
743
+ const mapped = {};
744
+ for (const [name, def] of Object.entries(defs)) {
745
+ if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
746
+ const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
747
+ mapped[target] = def;
748
+ for (const ref of refs2) if (ref === name) ;
749
+ }
750
+ if (Object.keys(mapped).length) resources[kind] = mapped;
751
+ if (app[kind] && typeof app[kind] === "object" && !Array.isArray(app[kind])) app[kind] = Object.fromEntries(Object.entries(app[kind]).map(([k, v]) => [`app-override--${context.stage}--${kind.slice(0, -1)}--${k}`, v]));
752
+ else if (Array.isArray(app[kind])) app[kind] = app[kind].map((v) => typeof v === "string" ? `app-override--${context.stage}--${kind.slice(0, -1)}--${v}` : v && typeof v === "object" ? { ...v, source: `app-override--${context.stage}--${kind.slice(0, -1)}--${v.source}` } : v);
753
+ }
754
+ return { app, resources };
755
+ }
756
+
757
+ // src/core/composition/dependencyLifecycle.ts
758
+ function asMap(value) {
759
+ if (Array.isArray(value)) return Object.fromEntries(value.filter((v) => typeof v === "string").map((v) => [v, {}]));
760
+ if (value && typeof value === "object") return value;
761
+ return {};
762
+ }
763
+ function healthyMerge(target, owners) {
764
+ const current = asMap(target.depends_on);
765
+ for (const owner of owners) {
766
+ const old = current[owner];
767
+ const cond = old && typeof old === "object" ? old.condition : void 0;
768
+ current[owner] = { ...old && typeof old === "object" ? old : {}, condition: cond === "service_healthy" ? cond : "service_healthy" };
769
+ }
770
+ target.depends_on = current;
771
+ }
772
+ function applyDependencyLifecycle(app, materialized, effectiveBuild) {
773
+ const appOwners = /* @__PURE__ */ new Set();
774
+ for (const dep of Object.values(materialized)) for (const owner of dep.endpointOwners) appOwners.add(owner);
775
+ healthyMerge(app, appOwners);
776
+ for (const [key, dep] of Object.entries(materialized)) {
777
+ const config = effectiveBuild.dependencies[key];
778
+ if (!config) continue;
779
+ for (const raw of config.dependsOn) {
780
+ const match = DEPENDENCY_REFERENCE_PATTERN.exec(raw);
781
+ if (!match) continue;
782
+ const target = materialized[match[1]];
783
+ if (!target) continue;
784
+ for (const sourceOwner of dep.endpointOwners) {
785
+ const source = dep.compose.services[sourceOwner];
786
+ if (source) healthyMerge(source, target.endpointOwners);
787
+ }
351
788
  }
352
789
  }
353
- const relativePaths = existingFiles.map((f) => f.relativePath);
354
- console.log(pc22.cyan(`
355
- \u{1F50D} Validating Compose Contract (${policyRel})...`));
356
- runStep(
357
- "docker",
358
- [
359
- "run",
360
- "--rm",
361
- "--network",
362
- "none",
363
- "--mount",
364
- `type=bind,src=${absProjectDir},dst=/project,readonly`,
365
- "-w",
366
- "/project",
367
- CONFTEST_IMAGE,
368
- "test",
369
- ...relativePaths,
370
- "-p",
371
- `${policyRel}/`,
372
- "--all-namespaces"
373
- ],
374
- absProjectDir,
375
- {
376
- stepName: "Compose Contract Validation",
377
- targetFile: relativePaths.join(", ")
378
- }
379
- );
790
+ }
791
+
792
+ // src/core/composition/serviceEndpoints.ts
793
+ function buildStandaloneAppEndpoints(build, stage, host = "app") {
794
+ const out = {};
795
+ 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 };
796
+ return out;
797
+ }
798
+ function buildStandaloneDependencyEndpoints(key, build, serviceNames, materialized) {
799
+ const out = {};
800
+ for (const [name, e] of Object.entries(build.dependencies[key]?.endpoints ?? {})) {
801
+ const host = serviceNames.get(e.service) ?? e.service;
802
+ 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 };
803
+ }
804
+ return out;
805
+ }
806
+
807
+ // src/core/composition/compileServiceComposition.ts
808
+ function getExecutionProfile(stage, full) {
809
+ switch (stage) {
810
+ case "dev":
811
+ return { configStage: "dev", appTarget: "dev", runtimeStage: "dev", integrated: full, attachTester: false };
812
+ case "prod":
813
+ return { configStage: "prod", appTarget: "prod", runtimeStage: "prod", integrated: true, attachTester: false };
814
+ case "test":
815
+ return { configStage: "test", appTarget: "test", runtimeStage: "test", integrated: false, attachTester: false };
816
+ case "e2e":
817
+ return { configStage: "e2e", appTarget: "prod", runtimeStage: "e2e", integrated: true, attachTester: true, testerTarget: "test-e2e" };
818
+ }
819
+ }
820
+ function mergeDocument(target, source, context) {
821
+ for (const section of ["services", "volumes", "networks", "configs", "secrets"]) {
822
+ const src = source[section];
823
+ if (!src) continue;
824
+ const dst = target[section] ??= {};
825
+ for (const [key, value] of Object.entries(src)) {
826
+ if (key in dst) throw new ConfigError({ configPath: `${section}.${key}`, referencedObject: context, reason: "Internal Compose namespace collision" });
827
+ dst[key] = value;
828
+ }
829
+ }
830
+ }
831
+ function getTemplateSeed(stage, meshMode) {
832
+ const base = parse(fs.readFileSync(getDockerComposeTemplate("docker-compose.base.yml"), "utf8"));
833
+ const stageName = stage === "e2e" ? "e2e" : stage;
834
+ const overlay = parse(fs.readFileSync(getDockerComposeTemplate(`docker-compose.${stageName}.yml`), "utf8"));
835
+ const merged = { ...base, services: { ...base.services ?? {} } };
836
+ for (const [name, svc] of Object.entries(overlay.services ?? {})) merged.services[name] = { ...merged.services[name] ?? {}, ...svc, build: { ...merged.services[name]?.build ?? {}, ...svc.build ?? {} } };
837
+ if (meshMode) delete merged.services.tester;
838
+ return merged;
839
+ }
840
+ function ownEnv(build, stage) {
841
+ const env = { ...build.app.env };
842
+ const reserved = ["EXEC_MODE", "INFRA_MODE", ...getPrimaryEndpoint(build.app.endpoints) ? ["PORT"] : []];
843
+ for (const key of reserved) if (key in env) throw new ConfigError({ sourceFile: "build.json", configPath: "app.env", stage, composition: "service", value: key, reason: "Application env cannot set a Builder-owned key" });
844
+ return env;
845
+ }
846
+ function resolveEnv(input, registry, source) {
847
+ const out = {};
848
+ for (const [key, value] of Object.entries(input)) {
849
+ collectBuilderReferences(value, "build", `${source}.${key}`);
850
+ out[key] = interpolateBuilderReferences(value, "build", registry).replace(/\$/g, "$$$$");
851
+ }
852
+ return out;
853
+ }
854
+ function addPorts(service, endpointPairs) {
855
+ for (const [ep, hostPort] of endpointPairs) {
856
+ const ports = Array.isArray(service.ports) ? service.ports : [];
857
+ if (ports.some((p) => p && typeof p === "object" && p.published === hostPort)) throw new ConfigError({ configPath: ep.logicalPath, stage: "service", value: hostPort, reason: "Duplicate host port publication" });
858
+ ports.push({ target: ep.networkPort, published: hostPort, host_ip: PUBLIC_HOST, protocol: "tcp" });
859
+ service.ports = ports;
860
+ }
861
+ }
862
+ function compileServiceComposition(stage, projectDir, options = {}) {
863
+ const root = resolveProjectDir(projectDir), buildPath = path4.join(root, "build.json"), raw = getBuildJson(root), effective = resolveBuildStage(raw, stage, buildPath), profile = getExecutionProfile(stage, Boolean(options.full));
864
+ resolveInsideProject(root, raw.dockerfile ?? "Dockerfile", { sourceFile: buildPath, configPath: "dockerfile", stage });
865
+ const seed = getTemplateSeed(stage, Boolean(options.meshMode));
866
+ const rawName = options.projectNameOverride ?? raw.name ?? path4.basename(root);
867
+ const projectName = deriveProjectName(rawName, stage);
868
+ const namespaced = {};
869
+ for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
870
+ const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
871
+ const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
872
+ validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
873
+ if (Object.keys(dep.endpoints).length) {
874
+ const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
875
+ namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
876
+ }
877
+ }
878
+ const materialized = {};
879
+ const compose = { ...seed, ...options.meshMode ? {} : { name: projectName }, services: { ...seed.services } };
880
+ let app = compose.services.app ?? (compose.services.app = { build: { context: "." } });
881
+ if (profile.integrated) for (const [key, entry] of Object.entries(namespaced)) {
882
+ if (options.suppressDependencies?.has(key)) continue;
883
+ const dep = effective.dependencies[key];
884
+ const item = structuredClone(entry.doc);
885
+ mergeDocument(compose, item, `dependency ${key}`);
886
+ const endpointOwnerMap = /* @__PURE__ */ new Map();
887
+ for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
888
+ const endpointOwners = new Set(endpointOwnerMap.values());
889
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
890
+ }
891
+ const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
892
+ const depEndpoints = {};
893
+ for (const [key, dep] of Object.entries(effective.dependencies)) {
894
+ depEndpoints[key] = buildStandaloneDependencyEndpoints(key, effective, namespaced[key]?.map ?? /* @__PURE__ */ new Map(), Boolean(materialized[key]));
895
+ if (options.meshMode) for (const ep of Object.values(depEndpoints[key])) {
896
+ ep.effectivelyPublished = false;
897
+ delete ep.publicHost;
898
+ delete ep.publicPort;
899
+ }
900
+ }
901
+ if (options.meshMode) for (const ep of Object.values(appEndpoints)) {
902
+ ep.effectivelyPublished = false;
903
+ delete ep.publicHost;
904
+ delete ep.publicPort;
905
+ }
906
+ const intents = [];
907
+ if (!options.meshMode) {
908
+ 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 });
909
+ for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) if (materialized[key]) {
910
+ 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 });
911
+ }
912
+ }
913
+ const allocation = allocateHostPorts(root, stage, intents, Boolean(options.validationMode));
914
+ for (const [name, ep] of Object.entries(appEndpoints)) if (allocation.has(ep.logicalPath)) {
915
+ ep.publicHost = PUBLIC_HOST;
916
+ ep.publicPort = allocation.get(ep.logicalPath);
917
+ ep.effectivelyPublished = true;
918
+ }
919
+ for (const [key, eps] of Object.entries(depEndpoints)) for (const [name, ep] of Object.entries(eps)) if (allocation.has(ep.logicalPath)) {
920
+ ep.publicHost = PUBLIC_HOST;
921
+ ep.publicPort = allocation.get(ep.logicalPath);
922
+ ep.effectivelyPublished = true;
923
+ }
924
+ const registry = (ref) => {
925
+ if (ref.target === "app") {
926
+ const ep2 = appEndpoints[ref.endpoint];
927
+ if (!ep2) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown app endpoint reference" });
928
+ return resolveEndpointProperty(ep2, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
929
+ }
930
+ const ep = depEndpoints[ref.dependency]?.[ref.endpoint];
931
+ if (!ep) throw new ConfigError({ sourceFile: buildPath, configPath: ref.raw, stage, composition: "service", referencedObject: ref.raw, reason: "Unknown dependency endpoint reference" });
932
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: buildPath, configPath: ref.raw, stage });
933
+ };
934
+ for (const [key, dep] of Object.entries(effective.dependencies)) {
935
+ const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
936
+ for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
937
+ }
938
+ const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
939
+ let buildAppEnvironment = { ...appEnv };
940
+ const runtimeDotenv = path4.join(root, `.env.${profile.runtimeStage}`);
941
+ if (fs.existsSync(runtimeDotenv)) {
942
+ const text = fs.readFileSync(runtimeDotenv, "utf8");
943
+ for (const line of text.split(/\r?\n/)) {
944
+ const match = line.match(/^\s*(?:export\s+)?(EXEC_MODE|INFRA_MODE|PORT)\s*=/);
945
+ if (match && (match[1] !== "PORT" || getPrimaryEndpoint(effective.app.endpoints))) throw new ConfigError({ sourceFile: runtimeDotenv, configPath: match[1], stage, composition: "service", reason: "Dotenv file cannot define Builder-owned environment" });
946
+ }
947
+ }
948
+ const internal = { EXEC_MODE: profile.runtimeStage, INFRA_MODE: profile.integrated ? "integrated" : "isolated", ...getPrimaryEndpoint(effective.app.endpoints) ? { PORT: String(getPrimaryEndpoint(effective.app.endpoints)[1].port) } : {} };
949
+ const appBuild = app.build && typeof app.build === "object" ? app.build : { context: "." };
950
+ const outputDir = options.composeOutputDir ? path4.resolve(options.composeOutputDir) : root;
951
+ const serviceContext = path4.relative(outputDir, root).replace(/\\/g, "/") || ".";
952
+ appBuild.context = options.meshMode ? serviceContext : ".";
953
+ if (raw.dockerfile) appBuild.dockerfile = raw.dockerfile;
954
+ else delete appBuild.dockerfile;
955
+ appBuild.target = profile.appTarget;
956
+ app.build = appBuild;
957
+ app.env_file = [{ path: options.meshMode ? path4.posix.join(serviceContext, `.env.${profile.runtimeStage}`) : `.env.${profile.runtimeStage}`, required: false }];
958
+ app.environment = { ...appEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
959
+ if (stage === "dev") app.volumes = [`${options.meshMode && serviceContext !== "." ? `./${serviceContext}` : "."}:/app`, "/app/node_modules"];
960
+ for (const [name, ep] of Object.entries(appEndpoints)) if (!options.meshMode && ep.effectivelyPublished) addPorts(app, [[ep, ep.publicPort]]);
961
+ for (const [key, dependency] of Object.entries(materialized)) {
962
+ for (const [epName, owner] of dependency.endpointOwnerMap.entries()) {
963
+ const endpoint = depEndpoints[key][epName];
964
+ if (!options.meshMode && endpoint.effectivelyPublished) addPorts(compose.services[owner], [[endpoint, endpoint.publicPort]]);
965
+ }
966
+ for (const owner of dependency.endpointOwners) {
967
+ const svc = compose.services[owner];
968
+ if (!options.meshMode && svc.networks !== void 0) {
969
+ const nets = svc.networks;
970
+ if (Array.isArray(nets)) {
971
+ if (!nets.includes("default")) nets.push("default");
972
+ } else if (nets && typeof nets === "object") nets.default = null;
973
+ }
974
+ }
975
+ for (const [epName, ep] of Object.entries(depEndpoints[key])) dependency.endpoints[epName] = ep;
976
+ }
977
+ if (effective.overrideCompose) {
978
+ const overridePath = resolveInsideProject(root, effective.overrideCompose, { sourceFile: buildPath, configPath: "override-compose", stage });
979
+ const odoc = rebaseComposePaths(loadComposeDocument(overridePath, { sourceFile: buildPath, configPath: "override-compose", stage, composition: "service" }), overridePath, options.composeOutputDir ?? root);
980
+ const prepared = validateAndPrepareAppOverride(odoc, { file: overridePath, stage, expectedBuildContext: options.meshMode ? path4.relative(options.composeOutputDir ?? root, root).replace(/\\/g, "/") || "." : "." });
981
+ for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
982
+ const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
983
+ const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
984
+ 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" });
985
+ buildAppEnvironment = { ...appEnv, ...overrideEnv };
986
+ const merged = { ...app, ...prepared.app };
987
+ merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
988
+ const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
989
+ if (overrideBuild.args !== void 0) appBuild.args = overrideBuild.args;
990
+ merged.build = appBuild;
991
+ merged.env_file = app.env_file;
992
+ merged.depends_on = app.depends_on;
993
+ merged.networks = { default: null, ...app.networks ?? {}, ...prepared.app.networks ?? {} };
994
+ compose.services.app = merged;
995
+ app = merged;
996
+ }
997
+ if (options.meshMode && options.appServiceName && options.appServiceName !== "app") {
998
+ delete compose.services.app;
999
+ compose.services[options.appServiceName] = app;
1000
+ }
1001
+ if (profile.integrated) applyDependencyLifecycle(app, materialized, effective);
1002
+ if (profile.attachTester && !options.meshMode) {
1003
+ const testerEnvRaw = effective.tester?.env ?? {};
1004
+ assertTesterReferencesArePublic(testerEnvRaw, "build", "tester.env");
1005
+ const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1006
+ compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1007
+ }
1008
+ const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1009
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, builderAppEnvironment, buildAppEnvironment, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1010
+ }
1011
+
1012
+ // src/core/checkers/checkEffectiveServiceStages.ts
1013
+ function checkAllEffectiveServiceStages(projectDir) {
1014
+ compileServiceComposition("dev", projectDir, { validationMode: true });
1015
+ compileServiceComposition("dev", projectDir, { full: true, validationMode: true });
1016
+ compileServiceComposition("prod", projectDir, { validationMode: true });
1017
+ compileServiceComposition("test", projectDir, { validationMode: true });
1018
+ compileServiceComposition("e2e", projectDir, { validationMode: true });
380
1019
  }
381
1020
 
382
1021
  // src/core/checkers/checkInfra.ts
@@ -386,8 +1025,8 @@ function checkInfra(projectDir = process.cwd()) {
386
1025
  checkDockerfile(buildJson, absProjectDir);
387
1026
  checkDockerfileContract(buildJson, absProjectDir);
388
1027
  checkYamlFiles(buildJson, absProjectDir);
389
- checkComposeContract(buildJson, absProjectDir);
390
- console.log(pc22.green("\n\u2705 All infrastructure and contract checks passed.\n"));
1028
+ checkAllEffectiveServiceStages(absProjectDir);
1029
+ console.log(pc22.green("\n\u2705 All V2 service infrastructure and contract checks passed.\n"));
391
1030
  }
392
1031
  function checkComposeAvailability() {
393
1032
  const composeCheck = spawnSync(
@@ -471,326 +1110,489 @@ Examples:
471
1110
  }
472
1111
  });
473
1112
  };
474
- var meshHealthcheckSchema = z.union([
475
- z.object({
476
- type: z.literal("tcp"),
477
- port: z.union([z.number(), z.string()]).optional()
478
- }).strict(),
479
- z.object({
480
- test: z.union([z.string(), z.array(z.string())]),
481
- interval: z.string().optional(),
482
- timeout: z.string().optional(),
483
- retries: z.number().optional(),
484
- start_period: z.string().optional(),
485
- disable: z.boolean().optional()
486
- }).passthrough()
487
- ]);
488
- var meshServiceSchema = z.object({
489
- path: z.string({ required_error: 'Service "path" is required' }).describe("Relative path to service directory containing build.json"),
490
- port: z.union([z.number(), z.string()]).optional().describe("Public host port mapped to internal port 3000"),
491
- preservePort: z.boolean().optional().describe("If true, use the port declared in build.json"),
492
- provideDependency: z.record(z.string(), z.string()).optional().describe("Map consumer dependency key to fellow mesh service provider"),
493
- replaceMocks: z.record(z.string(), z.string()).optional().describe("Alias for provideDependency"),
494
- envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides with URL templating"),
495
- healthcheck: meshHealthcheckSchema.optional()
496
- }).strict();
497
- var meshTesterSchema = z.object({
498
- path: z.string({ required_error: 'Tester "path" is required' }).describe("Relative path to E2E tester directory"),
499
- compose: z.string().optional().describe("Tester compose file (defaults to 'docker-compose.yml')"),
500
- dockerfile: z.string().optional().describe("Tester Dockerfile (defaults to 'Dockerfile')"),
501
- envOverrides: z.record(z.string(), z.string()).optional().describe(
502
- "Environment variable overrides for global tester with URL templating"
503
- ),
504
- policy: z.object({
505
- dockerfile: z.string().optional(),
506
- compose: z.string().optional()
507
- }).strict().optional()
508
- }).strict();
509
- var meshServiceNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
510
- var meshSchema = z.object({
511
- $schema: z.string().optional(),
512
- name: z.string().optional(),
513
- services: z.record(
514
- z.string().regex(meshServiceNameRegex, {
515
- message: "Service name must start with a lowercase letter or digit and contain only lowercase letters, digits, '-', '_', or '.'"
516
- }),
517
- meshServiceSchema
518
- ).refine((services) => Object.keys(services).length > 0, {
519
- message: 'At least one service must be defined in "services".'
520
- }),
521
- dependencies: z.record(
522
- z.string(),
523
- z.object({
524
- path: z.string(),
525
- service: z.string().optional()
526
- }).strict()
527
- ).optional(),
528
- tester: meshTesterSchema.optional()
529
- }).strict();
530
-
531
- // src/core/mesh/checkers/checkMeshJson.ts
532
- function checkMeshJson(mesh) {
533
- const result = meshSchema.safeParse(mesh);
534
- if (!result.success) {
535
- const errorDetails = result.error.issues.map(
536
- (issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message
537
- ).join("; ");
538
- throw new ScriptError(`Invalid mesh.json: ${errorDetails}`);
539
- }
540
- const services = result.data.services;
541
- const serviceKeys = new Set(Object.keys(services));
542
- const graph = /* @__PURE__ */ new Map();
543
- for (const sName of serviceKeys) {
544
- graph.set(sName, /* @__PURE__ */ new Set());
545
- }
546
- for (const [serviceName, serviceConfig] of Object.entries(services)) {
547
- const provideMap = {
548
- ...serviceConfig.replaceMocks || {},
549
- ...serviceConfig.provideDependency || {}
550
- };
551
- for (const [depKey, targetSvc] of Object.entries(provideMap)) {
552
- if (!serviceKeys.has(targetSvc)) {
553
- throw new ScriptError(
554
- `Invalid mesh.json: Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetSvc}".`
555
- );
556
- }
557
- graph.get(serviceName).add(targetSvc);
558
- }
559
- }
560
- const visited = /* @__PURE__ */ new Map();
561
- function dfs(node, pathStack) {
562
- visited.set(node, "visiting");
563
- pathStack.push(node);
564
- const neighbors = graph.get(node) || /* @__PURE__ */ new Set();
565
- for (const neighbor of neighbors) {
566
- const state = visited.get(neighbor);
567
- if (state === "visiting") {
568
- const cycleStart = pathStack.indexOf(neighbor);
569
- const cycle = [...pathStack.slice(cycleStart), neighbor];
570
- throw new ScriptError(
571
- `Dependency cycle detected in mesh.json: ${cycle.join(" -> ")}`
572
- );
573
- }
574
- if (!state) {
575
- dfs(neighbor, pathStack);
576
- }
577
- }
578
- pathStack.pop();
579
- visited.set(node, "visited");
580
- }
581
- for (const sName of serviceKeys) {
582
- if (!visited.has(sName)) {
583
- dfs(sName, []);
584
- }
585
- }
586
- }
1113
+ var identifierSchema2 = z.string().regex(BUILDER_IDENTIFIER_PATTERN, "must match ^[a-z][a-z0-9-]*$");
1114
+ var serviceNameSchema = identifierSchema2.refine((name) => !RESERVED_MESH_SERVICE_NAMES.has(name), { message: "is reserved and cannot be used as a mesh service name" });
1115
+ var envSchema2 = z.record(z.string(), z.string());
1116
+ 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();
1117
+ 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();
1118
+ var meshStageSchema = z.object({ services: z.record(serviceNameSchema, meshServiceStageOverlaySchema).optional() }).strict();
1119
+ var meshSchema = z.object({ $schema: z.string().optional(), name: z.string().optional(), tester: z.object({ compose: z.string().min(1), service: z.string().min(1), env: envSchema2.optional() }).strict().optional(), services: z.record(serviceNameSchema, meshServiceSchema), dev: meshStageSchema.optional(), prod: meshStageSchema.optional(), test: meshStageSchema.optional(), e2e: meshStageSchema.optional() }).strict();
587
1120
 
588
1121
  // src/core/mesh/getMeshJson.ts
589
1122
  function getMeshJson(projectDir = process.cwd()) {
590
- const absDir = resolveProjectDir(projectDir);
591
- const meshPath = path13.resolve(absDir, "mesh.json");
592
- if (!existsSync(meshPath)) {
593
- throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
594
- }
1123
+ const absDir = resolveProjectDir(projectDir), meshPath = path4.resolve(absDir, "mesh.json");
1124
+ if (!existsSync(meshPath)) throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
595
1125
  let content;
596
1126
  try {
597
1127
  content = readFileSync(meshPath, "utf-8");
598
1128
  } catch (err) {
599
- throw new ScriptError(
600
- `Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`
601
- );
1129
+ throw new ScriptError(`Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`);
602
1130
  }
603
1131
  let parsed;
604
1132
  try {
605
1133
  parsed = JSON.parse(content);
606
1134
  } catch (err) {
607
- throw new ScriptError(
608
- `Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`
609
- );
1135
+ throw new ScriptError(`Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`);
610
1136
  }
611
- if (!parsed || typeof parsed !== "object") {
612
- throw new ScriptError(`Invalid mesh.json: root must be an object.`);
1137
+ const result = meshSchema.safeParse(parsed);
1138
+ if (!result.success) {
1139
+ const reason = result.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
1140
+ throw new ConfigError({ sourceFile: meshPath, configPath: "<root>", composition: "mesh", reason: `Invalid mesh.json: ${reason}` });
613
1141
  }
614
- const meshConfig = parsed;
615
- checkMeshJson(meshConfig);
616
- return meshConfig;
1142
+ return result.data;
617
1143
  }
618
- function checkMeshServices(mesh, meshDir = process.cwd()) {
619
- const absMeshDir = resolveProjectDir(meshDir);
620
- const serviceNames = Object.keys(mesh.services);
621
- console.log(
622
- pc22.bold(
623
- pc22.cyan(
624
- `
625
- \u{1F50D} Checking Mesh Services (${serviceNames.length} service${serviceNames.length === 1 ? "" : "s"})...`
626
- )
627
- )
628
- );
629
- for (const serviceName of serviceNames) {
630
- const serviceConfig = mesh.services[serviceName];
631
- if (!serviceConfig) {
632
- throw new ScriptError(`Service "${serviceName}" configuration is missing.`);
1144
+
1145
+ // src/core/config/resolveMeshStage.ts
1146
+ function resolveMeshStage(mesh, stage, sourceFile) {
1147
+ const overlays = mesh[stage]?.services ?? {}, names = /* @__PURE__ */ new Set([...Object.keys(mesh.services), ...Object.keys(overlays)]), services = {};
1148
+ for (const name of names) {
1149
+ const base = mesh.services[name], patch = overlays[name];
1150
+ const merged = { path: patch?.path ?? base?.path, env: mergeStringMap(base?.env, patch?.env), dependencies: { ...base?.dependencies ?? {}, ...patch?.dependencies ?? {} }, dependsOn: unionStable(base?.dependsOn, patch?.dependsOn), publish: unionStable(base?.publish, patch?.publish) };
1151
+ if (!merged.path) throw new ConfigError({ sourceFile, configPath: `services.${name}.path`, stage, composition: "mesh", reason: "Effective mesh service requires path" });
1152
+ services[name] = merged;
1153
+ }
1154
+ if (!Object.keys(services).length) throw new ConfigError({ sourceFile, configPath: "services", stage, composition: "mesh", reason: "At least one effective mesh service is required" });
1155
+ const graph = /* @__PURE__ */ new Map();
1156
+ for (const [name, service] of Object.entries(services)) {
1157
+ 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" });
1158
+ graph.set(name, /* @__PURE__ */ new Set());
1159
+ for (const target of service.dependsOn) {
1160
+ if (target === name) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Mesh service cannot depend on itself" });
1161
+ if (!services[target]) throw new ConfigError({ sourceFile, configPath: `services.${name}.dependsOn`, stage, composition: "mesh", referencedObject: target, reason: "Unknown mesh lifecycle target" });
1162
+ graph.get(name).add(target);
1163
+ }
1164
+ }
1165
+ assertAcyclicGraph(graph, { sourceFile, stage, composition: "mesh" });
1166
+ const result = { ...mesh, services };
1167
+ delete result.dev;
1168
+ delete result.prod;
1169
+ delete result.test;
1170
+ delete result.e2e;
1171
+ return result;
1172
+ }
1173
+ function loadEffectiveMeshServices(meshDir, effectiveMesh, stage) {
1174
+ const out = {};
1175
+ for (const [name, svc] of Object.entries(effectiveMesh.services).sort(([a], [b]) => a.localeCompare(b))) {
1176
+ const abs = resolveInsideProject(meshDir, svc.path, { sourceFile: path4.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage });
1177
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new ConfigError({ sourceFile: path4.join(meshDir, "mesh.json"), configPath: `services.${name}.path`, stage, composition: "mesh", value: svc.path, reason: "Mesh service directory does not exist" });
1178
+ const buildJsonPath = path4.join(abs, "build.json"), build = getBuildJson(abs), effectiveBuild = resolveBuildStage(build, stage, buildJsonPath);
1179
+ out[name] = { name, path: svc.path, absolutePath: abs, buildJsonPath, effectiveBuild, meshEnv: { ...svc.env ?? {} }, dependencyBindings: { ...svc.dependencies ?? {} }, dependsOn: [...svc.dependsOn ?? []], publish: [...svc.publish ?? []] };
1180
+ }
1181
+ return out;
1182
+ }
1183
+
1184
+ // src/core/mesh/v2/substitution.ts
1185
+ function buildDependencyBindings(services, stage, meshJsonPath) {
1186
+ const out = [];
1187
+ for (const service of Object.values(services)) {
1188
+ for (const [logicalDependency, providerService] of Object.entries(service.dependencyBindings)) {
1189
+ 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}` });
1190
+ 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" });
1191
+ out.push({ consumerService: service.name, logicalDependency, providerService });
633
1192
  }
634
- const serviceDir = path13.resolve(absMeshDir, serviceConfig.path);
635
- if (!isPathInside(absMeshDir, serviceDir)) {
636
- throw new ScriptError(
637
- `Security error: Service "${serviceName}" directory escapes the mesh directory: ${serviceDir}`
638
- );
639
- }
640
- if (!existsSync(serviceDir)) {
641
- throw new ScriptError(
642
- `Service "${serviceName}" directory does not exist: ${serviceDir} (declared path: "${serviceConfig.path}")`
643
- );
644
- }
645
- if (!statSync(serviceDir).isDirectory()) {
646
- throw new ScriptError(
647
- `Service "${serviceName}" path is not a directory: ${serviceDir}`
648
- );
649
- }
650
- const buildJsonPath = path13.resolve(serviceDir, "build.json");
651
- if (!existsSync(buildJsonPath)) {
652
- throw new ScriptError(
653
- `Service "${serviceName}" is missing a valid build.json at: ${buildJsonPath}`
654
- );
655
- }
656
- console.log(
657
- pc22.bold(pc22.blue(`
658
- --- Validating Infrastructure for [${serviceName}] ---`))
659
- );
660
- checkInfra(serviceDir);
661
1193
  }
1194
+ return out;
662
1195
  }
663
- function checkMeshTester(mesh, meshDir = process.cwd(), options = {}) {
664
- if (!mesh.tester) {
665
- if (options.required) {
666
- throw new ScriptError(
667
- 'E2E tester not configured in mesh.json: Missing "tester" configuration.'
668
- );
1196
+ function bindingKey(consumer, dependency) {
1197
+ return `${consumer}::${dependency}`;
1198
+ }
1199
+ function bindingsMap(bindings) {
1200
+ return new Map(bindings.map((b) => [bindingKey(b.consumerService, b.logicalDependency), b.providerService]));
1201
+ }
1202
+
1203
+ // src/core/mesh/v2/publication.ts
1204
+ var APP = /^app\.endpoints\.([a-z][a-z0-9-]*)$/;
1205
+ var DEP = /^dependencies\.([a-z][a-z0-9-]*)\.endpoints\.([a-z][a-z0-9-]*)$/;
1206
+ function resolveMeshPublication(services, bindings, stage, meshJsonPath) {
1207
+ const out = [];
1208
+ for (const svc of Object.values(services).sort((a, b) => a.name.localeCompare(b.name))) for (const raw of svc.publish) {
1209
+ let m;
1210
+ if (m = APP.exec(raw)) {
1211
+ const ep = m[1], endpoint = svc.effectiveBuild.app.endpoints[ep];
1212
+ if (!endpoint) throw new ConfigError({ sourceFile: meshJsonPath, configPath: `services.${svc.name}.publish`, stage, composition: "mesh", value: raw, reason: "Published app endpoint does not exist" });
1213
+ 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" });
1214
+ out.push({ logicalPath: `${svc.name}.app.endpoints.${ep}`, ownerMeshService: svc.name, target: "app", endpoint: ep });
1215
+ continue;
669
1216
  }
670
- return;
671
- }
672
- const absMeshDir = resolveProjectDir(meshDir);
673
- const testerConfig = mesh.tester;
674
- if (!testerConfig.path || typeof testerConfig.path !== "string") {
675
- throw new ScriptError(
676
- 'Invalid tester configuration in mesh.json: Missing or invalid "path".'
677
- );
1217
+ if (m = DEP.exec(raw)) {
1218
+ const dependency = m[1], endpoint = m[2], dep = svc.effectiveBuild.dependencies[dependency];
1219
+ 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" });
1220
+ 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" });
1221
+ 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" });
1222
+ 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" });
1223
+ out.push({ logicalPath: `${svc.name}.dependencies.${dependency}.endpoints.${endpoint}`, ownerMeshService: svc.name, target: "dependency", dependency, endpoint });
1224
+ continue;
1225
+ }
1226
+ 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>" });
678
1227
  }
679
- const absTesterDir = path13.resolve(absMeshDir, testerConfig.path);
680
- if (!isPathInside(absMeshDir, absTesterDir)) {
681
- throw new ScriptError(
682
- `Security error: Tester directory path "${testerConfig.path}" escapes the mesh project directory.`
683
- );
1228
+ return out;
1229
+ }
1230
+
1231
+ // src/core/mesh/v2/meshReferences.ts
1232
+ function resolveMesh(ref, ctx, source) {
1233
+ const name = ref.meshService;
1234
+ if (!ctx.services[name]) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: `Unknown mesh service reference "${name}"` });
1235
+ const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(name, ref.dependency)) : void 0;
1236
+ const ep = ref.target === "app" ? ctx.endpoints.app[name]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[name]?.[ref.dependency]?.[ref.endpoint];
1237
+ if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: "Referenced endpoint does not exist" });
1238
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1239
+ }
1240
+ function resolveBuild(ref, consumer, ctx, source) {
1241
+ const provider = ref.target === "dependency" ? ctx.bindings.get(bindingKey(consumer, ref.dependency)) : void 0;
1242
+ const ep = ref.target === "app" ? ctx.endpoints.app[consumer]?.[ref.endpoint] : provider ? ctx.endpoints.app[provider]?.[ref.endpoint] : ctx.endpoints.dependencies[consumer]?.[ref.dependency]?.[ref.endpoint];
1243
+ if (!ep) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: ref.raw, reason: provider ? `Provider "${provider}" does not expose endpoint "${ref.endpoint}"` : "Referenced endpoint does not exist" });
1244
+ try {
1245
+ return resolveEndpointProperty(ep, ref.property, { sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage });
1246
+ } catch (error) {
1247
+ if (provider && error instanceof ConfigError) throw new ConfigError({ sourceFile: ctx.meshJsonPath, configPath: source, stage: ctx.stage, composition: "mesh", referencedObject: `${consumer}.dependencies.${ref.dependency}.endpoints.${ref.endpoint}.${ref.property} -> ${provider}.app.endpoints.${ref.endpoint}.${ref.property}`, reason: error.message });
1248
+ throw error;
684
1249
  }
685
- if (!existsSync(absTesterDir)) {
686
- throw new ScriptError(
687
- `E2E tester directory does not exist: ${absTesterDir} (declared path: "${testerConfig.path}")`
688
- );
1250
+ }
1251
+ function interpolate(value, scope, resolve, source) {
1252
+ const sentinel = "\0DOLLAR\0";
1253
+ return value.replace(/\$\$/g, sentinel).replace(/\$\{([^}]*)\}/g, (_whole, body) => {
1254
+ const ref = collectBuilderReferences(`\${${body}}`, scope, source)[0];
1255
+ return resolve(ref);
1256
+ }).replaceAll(sentinel, "$").replace(/\$/g, "$$$$");
1257
+ }
1258
+ function resolveMeshEnvMap(env, ctx, sourcePrefix) {
1259
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "mesh", (ref) => resolveMesh(ref, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1260
+ }
1261
+ function resolveServiceBuildEnvThroughMesh(consumer, env, ctx, sourcePrefix) {
1262
+ return Object.fromEntries(Object.entries(env).map(([key, value]) => [key, interpolate(value, "build", (ref) => resolveBuild(ref, consumer, ctx, `${sourcePrefix}.${key}`), `${sourcePrefix}.${key}`)]));
1263
+ }
1264
+ function assertMeshTesterEnvPublic(env, source) {
1265
+ assertTesterReferencesArePublic(env, "mesh", source);
1266
+ }
1267
+
1268
+ // src/core/mesh/v2/lifecycle.ts
1269
+ function buildMeshLifecycleEdges(services, bindings, stage, meshJsonPath) {
1270
+ const result = [];
1271
+ const seen = /* @__PURE__ */ new Set();
1272
+ 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)]) {
1273
+ 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" });
1274
+ const source = svc.dependsOn.includes(provider) ? "dependsOn" : "dependency-binding";
1275
+ const id = `${svc.name}\0${provider}`;
1276
+ if (!seen.has(id)) {
1277
+ seen.add(id);
1278
+ result.push({ consumer: svc.name, provider, source });
1279
+ }
689
1280
  }
690
- console.log(
691
- pc22.bold(pc22.cyan(`
692
- \u{1F50D} Checking E2E Tester (${testerConfig.path})...`))
693
- );
694
- const composeRel = testerConfig.compose || "docker-compose.yml";
695
- const composePath = path13.resolve(absTesterDir, composeRel);
696
- if (!existsSync(composePath)) {
697
- throw new ScriptError(
698
- `E2E tester docker compose file not found at: ${composePath}`
699
- );
1281
+ const graph = new Map(Object.keys(services).map((name) => [name, /* @__PURE__ */ new Set()]));
1282
+ for (const edge of result) graph.get(edge.consumer).add(edge.provider);
1283
+ assertAcyclicGraph(graph, { sourceFile: meshJsonPath, stage, composition: "mesh" });
1284
+ return result;
1285
+ }
1286
+ function applyMeshLifecycleEdges(services, edges) {
1287
+ for (const edge of edges) {
1288
+ const consumer = services[edge.consumer];
1289
+ const old = consumer.depends_on && typeof consumer.depends_on === "object" && !Array.isArray(consumer.depends_on) ? consumer.depends_on : {};
1290
+ old[edge.provider] = { condition: "service_healthy" };
1291
+ consumer.depends_on = old;
700
1292
  }
701
- try {
702
- const composeContent = readFileSync(composePath, "utf-8");
703
- const docs = parseAllDocuments(composeContent);
704
- const docErrors = docs.flatMap((doc) => doc.errors);
705
- if (docErrors.length > 0) {
706
- throw new Error(docErrors.map((e) => e.message).join("\n"));
1293
+ }
1294
+
1295
+ // src/core/mesh/v2/compileMeshTester.ts
1296
+ function refs(svc) {
1297
+ const out = [];
1298
+ const add = (v) => {
1299
+ if (typeof v === "string") out.push(v);
1300
+ };
1301
+ if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1302
+ else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1303
+ if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1304
+ if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1305
+ if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1306
+ return out;
1307
+ }
1308
+ function referencedResources(svc, doc) {
1309
+ const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1310
+ for (const v of Array.isArray(svc.volumes) ? svc.volumes : []) {
1311
+ if (typeof v === "string") {
1312
+ const source = v.split(":")[0];
1313
+ if (doc.volumes?.[source]) sets.volumes.add(source);
1314
+ } else if (v && typeof v === "object" && v.type === "volume" && doc.volumes?.[v.source]) sets.volumes.add(v.source);
1315
+ }
1316
+ const nets = svc.networks;
1317
+ if (Array.isArray(nets)) nets.forEach((n) => {
1318
+ if (typeof n === "string" && doc.networks?.[n]) sets.networks.add(n);
1319
+ });
1320
+ else if (nets && typeof nets === "object") Object.keys(nets).forEach((n) => {
1321
+ if (doc.networks?.[n]) sets.networks.add(n);
1322
+ });
1323
+ for (const kind of ["configs", "secrets"]) {
1324
+ const v = svc[kind];
1325
+ if (Array.isArray(v)) for (const x of v) {
1326
+ const n = typeof x === "string" ? x : x?.source;
1327
+ if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1328
+ }
1329
+ }
1330
+ return sets;
1331
+ }
1332
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1333
+ const meshPath = `${meshDir}/mesh.json`, file = resolveInsideProject(meshDir, tester.compose, { sourceFile: meshPath, configPath: "tester.compose", stage }), raw = rebaseComposePaths(loadComposeDocument(file, { sourceFile: meshPath, configPath: "tester.compose", stage, composition: "mesh" }), file, meshDir);
1334
+ 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" });
1335
+ const included = /* @__PURE__ */ new Set(), visit = (name) => {
1336
+ if (included.has(name)) return;
1337
+ if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1338
+ included.add(name);
1339
+ for (const ref of refs(raw.services[name])) visit(ref);
1340
+ };
1341
+ visit(tester.service);
1342
+ for (const name of included) {
1343
+ const svc = raw.services[name];
1344
+ if (name !== tester.service && svc.network_mode === "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Only the selected tester runner may use host networking" });
1345
+ if (name === tester.service && svc.network_mode !== void 0 && svc.network_mode !== "host") throw new ConfigError({ sourceFile: file, configPath: `services.${name}.network_mode`, stage, composition: "mesh", reason: "Selected tester runner must be compatible with host networking" });
1346
+ if (name === tester.service && svc.networks !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.networks`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot declare networks" });
1347
+ }
1348
+ const res = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
1349
+ for (const name of included) {
1350
+ const own = referencedResources(raw.services[name], raw);
1351
+ for (const k of Object.keys(res)) for (const v of own[k]) res[k].add(v);
1352
+ }
1353
+ const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1354
+ for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1355
+ const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
1356
+ const runner = ns.serviceNameMap.get(tester.service);
1357
+ const runnerSvc = ns.document.services[runner];
1358
+ if (runnerSvc.ports !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${tester.service}.ports`, stage, composition: "mesh", reason: "Selected host-network tester runner cannot define ports" });
1359
+ runnerSvc.network_mode = "host";
1360
+ delete runnerSvc.networks;
1361
+ const meshCtx = referenceContext ?? { services: {}, bindings: /* @__PURE__ */ new Map(), endpoints: endpointRegistry, stage, meshJsonPath: meshPath };
1362
+ const env = tester.env ?? {};
1363
+ assertMeshTesterEnvPublic(env, "tester.env");
1364
+ runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1365
+ const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
1366
+ for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1367
+ runnerSvc.depends_on = depends;
1368
+ 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 };
1369
+ }
1370
+ function assertUniqueHostPortMappings(yamlConfig) {
1371
+ const parsed = parse(yamlConfig);
1372
+ const owners = /* @__PURE__ */ new Map();
1373
+ for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1374
+ for (const port of service?.ports ?? []) {
1375
+ let hostPort = null;
1376
+ if (typeof port === "string") {
1377
+ const parts = port.split(":");
1378
+ if (parts.length === 2) hostPort = Number(parts[0]);
1379
+ if (parts.length === 3) hostPort = Number(parts[1]);
1380
+ } else if (port && typeof port === "object" && "published" in port) {
1381
+ hostPort = Number(port.published);
1382
+ }
1383
+ if (!hostPort || !Number.isInteger(hostPort)) continue;
1384
+ const existing = owners.get(hostPort);
1385
+ if (existing) {
1386
+ throw new ScriptError(
1387
+ `Port Collision Detected: Host port ${hostPort} is requested by both "${existing}" and "${serviceName}".`
1388
+ );
1389
+ }
1390
+ owners.set(hostPort, serviceName);
707
1391
  }
708
- } catch (err) {
709
- throw new ScriptError(
710
- `Invalid YAML syntax in tester docker compose (${composeRel}): ${errorMessage(err)}`
711
- );
712
1392
  }
713
- const dockerfileRel = testerConfig.dockerfile || "Dockerfile";
714
- const dockerfilePath = path13.resolve(absTesterDir, dockerfileRel);
715
- if (!existsSync(dockerfilePath)) {
716
- throw new ScriptError(
717
- `E2E tester Dockerfile not found at: ${dockerfilePath}`
718
- );
1393
+ }
1394
+
1395
+ // src/core/mesh/v2/compileMeshComposition.ts
1396
+ function mergeFragment(target, fragment, owner) {
1397
+ for (const key of ["services", "volumes", "networks", "configs", "secrets"]) {
1398
+ const incoming = fragment[key];
1399
+ if (!incoming) continue;
1400
+ const dest = target[key] ??= {};
1401
+ for (const [name, value] of Object.entries(incoming)) {
1402
+ if (name in dest) throw new ConfigError({ configPath: `${key}.${name}`, referencedObject: owner, reason: "Mesh composition name collision" });
1403
+ dest[name] = value;
1404
+ }
1405
+ }
1406
+ }
1407
+ function appendPort(service, target, published) {
1408
+ const ports = Array.isArray(service.ports) ? service.ports : [];
1409
+ ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1410
+ service.ports = ports;
1411
+ }
1412
+ function ownerFor(pub, fragment) {
1413
+ return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1414
+ }
1415
+ function setEnv(service, env) {
1416
+ const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1417
+ service.environment = { ...current, ...env };
1418
+ }
1419
+ function compileMeshComposition(stage, meshDir, options = {}) {
1420
+ const meshPath = path4.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);
1421
+ const rawName = raw.name ?? path4.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
1422
+ const fragments = {};
1423
+ const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1424
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1425
+ 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" });
1426
+ const suppress = new Set(Object.keys(svc.dependencyBindings));
1427
+ const fragment = compileServiceComposition(stage, svc.absolutePath, { full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
1428
+ fragments[name] = fragment;
1429
+ mergeFragment(compose, fragment.compose, name);
1430
+ const app = compose.services[name];
1431
+ const networks = { mesh: null };
1432
+ const localDeps = Object.keys(fragment.endpoints.dependencies).filter((dep) => !bindingMap.has(bindingKey(name, dep)) && Object.keys(fragment.effectiveBuild.dependencies[dep]?.endpoints ?? {}).length > 0);
1433
+ if (localDeps.length) {
1434
+ const privateName = `mesh--${name}`;
1435
+ networks[privateName] = null;
1436
+ compose.networks[privateName] = { driver: "bridge" };
1437
+ for (const dep of localDeps) {
1438
+ for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1439
+ const owner = ep.networkHost;
1440
+ const ownerService = compose.services[owner];
1441
+ if (ownerService) {
1442
+ const old = ownerService.networks && typeof ownerService.networks === "object" && !Array.isArray(ownerService.networks) ? ownerService.networks : {};
1443
+ old[privateName] = null;
1444
+ ownerService.networks = old;
1445
+ }
1446
+ }
1447
+ for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
1448
+ const ownerService = compose.services[generated];
1449
+ const old = ownerService.networks && typeof ownerService.networks === "object" && !Array.isArray(ownerService.networks) ? ownerService.networks : {};
1450
+ old[privateName] = null;
1451
+ ownerService.networks = old;
1452
+ }
1453
+ }
1454
+ }
1455
+ app.networks = networks;
1456
+ }
1457
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1458
+ for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint))) {
1459
+ const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1460
+ intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1461
+ }
1462
+ for (const name of Object.keys(services).sort()) for (const pub of publication.filter((p) => p.ownerMeshService === name && p.target === "dependency").sort((a, b) => `${a.dependency}.${a.endpoint}`.localeCompare(`${b.dependency}.${b.endpoint}`))) {
1463
+ const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1464
+ intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1465
+ }
1466
+ const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
1467
+ const endpoints = { app: {}, dependencies: {} };
1468
+ for (const [name, svc] of Object.entries(services)) {
1469
+ endpoints.app[name] = {};
1470
+ for (const [epName, ep] of Object.entries(svc.effectiveBuild.app.endpoints)) {
1471
+ const host = name;
1472
+ const record = { logicalPath: `${name}.app.endpoints.${epName}`, networkHost: host, networkPort: ep.port, ...ep.scheme ? { scheme: ep.scheme } : {}, effectivelyPublished: false };
1473
+ endpoints.app[name][epName] = record;
1474
+ }
1475
+ endpoints.dependencies[name] = {};
1476
+ const fragment = fragments[name];
1477
+ for (const [depName, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
1478
+ if (bindingMap.has(bindingKey(name, depName))) continue;
1479
+ endpoints.dependencies[name][depName] = {};
1480
+ for (const [epName, def] of Object.entries(dep.endpoints)) {
1481
+ const local = fragment.endpoints.dependencies[depName]?.[epName];
1482
+ if (!local) continue;
1483
+ endpoints.dependencies[name][depName][epName] = { ...local, logicalPath: `${name}.dependencies.${depName}.endpoints.${epName}`, effectivelyPublished: false };
1484
+ }
1485
+ }
1486
+ }
1487
+ for (const pub of publication) {
1488
+ const ep = pub.target === "app" ? endpoints.app[pub.ownerMeshService]?.[pub.endpoint] : endpoints.dependencies[pub.ownerMeshService]?.[pub.dependency]?.[pub.endpoint];
1489
+ if (!ep) continue;
1490
+ ep.publicHost = PUBLIC_HOST;
1491
+ ep.publicPort = ports.get(pub.logicalPath);
1492
+ ep.effectivelyPublished = true;
1493
+ }
1494
+ for (const pub of publication) {
1495
+ const fragment = fragments[pub.ownerMeshService], endpoint = pub.target === "app" ? endpoints.app[pub.ownerMeshService][pub.endpoint] : endpoints.dependencies[pub.ownerMeshService][pub.dependency][pub.endpoint];
1496
+ const owner = ownerFor(pub, fragment);
1497
+ const service = compose.services[owner];
1498
+ if (service && endpoint) appendPort(service, endpoint.networkPort, endpoint.publicPort);
1499
+ }
1500
+ const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1501
+ for (const [name, fragment] of Object.entries(fragments)) {
1502
+ const app = compose.services[name];
1503
+ const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1504
+ const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1505
+ setEnv(app, { ...buildEnv, ...meshEnv });
1506
+ for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1507
+ const logicalBinding = bindingMap.get(bindingKey(name, depName));
1508
+ if (logicalBinding) continue;
1509
+ const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1510
+ const prefix = `svc--${name}--dep--${depName}--`;
1511
+ for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
1512
+ }
1513
+ }
1514
+ const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
1515
+ applyMeshLifecycleEdges(compose.services, edges);
1516
+ for (const [name, svc] of Object.entries(services)) for (const [sourceDep, dep] of Object.entries(svc.effectiveBuild.dependencies)) {
1517
+ if (bindingMap.has(bindingKey(name, sourceDep))) continue;
1518
+ for (const rawTarget of dep.dependsOn) {
1519
+ const targetKey = rawTarget.slice("dependencies.".length);
1520
+ const provider = bindingMap.get(bindingKey(name, targetKey));
1521
+ if (!provider) continue;
1522
+ const localEndpoints = endpoints.dependencies[name]?.[sourceDep] ?? {};
1523
+ for (const ep of Object.values(localEndpoints)) {
1524
+ const localOwner = ep.networkHost, localSvc = compose.services[localOwner];
1525
+ if (!localSvc) continue;
1526
+ const ds = localSvc.depends_on && typeof localSvc.depends_on === "object" && !Array.isArray(localSvc.depends_on) ? localSvc.depends_on : {};
1527
+ ds[provider] = { condition: "service_healthy" };
1528
+ localSvc.depends_on = ds;
1529
+ const net2 = localSvc.networks && typeof localSvc.networks === "object" && !Array.isArray(localSvc.networks) ? localSvc.networks : {};
1530
+ net2.mesh = null;
1531
+ localSvc.networks = net2;
1532
+ }
1533
+ }
1534
+ }
1535
+ const fullGraph = new Map(Object.keys(compose.services).map((name) => [name, /* @__PURE__ */ new Set()]));
1536
+ for (const [serviceName, service] of Object.entries(compose.services)) {
1537
+ const dependencies = service.depends_on;
1538
+ if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) for (const target of Object.keys(dependencies)) {
1539
+ if (fullGraph.has(target)) fullGraph.get(serviceName).add(target);
1540
+ }
1541
+ }
1542
+ assertAcyclicGraph(fullGraph, { sourceFile: meshPath, stage, composition: "mesh" });
1543
+ let testerServiceName;
1544
+ if (stage === "e2e") {
1545
+ 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? }" });
1546
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
1547
+ if (built) {
1548
+ 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 } : {} };
1549
+ mergeFragment(compose, fragment, "mesh tester");
1550
+ testerServiceName = built.runnerServiceName;
1551
+ }
719
1552
  }
720
- const dockerfileContent = readFileSync(dockerfilePath, "utf-8");
721
- console.log(pc22.cyan(`
722
- \u{1F50D} Linting E2E Tester Dockerfile (${dockerfileRel})...`));
723
- runStep(
724
- "docker",
725
- ["run", "--rm", "-i", "--network", "none", HADOLINT_IMAGE, "hadolint", "--failure-threshold", "error", "-"],
726
- absTesterDir,
727
- {
728
- stepName: "E2E Tester Dockerfile Linting",
729
- targetFile: dockerfileRel,
730
- input: dockerfileContent
1553
+ const yaml = stringify(compose);
1554
+ assertUniqueHostPortMappings(yaml);
1555
+ return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1556
+ }
1557
+
1558
+ // src/core/mesh/checkers/checkMeshServices.ts
1559
+ function checkMeshServices(mesh, meshDir) {
1560
+ const root = resolveProjectDir(meshDir), meshPath = path4.join(root, "mesh.json");
1561
+ const checked = /* @__PURE__ */ new Set();
1562
+ for (const stage of ["dev", "prod", "test", "e2e"]) {
1563
+ const effective = resolveMeshStage(mesh, stage, meshPath);
1564
+ const services = loadEffectiveMeshServices(root, effective, stage);
1565
+ for (const [name, svc] of Object.entries(services)) {
1566
+ if (!checked.has(svc.absolutePath)) {
1567
+ console.log(pc22.cyan(`
1568
+ \u{1F50D} Checking mesh service ${name}...`));
1569
+ checkInfra(svc.absolutePath);
1570
+ checked.add(svc.absolutePath);
1571
+ }
1572
+ if (stage === "test") {
1573
+ const fragment = compileServiceComposition("test", svc.absolutePath, { validationMode: true, meshMode: true, deferReferenceResolution: true });
1574
+ const endpoints = { app: { [name]: fragment.endpoints.app }, dependencies: { [name]: fragment.endpoints.dependencies } };
1575
+ const ctx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
1576
+ for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1577
+ 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" });
1578
+ }
1579
+ resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
1580
+ for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1581
+ resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1582
+ }
731
1583
  }
732
- );
733
- const dockerfilePolicyRel = testerConfig.policy?.dockerfile || "policy/dockerfile";
734
- const dockerfilePolicyDir = path13.resolve(absTesterDir, dockerfilePolicyRel);
735
- if (existsSync(dockerfilePolicyDir)) {
736
- console.log(
737
- pc22.cyan(
738
- `
739
- \u{1F50D} Validating Tester Dockerfile Contract (${dockerfilePolicyRel})...`
740
- )
741
- );
742
- runStep(
743
- "docker",
744
- [
745
- "run",
746
- "--rm",
747
- "--network",
748
- "none",
749
- "--mount",
750
- `type=bind,src=${absTesterDir},dst=/project,readonly`,
751
- "-w",
752
- "/project",
753
- CONFTEST_IMAGE,
754
- "test",
755
- dockerfileRel,
756
- "-p",
757
- `${dockerfilePolicyRel}/`
758
- ],
759
- absTesterDir,
760
- { stepName: "E2E Tester Dockerfile Contract", targetFile: dockerfileRel }
761
- );
1584
+ if (stage !== "test") compileMeshComposition(stage, root, { validationMode: true, allowMissingTester: true });
762
1585
  }
763
- const composePolicyRel = testerConfig.policy?.compose || "policy/compose";
764
- const composePolicyDir = path13.resolve(absTesterDir, composePolicyRel);
765
- if (existsSync(composePolicyDir)) {
766
- console.log(
767
- pc22.cyan(`
768
- \u{1F50D} Validating Tester Compose Contract (${composePolicyRel})...`)
769
- );
770
- runStep(
771
- "docker",
772
- [
773
- "run",
774
- "--rm",
775
- "--network",
776
- "none",
777
- "--mount",
778
- `type=bind,src=${absTesterDir},dst=/project,readonly`,
779
- "-w",
780
- "/project",
781
- CONFTEST_IMAGE,
782
- "test",
783
- composeRel,
784
- "-p",
785
- `${composePolicyRel}/`,
786
- "--all-namespaces"
787
- ],
788
- absTesterDir,
789
- { stepName: "E2E Tester Compose Contract", targetFile: composeRel }
790
- );
1586
+ }
1587
+ function checkMeshTester(mesh, meshDir, options = {}) {
1588
+ const root = resolveProjectDir(meshDir);
1589
+ if (!mesh.tester) {
1590
+ if (options.required) throw new ConfigError({ sourceFile: path4.join(root, "mesh.json"), configPath: "tester", stage: "e2e", composition: "mesh", reason: "Global mesh E2E requires root tester" });
1591
+ return;
791
1592
  }
792
- console.log(pc22.green(`\u2705 E2E tester configuration and contracts verified.
793
- `));
1593
+ const file = resolveInsideProject(root, mesh.tester.compose, { sourceFile: path4.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e" });
1594
+ loadComposeDocument(file, { sourceFile: path4.join(root, "mesh.json"), configPath: "tester.compose", stage: "e2e", composition: "mesh" });
1595
+ compileMeshComposition("e2e", root, { validationMode: true });
794
1596
  }
795
1597
 
796
1598
  // src/core/mesh/checkers/checkMesh.ts
@@ -801,7 +1603,7 @@ function checkMesh(meshDir = process.cwd(), options = {}) {
801
1603
  checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
802
1604
  console.log(
803
1605
  pc22.bold(
804
- pc22.green("\n\u{1F389} All mesh infrastructure, services, and contract checks passed!\n")
1606
+ pc22.green("\n\u{1F389} All V2 mesh infrastructure, services, and contract checks passed!\n")
805
1607
  )
806
1608
  );
807
1609
  }
@@ -840,960 +1642,104 @@ Examples:
840
1642
  }
841
1643
  });
842
1644
  };
843
- var extractBuildDeps = (buildJson, projectDir = process.cwd()) => {
844
- if (!buildJson || typeof buildJson !== "object") {
845
- return [];
846
- }
847
- if (!("dependencies" in buildJson) || !buildJson.dependencies) {
848
- return [];
849
- }
850
- const schema = z.object({
851
- dependencies: z.record(
852
- z.string(),
853
- z.object({
854
- path: z.string(),
855
- service: z.string().optional(),
856
- port: z.union([z.number(), z.string()]).optional()
857
- })
858
- )
859
- });
860
- const result = schema.safeParse(buildJson);
861
- if (!result.success) {
862
- const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
863
- throw new ScriptError(
864
- `Invalid build.json structure for dependencies: ${errorDetails}`
865
- );
866
- }
867
- const dependenciesData = result.data.dependencies;
868
- const dependencies = Object.entries(dependenciesData || {}).map(
869
- ([name, service]) => {
870
- return {
871
- path: path13.resolve(projectDir, service.path),
872
- name,
873
- serviceName: service.service,
874
- port: service.port
875
- };
876
- }
877
- );
878
- return dependencies;
879
- };
880
- var VALID_STAGES = ["dev", "prod", "test", "e2e"];
881
- var extractOverrides = (buildJson, projectDir = process.cwd()) => {
882
- if (!buildJson || typeof buildJson !== "object") {
883
- return {};
884
- }
885
- if (!("overrides" in buildJson) || !buildJson.overrides) {
886
- return {};
887
- }
888
- const schema = z.object({
889
- overrides: z.record(
890
- z.enum(VALID_STAGES, {
891
- errorMap: () => ({
892
- message: `Unknown stage override. Supported stages are: ${VALID_STAGES.join(", ")}`
893
- })
894
- }),
895
- z.object({
896
- path: z.string({ required_error: "Override 'path' is required" })
897
- })
898
- )
899
- });
900
- const result = schema.safeParse(buildJson);
901
- if (!result.success) {
902
- const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
903
- throw new ScriptError(
904
- `Invalid build.json structure for overrides: ${errorDetails}`
905
- );
1645
+ function compileMeshEnvironment(stage, rawMeshDir = process.cwd(), options = {}) {
1646
+ const meshDir = resolveProjectDir(rawMeshDir), compiled = compileMeshComposition(stage, meshDir), yaml = stringify(compiled.compose);
1647
+ if (options.validateWithDocker !== false) {
1648
+ const result = spawnSync("docker", ["compose", "--project-directory", meshDir, "-f", "-", "config", "--quiet"], { cwd: meshDir, encoding: "utf-8", input: yaml });
1649
+ 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 });
906
1650
  }
907
- const resolvedOverrides = {};
908
- for (const [key, value] of Object.entries(result.data.overrides)) {
909
- resolvedOverrides[key] = {
910
- path: path13.resolve(projectDir, value.path)
911
- };
912
- }
913
- return resolvedOverrides;
1651
+ return { yaml, ...compiled.testerServiceName ? { testerServiceName: compiled.testerServiceName } : {} };
1652
+ }
1653
+ var activeComposeSet = /* @__PURE__ */ new Set();
1654
+ var signalHandlersRegistered = false;
1655
+ var activeChildProcess = null;
1656
+ var isTearingDown = false;
1657
+ var isShuttingDown = false;
1658
+ var isProcessAlive = (c) => {
1659
+ return Boolean(c && c.exitCode === null && c.signalCode === null);
914
1660
  };
915
- function normalizeProjectName(name, projectDir) {
916
- let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
917
- if (!normalized || !/^[a-z0-9]/.test(normalized)) {
918
- return "project";
1661
+ function setActiveChild(child) {
1662
+ activeChildProcess = child;
1663
+ if (!child) {
1664
+ isShuttingDown = false;
919
1665
  }
920
- return normalized;
921
1666
  }
922
- function deriveProjectName(name, stage, projectDir, options = {}) {
923
- let base = normalizeProjectName(name);
924
- if (options.hash && projectDir) ;
925
- if (!stage) {
926
- return base;
927
- }
928
- const s = stage.toLowerCase();
929
- if (s === "dev") {
930
- return base;
931
- }
932
- if (s === "prod") {
933
- return `${base}-prod`;
934
- }
935
- if (s === "test" || s === "test-unit") {
936
- return `${base}-test`;
937
- }
938
- if (s === "e2e" || s === "test-e2e") {
939
- return `${base}-e2e`;
940
- }
941
- return `${base}-${s}`;
1667
+ function setTearingDown(tearingDown) {
1668
+ isTearingDown = tearingDown;
942
1669
  }
943
-
944
- // src/core/mesh/compileMeshEnvironment.ts
945
- function compileMeshEnvironment(mode, rawMeshDir = process.cwd(), options = {}) {
946
- const meshDir = resolveProjectDir(rawMeshDir);
947
- const mesh = getMeshJson(meshDir);
948
- const rawProjectName = mesh.name || path13.basename(meshDir);
949
- const projectName = deriveProjectName(
950
- rawProjectName,
951
- options.includeTester ? "e2e" : mode
952
- );
953
- const composeConfig = {
954
- name: projectName,
955
- networks: {
956
- mesh: {}
957
- },
958
- services: {}
1670
+ function registerActiveCompose(yamlConfig, projectDir, options = {}) {
1671
+ const entry = {
1672
+ yamlConfig,
1673
+ projectDir,
1674
+ removeVolumes: options.removeVolumes
959
1675
  };
960
- function mergeTopLevelResources(parsed) {
961
- if (!parsed || typeof parsed !== "object") return;
962
- for (const key of ["volumes", "secrets", "configs"]) {
963
- if (parsed[key] && typeof parsed[key] === "object") {
964
- composeConfig[key] = {
965
- ...composeConfig[key] || {},
966
- ...parsed[key]
967
- };
968
- }
969
- }
970
- }
971
- function rewriteServiceVolume(svc, oldKey, newKey) {
972
- if (!svc || !Array.isArray(svc.volumes)) return;
973
- svc.volumes = svc.volumes.map((vol) => {
974
- if (typeof vol === "string") {
975
- if (vol === oldKey) return newKey;
976
- if (vol.startsWith(`${oldKey}:`)) {
977
- return `${newKey}:${vol.slice(oldKey.length + 1)}`;
978
- }
979
- return vol;
980
- }
981
- if (vol && typeof vol === "object" && vol.source === oldKey) {
982
- return { ...vol, source: newKey };
983
- }
984
- return vol;
985
- });
986
- }
987
- function rewriteServiceSecret(svc, oldKey, newKey) {
988
- if (!svc || !svc.secrets) return;
989
- if (Array.isArray(svc.secrets)) {
990
- svc.secrets = svc.secrets.map((sec) => {
991
- if (sec === oldKey) return newKey;
992
- if (typeof sec === "object" && sec.source === oldKey) {
993
- return { ...sec, source: newKey };
994
- }
995
- return sec;
996
- });
1676
+ activeComposeSet.add(entry);
1677
+ ensureSignalHandlers();
1678
+ return () => {
1679
+ activeComposeSet.delete(entry);
1680
+ };
1681
+ }
1682
+ function ensureSignalHandlers() {
1683
+ if (signalHandlersRegistered) return;
1684
+ signalHandlersRegistered = true;
1685
+ const handleSignal = (signal) => {
1686
+ if (isTearingDown) {
1687
+ return;
997
1688
  }
998
- }
999
- function rewriteServiceConfig(svc, oldKey, newKey) {
1000
- if (!svc || !svc.configs) return;
1001
- if (Array.isArray(svc.configs)) {
1002
- svc.configs = svc.configs.map((cfg) => {
1003
- if (cfg === oldKey) return newKey;
1004
- if (typeof cfg === "object" && cfg.source === oldKey) {
1005
- return { ...cfg, source: newKey };
1689
+ if (activeChildProcess && isProcessAlive(activeChildProcess)) {
1690
+ const child = activeChildProcess;
1691
+ if (signal === "SIGINT") {
1692
+ if (!isShuttingDown) {
1693
+ isShuttingDown = true;
1694
+ setTimeout(() => {
1695
+ if (isProcessAlive(child)) {
1696
+ try {
1697
+ child.kill("SIGKILL");
1698
+ } catch {
1699
+ }
1700
+ }
1701
+ }, 1e4).unref();
1702
+ return;
1006
1703
  }
1007
- return cfg;
1008
- });
1009
- }
1010
- }
1011
- function mergeAndNamespaceMockResources(parsed, namespacePrefix, baseDir, targetMeshDir) {
1012
- if (!parsed || typeof parsed !== "object") return;
1013
- if (parsed.volumes && typeof parsed.volumes === "object") {
1014
- composeConfig.volumes = composeConfig.volumes || {};
1015
- for (const [volKey, volDef] of Object.entries(parsed.volumes)) {
1016
- const namespacedVolKey = `${namespacePrefix}_${volKey}`;
1017
- composeConfig.volumes[namespacedVolKey] = volDef ?? {};
1018
- if (parsed.services && typeof parsed.services === "object") {
1019
- for (const svc of Object.values(parsed.services)) {
1020
- rewriteServiceVolume(svc, volKey, namespacedVolKey);
1021
- }
1704
+ try {
1705
+ child.kill("SIGINT");
1706
+ } catch {
1022
1707
  }
1708
+ return;
1023
1709
  }
1024
- }
1025
- if (parsed.secrets && typeof parsed.secrets === "object") {
1026
- composeConfig.secrets = composeConfig.secrets || {};
1027
- for (const [secKey, secDef] of Object.entries(parsed.secrets)) {
1028
- const namespacedSecKey = `${namespacePrefix}_${secKey}`;
1029
- const clonedDef = { ...secDef };
1030
- if (clonedDef.file) {
1031
- clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1032
- }
1033
- composeConfig.secrets[namespacedSecKey] = clonedDef;
1034
- if (parsed.services && typeof parsed.services === "object") {
1035
- for (const svc of Object.values(parsed.services)) {
1036
- rewriteServiceSecret(svc, secKey, namespacedSecKey);
1037
- }
1038
- }
1710
+ try {
1711
+ child.kill(signal);
1712
+ } catch {
1039
1713
  }
1040
- }
1041
- if (parsed.configs && typeof parsed.configs === "object") {
1042
- composeConfig.configs = composeConfig.configs || {};
1043
- for (const [cfgKey, cfgDef] of Object.entries(parsed.configs)) {
1044
- const namespacedCfgKey = `${namespacePrefix}_${cfgKey}`;
1045
- const clonedDef = { ...cfgDef };
1046
- if (clonedDef.file) {
1047
- clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1048
- }
1049
- composeConfig.configs[namespacedCfgKey] = clonedDef;
1050
- if (parsed.services && typeof parsed.services === "object") {
1051
- for (const svc of Object.values(parsed.services)) {
1052
- rewriteServiceConfig(svc, cfgKey, namespacedCfgKey);
1714
+ setTimeout(() => {
1715
+ if (isProcessAlive(child)) {
1716
+ try {
1717
+ child.kill("SIGKILL");
1718
+ } catch {
1053
1719
  }
1054
1720
  }
1055
- }
1721
+ }, 1e4).unref();
1722
+ return;
1056
1723
  }
1057
- }
1058
- function applyInternalMockDependsOnMapping(svc, mapping) {
1059
- if (!svc.depends_on) return;
1060
- if (Array.isArray(svc.depends_on)) {
1061
- svc.depends_on = svc.depends_on.map((d) => mapping.get(d) || d);
1062
- } else if (typeof svc.depends_on === "object") {
1063
- const newDepends = {};
1064
- for (const [k, v] of Object.entries(svc.depends_on)) {
1065
- newDepends[mapping.get(k) || k] = v;
1724
+ if (isShuttingDown) return;
1725
+ isShuttingDown = true;
1726
+ for (const item of activeComposeSet) {
1727
+ try {
1728
+ teardownCompose(item.yamlConfig, item.projectDir, {
1729
+ removeVolumes: item.removeVolumes ?? false
1730
+ }).catch(() => {
1731
+ });
1732
+ } catch {
1066
1733
  }
1067
- svc.depends_on = newDepends;
1068
- }
1069
- }
1070
- function registerService(key, serviceDef, origin) {
1071
- if (composeConfig.services[key]) {
1072
- throw new ScriptError(
1073
- `Service name collision in mesh compose configuration: Service "${key}" from ${origin} conflicts with an existing service definition.`
1074
- );
1075
1734
  }
1076
- composeConfig.services[key] = serviceDef;
1077
- }
1078
- for (const serviceName of Object.keys(mesh.services)) {
1079
- composeConfig.networks[`${serviceName}_net`] = {};
1080
- }
1081
- if (mesh.dependencies && typeof mesh.dependencies === "object") {
1082
- for (const [depKey, depDef] of Object.entries(mesh.dependencies)) {
1083
- const depComposePath = path13.resolve(meshDir, depDef.path);
1084
- if (!existsSync(depComposePath)) {
1085
- throw new ScriptError(
1086
- `Root dependency compose file not found: ${depComposePath}`
1087
- );
1088
- }
1089
- const raw = readFileSync(depComposePath, "utf-8");
1090
- const parsed = parse(raw);
1091
- if (!parsed?.services || typeof parsed.services !== "object") {
1092
- throw new ScriptError(
1093
- `Root dependency compose file "${depDef.path}" does not define any services.`
1094
- );
1095
- }
1096
- mergeAndNamespaceMockResources(parsed, `mesh_${depKey}`, meshDir, meshDir);
1097
- const targetServiceName = depDef.service || Object.keys(parsed.services)[0];
1098
- const serviceEntry = targetServiceName ? parsed.services[targetServiceName] : void 0;
1099
- if (!serviceEntry) {
1100
- throw new ScriptError(
1101
- `Service "${targetServiceName}" not found in root dependency compose file: ${depComposePath}`
1102
- );
1103
- }
1104
- const sidecarMapping = /* @__PURE__ */ new Map();
1105
- for (const sName of Object.keys(parsed.services)) {
1106
- if (sName === targetServiceName) {
1107
- sidecarMapping.set(sName, depKey);
1108
- } else {
1109
- const companionKey = `${depKey}-${sName}`;
1110
- sidecarMapping.set(sName, composeConfig.services[sName] ? companionKey : sName);
1111
- }
1112
- }
1113
- const resolvedService = resolveServicePaths(serviceEntry, meshDir, meshDir);
1114
- delete resolvedService.container_name;
1115
- normalizeDependsOn(resolvedService);
1116
- applyInternalMockDependsOnMapping(resolvedService, sidecarMapping);
1117
- resolvedService.networks = {
1118
- mesh: {
1119
- aliases: [depKey, targetServiceName].filter(Boolean)
1120
- }
1121
- };
1122
- registerService(depKey, resolvedService, `root dependency "${depKey}"`);
1123
- for (const [sName, sDef] of Object.entries(parsed.services)) {
1124
- if (sName !== targetServiceName) {
1125
- const finalKey = sidecarMapping.get(sName);
1126
- const companion = resolveServicePaths(sDef, meshDir, meshDir);
1127
- delete companion.container_name;
1128
- normalizeDependsOn(companion);
1129
- applyInternalMockDependsOnMapping(companion, sidecarMapping);
1130
- companion.networks = {
1131
- mesh: {
1132
- aliases: [sName, finalKey]
1133
- }
1134
- };
1135
- registerService(finalKey, companion, `companion of root dependency "${depKey}"`);
1136
- }
1137
- }
1138
- }
1139
- }
1140
- const providerAliases = /* @__PURE__ */ new Map();
1141
- for (const sName of Object.keys(mesh.services)) {
1142
- providerAliases.set(sName, /* @__PURE__ */ new Set());
1143
- }
1144
- const globalDepAliasToProvider = /* @__PURE__ */ new Map();
1145
- const INTERNAL_PORT = 3e3;
1146
- const serviceUrls = /* @__PURE__ */ new Map();
1147
- const allocatedPorts = /* @__PURE__ */ new Map();
1148
- function claimPort(portVal, ownerDesc) {
1149
- if (!portVal) return;
1150
- const portStr = String(portVal);
1151
- const hostPort = portStr.includes(":") ? portStr.split(":")[0] : portStr;
1152
- if (!hostPort) return;
1153
- if (allocatedPorts.has(hostPort)) {
1154
- throw new ScriptError(
1155
- `\u274C Port Collision Detected: Host port ${hostPort} is requested by both [${allocatedPorts.get(hostPort)}] and [${ownerDesc}].`
1156
- );
1157
- }
1158
- allocatedPorts.set(hostPort, ownerDesc);
1159
- }
1160
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
1161
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
1162
- const serviceBuildJson = getBuildJson(serviceDir);
1163
- const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
1164
- let publicPort = null;
1165
- if (serviceConfig.port !== void 0 && serviceConfig.port !== null && serviceConfig.port !== "") {
1166
- publicPort = serviceConfig.port;
1167
- claimPort(publicPort, `mesh service "${serviceName}"`);
1168
- } else if (serviceConfig.preservePort && serviceBuildJson.port) {
1169
- publicPort = serviceBuildJson.port;
1170
- claimPort(publicPort, `mesh service "${serviceName}" (via preservePort)`);
1171
- }
1172
- const provideMap = {
1173
- ...serviceConfig.replaceMocks || {},
1174
- ...serviceConfig.provideDependency || {}
1175
- };
1176
- for (const dep of serviceDeps) {
1177
- if (!provideMap[dep.name] && !(mesh.dependencies && mesh.dependencies[dep.name]) && dep.port) {
1178
- claimPort(dep.port, `local dependency "${dep.name}" of service "${serviceName}"`);
1179
- }
1180
- }
1181
- const hostPort = publicPort ? String(publicPort).includes(":") ? String(publicPort).split(":")[0] : String(publicPort) : null;
1182
- serviceUrls.set(serviceName, {
1183
- networkUrl: `http://${serviceName}:${INTERNAL_PORT}`,
1184
- publicUrl: hostPort ? `http://localhost:${hostPort}` : null
1185
- });
1186
- }
1187
- function escapeRegExp(string) {
1188
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1189
- }
1190
- function interpolateEnvTemplates(value, context) {
1191
- if (typeof value !== "string") {
1192
- return value;
1193
- }
1194
- if (!options.silenceWarnings && context.includes("Tester") && value.includes(".network_url")) {
1195
- console.warn(
1196
- pc22.yellow(`
1197
- \u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${value}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
1198
- `)
1199
- );
1200
- }
1201
- let interpolated = value;
1202
- for (const [sName, urls] of serviceUrls.entries()) {
1203
- interpolated = interpolated.replace(
1204
- new RegExp(`\\$\\{${escapeRegExp(sName)}\\.network_url\\}`, "g"),
1205
- urls.networkUrl
1206
- );
1207
- if (urls.publicUrl) {
1208
- interpolated = interpolated.replace(
1209
- new RegExp(`\\$\\{${escapeRegExp(sName)}\\.public_url\\}`, "g"),
1210
- urls.publicUrl
1211
- );
1212
- }
1213
- }
1214
- const unresolvedMatch = interpolated.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
1215
- if (unresolvedMatch) {
1216
- const variable = unresolvedMatch[0];
1217
- const targetService = unresolvedMatch[1];
1218
- const type = unresolvedMatch[2];
1219
- if (!serviceUrls.has(targetService)) {
1220
- throw new ScriptError(
1221
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" is not defined in mesh.json.`
1222
- );
1223
- } else if (type === "public_url") {
1224
- throw new ScriptError(
1225
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' or 'preservePort' in mesh.json).`
1226
- );
1227
- } else {
1228
- throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
1229
- }
1230
- }
1231
- return interpolated;
1232
- }
1233
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
1234
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
1235
- const serviceBuildJson = getBuildJson(serviceDir);
1236
- const serviceOverrides = extractOverrides(serviceBuildJson, serviceDir);
1237
- const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
1238
- const relServiceDir = toComposePath(meshDir, serviceDir);
1239
- const dockerfile = serviceBuildJson.dockerfile || "Dockerfile";
1240
- const environment = {
1241
- INFRA_MODE: "integrated",
1242
- EXEC_MODE: mode
1243
- };
1244
- let overrideVolumes = [];
1245
- let overrideHealthcheck = void 0;
1246
- let overrideCommand = void 0;
1247
- let overrideApp = void 0;
1248
- const stageOverride = serviceOverrides[mode];
1249
- if (stageOverride && existsSync(stageOverride.path)) {
1250
- try {
1251
- const overrideYaml = parse(readFileSync(stageOverride.path, "utf-8"));
1252
- mergeTopLevelResources(overrideYaml);
1253
- overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
1254
- if (!overrideApp && overrideYaml?.services && Object.keys(overrideYaml.services).length > 0) {
1255
- throw new ScriptError(
1256
- `Override file "${stageOverride.path}" must define service "app" or "${serviceName}".`
1257
- );
1258
- }
1259
- if (overrideApp) {
1260
- if (Array.isArray(overrideApp.environment)) {
1261
- for (const item of overrideApp.environment) {
1262
- const eqIdx = item.indexOf("=");
1263
- if (eqIdx !== -1) {
1264
- environment[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1265
- } else {
1266
- environment[item] = process.env[item] ?? null;
1267
- }
1268
- }
1269
- } else if (overrideApp.environment && typeof overrideApp.environment === "object") {
1270
- Object.assign(environment, overrideApp.environment);
1271
- }
1272
- if (overrideApp.command) {
1273
- overrideCommand = overrideApp.command;
1274
- }
1275
- if (Array.isArray(overrideApp.volumes)) {
1276
- overrideVolumes = overrideApp.volumes.map(
1277
- (vol) => resolveVolumeEntry(vol, serviceDir, meshDir)
1278
- );
1279
- }
1280
- if (overrideApp.healthcheck) {
1281
- overrideHealthcheck = overrideApp.healthcheck;
1282
- }
1283
- }
1284
- } catch (err) {
1285
- if (err instanceof ScriptError) throw err;
1286
- const msg = err instanceof Error ? err.message : String(err);
1287
- throw new ScriptError(
1288
- `Failed to parse override file ${stageOverride.path}: ${msg}`
1289
- );
1290
- }
1291
- }
1292
- environment.PORT = String(INTERNAL_PORT);
1293
- const buildArgs = {};
1294
- if (overrideApp?.build?.args) {
1295
- if (Array.isArray(overrideApp.build.args)) {
1296
- for (const item of overrideApp.build.args) {
1297
- if (typeof item === "string") {
1298
- const eqIdx = item.indexOf("=");
1299
- if (eqIdx !== -1) {
1300
- buildArgs[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1301
- } else {
1302
- buildArgs[item] = process.env[item] ?? null;
1303
- }
1304
- }
1305
- }
1306
- } else if (typeof overrideApp.build.args === "object") {
1307
- Object.assign(buildArgs, overrideApp.build.args);
1308
- }
1309
- }
1310
- if (serviceBuildJson.envOverrides) {
1311
- for (const [k, v] of Object.entries(serviceBuildJson.envOverrides)) {
1312
- buildArgs[k] = interpolateEnvTemplates(v, `Service build.json: ${serviceName}`);
1313
- }
1314
- }
1315
- if (serviceConfig.envOverrides) {
1316
- for (const [k, v] of Object.entries(serviceConfig.envOverrides)) {
1317
- const interpolated = interpolateEnvTemplates(v, `Service: ${serviceName}`);
1318
- environment[k] = interpolated;
1319
- buildArgs[k] = interpolated;
1320
- }
1321
- }
1322
- const serviceDef = {
1323
- build: {
1324
- context: relServiceDir,
1325
- dockerfile,
1326
- target: mode,
1327
- ...Object.keys(buildArgs).length > 0 ? { args: buildArgs } : {}
1328
- },
1329
- init: true,
1330
- logging: {
1331
- driver: "json-file",
1332
- options: {
1333
- "max-size": "10m",
1334
- "max-file": "3"
1335
- }
1336
- },
1337
- environment,
1338
- depends_on: {}
1339
- };
1340
- const envFilePath = path13.resolve(serviceDir, `.env.${mode}`);
1341
- if (existsSync(envFilePath)) {
1342
- serviceDef.env_file = [toComposePath(meshDir, envFilePath)];
1343
- }
1344
- if (mode === "dev") {
1345
- const volSet = /* @__PURE__ */ new Set();
1346
- volSet.add(`${relServiceDir}:/app`);
1347
- volSet.add("/app/node_modules");
1348
- for (const v of overrideVolumes) {
1349
- if (typeof v === "string") {
1350
- volSet.add(v);
1351
- }
1352
- }
1353
- serviceDef.volumes = Array.from(volSet);
1354
- }
1355
- const urls = serviceUrls.get(serviceName);
1356
- if (urls.publicUrl) {
1357
- const pubPort = urls.publicUrl.split(":").pop();
1358
- serviceDef.ports = [`${pubPort}:${INTERNAL_PORT}`];
1359
- } else {
1360
- delete serviceDef.ports;
1361
- }
1362
- if (overrideCommand) {
1363
- serviceDef.command = overrideCommand;
1364
- }
1365
- if (serviceConfig.healthcheck) {
1366
- if (serviceConfig.healthcheck.type === "tcp") {
1367
- const hcPort = serviceConfig.healthcheck.port || INTERNAL_PORT;
1368
- serviceDef.healthcheck = {
1369
- test: [
1370
- "CMD-SHELL",
1371
- `nc -z 127.0.0.1 ${hcPort} || node -e "require('net').connect(${hcPort},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
1372
- ],
1373
- interval: "2s",
1374
- timeout: "2s",
1375
- start_period: "3s",
1376
- retries: 10
1377
- };
1378
- } else {
1379
- serviceDef.healthcheck = serviceConfig.healthcheck;
1380
- }
1381
- } else if (overrideHealthcheck) {
1382
- serviceDef.healthcheck = overrideHealthcheck;
1383
- } else {
1384
- serviceDef.healthcheck = {
1385
- test: [
1386
- "CMD-SHELL",
1387
- `nc -z 127.0.0.1 ${INTERNAL_PORT} || node -e "require('net').connect(${INTERNAL_PORT},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
1388
- ],
1389
- interval: "2s",
1390
- timeout: "2s",
1391
- start_period: "3s",
1392
- retries: 10
1393
- };
1394
- }
1395
- const namespacedAppKey = `${serviceName}-app`;
1396
- serviceDef.networks = {
1397
- mesh: {
1398
- aliases: [serviceName, namespacedAppKey]
1399
- },
1400
- [`${serviceName}_net`]: {
1401
- aliases: ["app", serviceName, namespacedAppKey]
1402
- }
1403
- };
1404
- const provideMap = {
1405
- ...serviceConfig.replaceMocks || {},
1406
- ...serviceConfig.provideDependency || {}
1407
- };
1408
- const declaredDepNames = new Set(serviceDeps.map((d) => d.name));
1409
- for (const [depKey, targetProvider] of Object.entries(provideMap)) {
1410
- if (!declaredDepNames.has(depKey)) {
1411
- throw new ScriptError(
1412
- `Service "${serviceName}" declares provideDependency/replaceMocks for "${depKey}", but "${depKey}" is not declared in its build.json dependencies.`
1413
- );
1414
- }
1415
- if (!mesh.services[targetProvider]) {
1416
- throw new ScriptError(
1417
- `Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetProvider}".`
1418
- );
1419
- }
1420
- if (globalDepAliasToProvider.has(depKey) && globalDepAliasToProvider.get(depKey) !== targetProvider) {
1421
- throw new ScriptError(
1422
- `Dependency alias collision: Dependency key "${depKey}" is mapped to multiple different provider services ("${globalDepAliasToProvider.get(
1423
- depKey
1424
- )}" and "${targetProvider}").`
1425
- );
1426
- }
1427
- if (mesh.services[depKey] && depKey !== targetProvider) {
1428
- throw new ScriptError(
1429
- `Dependency alias conflict: Dependency key "${depKey}" collides with declared mesh service "${depKey}".`
1430
- );
1431
- }
1432
- globalDepAliasToProvider.set(depKey, targetProvider);
1433
- }
1434
- for (const dep of serviceDeps) {
1435
- const depKey = dep.name;
1436
- if (provideMap[depKey]) {
1437
- const fellowService = provideMap[depKey];
1438
- const fellowAppKey = `${fellowService}-app`;
1439
- serviceDef.depends_on[fellowAppKey] = {
1440
- condition: "service_healthy"
1441
- };
1442
- providerAliases.get(fellowService)?.add(depKey);
1443
- } else if (mesh.dependencies && mesh.dependencies[depKey]) {
1444
- serviceDef.depends_on[depKey] = {
1445
- condition: "service_healthy"
1446
- };
1447
- } else {
1448
- const namespacedDepKey = `${serviceName}-${depKey}`;
1449
- serviceDef.depends_on[namespacedDepKey] = {
1450
- condition: "service_healthy"
1451
- };
1452
- const depComposePath = dep.path;
1453
- if (!existsSync(depComposePath)) {
1454
- throw new ScriptError(
1455
- `Mock compose file for dependency "${depKey}" not found: ${depComposePath}`
1456
- );
1457
- }
1458
- const raw = readFileSync(depComposePath, "utf-8");
1459
- const parsed = parse(raw);
1460
- if (!parsed?.services || typeof parsed.services !== "object") {
1461
- throw new ScriptError(
1462
- `Invalid compose file for dependency "${depKey}": missing "services"`
1463
- );
1464
- }
1465
- mergeAndNamespaceMockResources(parsed, `${serviceName}_${depKey}`, serviceDir, meshDir);
1466
- if (dep.serviceName && !parsed.services[dep.serviceName]) {
1467
- throw new ScriptError(
1468
- `Service "${dep.serviceName}" declared in build.json not found in mock compose ${depComposePath}`
1469
- );
1470
- }
1471
- const targetMockService = dep.serviceName ? parsed.services[dep.serviceName] : Object.values(parsed.services)[0];
1472
- if (!targetMockService) {
1473
- throw new ScriptError(
1474
- `No services found in mock compose ${depComposePath}`
1475
- );
1476
- }
1477
- const sidecarMapping = /* @__PURE__ */ new Map();
1478
- for (const mName of Object.keys(parsed.services)) {
1479
- if (parsed.services[mName] === targetMockService) {
1480
- sidecarMapping.set(mName, namespacedDepKey);
1481
- } else {
1482
- sidecarMapping.set(mName, `${serviceName}-${mName}`);
1483
- }
1484
- }
1485
- const resolvedMock = resolveServicePaths(
1486
- targetMockService,
1487
- serviceDir,
1488
- meshDir
1489
- );
1490
- delete resolvedMock.ports;
1491
- delete resolvedMock.container_name;
1492
- normalizeDependsOn(resolvedMock);
1493
- applyInternalMockDependsOnMapping(resolvedMock, sidecarMapping);
1494
- if (dep.port) {
1495
- const portMapping = String(dep.port).includes(":") ? String(dep.port) : `${dep.port}:3000`;
1496
- resolvedMock.ports = [...resolvedMock.ports || [], portMapping];
1497
- }
1498
- resolvedMock.networks = {
1499
- [`${serviceName}_net`]: {
1500
- aliases: [depKey, namespacedDepKey]
1501
- }
1502
- };
1503
- registerService(namespacedDepKey, resolvedMock, `mock dependency for "${serviceName}"`);
1504
- for (const [mName, mDef] of Object.entries(parsed.services)) {
1505
- if (mDef !== targetMockService) {
1506
- const sidecarKey = sidecarMapping.get(mName);
1507
- if (!composeConfig.services[sidecarKey]) {
1508
- const resolvedSidecar = resolveServicePaths(mDef, serviceDir, meshDir);
1509
- delete resolvedSidecar.ports;
1510
- delete resolvedSidecar.container_name;
1511
- normalizeDependsOn(resolvedSidecar);
1512
- applyInternalMockDependsOnMapping(resolvedSidecar, sidecarMapping);
1513
- resolvedSidecar.networks = {
1514
- [`${serviceName}_net`]: {
1515
- aliases: [mName, sidecarKey]
1516
- }
1517
- };
1518
- registerService(sidecarKey, resolvedSidecar, `sidecar of mock "${depKey}"`);
1519
- }
1520
- }
1521
- }
1522
- }
1523
- }
1524
- if (Object.keys(serviceDef.depends_on).length === 0) {
1525
- delete serviceDef.depends_on;
1526
- }
1527
- registerService(namespacedAppKey, serviceDef, `mesh service "${serviceName}"`);
1528
- }
1529
- for (const [providerName, aliases] of providerAliases.entries()) {
1530
- const appKey = `${providerName}-app`;
1531
- const serviceDef = composeConfig.services[appKey];
1532
- if (serviceDef && serviceDef.networks?.mesh) {
1533
- const existingAliases = new Set(serviceDef.networks.mesh.aliases || []);
1534
- for (const alias of aliases) {
1535
- existingAliases.add(alias);
1536
- }
1537
- serviceDef.networks.mesh.aliases = Array.from(existingAliases);
1538
- }
1539
- }
1540
- let testerServiceName;
1541
- if (options.includeTester && mesh.tester) {
1542
- const testerDir = path13.resolve(meshDir, mesh.tester.path);
1543
- const composeRel = mesh.tester.compose || "docker-compose.yml";
1544
- const testerComposePath = path13.resolve(testerDir, composeRel);
1545
- if (existsSync(testerComposePath)) {
1546
- const raw = readFileSync(testerComposePath, "utf-8");
1547
- const parsed = parse(raw);
1548
- mergeTopLevelResources(parsed);
1549
- if (parsed?.services && typeof parsed.services === "object") {
1550
- const firstKey = Object.keys(parsed.services)[0];
1551
- if (firstKey && parsed.services[firstKey]) {
1552
- testerServiceName = firstKey;
1553
- for (const [tKey, tDef] of Object.entries(parsed.services)) {
1554
- const resolvedTester = resolveServicePaths(
1555
- tDef,
1556
- testerDir,
1557
- meshDir
1558
- );
1559
- delete resolvedTester.container_name;
1560
- normalizeDependsOn(resolvedTester);
1561
- resolvedTester.network_mode = "host";
1562
- delete resolvedTester.networks;
1563
- if (tKey === firstKey) {
1564
- resolvedTester.depends_on = resolvedTester.depends_on || {};
1565
- for (const sName of Object.keys(mesh.services)) {
1566
- resolvedTester.depends_on[`${sName}-app`] = {
1567
- condition: "service_healthy"
1568
- };
1569
- }
1570
- if (mesh.tester.envOverrides) {
1571
- if (Array.isArray(resolvedTester.environment)) {
1572
- const envObj = {};
1573
- for (const item of resolvedTester.environment) {
1574
- if (typeof item === "string") {
1575
- const eqIdx = item.indexOf("=");
1576
- if (eqIdx !== -1) {
1577
- envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1578
- } else {
1579
- envObj[item] = process.env[item] ?? null;
1580
- }
1581
- }
1582
- }
1583
- resolvedTester.environment = envObj;
1584
- } else if (!resolvedTester.environment || typeof resolvedTester.environment !== "object") {
1585
- resolvedTester.environment = {};
1586
- }
1587
- for (const [k, v] of Object.entries(mesh.tester.envOverrides)) {
1588
- resolvedTester.environment[k] = interpolateEnvTemplates(v, `Tester: ${tKey}`);
1589
- }
1590
- }
1591
- }
1592
- registerService(tKey, resolvedTester, `tester service "${tKey}"`);
1593
- }
1594
- }
1595
- }
1596
- }
1597
- }
1598
- for (const svc of Object.values(composeConfig.services)) {
1599
- if (svc.depends_on && typeof svc.depends_on === "object") {
1600
- for (const [depTarget, depOpts] of Object.entries(svc.depends_on)) {
1601
- const targetSvc = composeConfig.services[depTarget];
1602
- if (targetSvc && (!targetSvc.healthcheck || targetSvc.healthcheck.disable) && depOpts && depOpts.condition === "service_healthy") {
1603
- depOpts.condition = "service_started";
1604
- }
1605
- }
1606
- }
1607
- }
1608
- const generatedYaml = stringify(composeConfig);
1609
- if (options.validateWithDocker === false) {
1610
- return { yaml: generatedYaml, testerServiceName };
1611
- }
1612
- const result = spawnSync(
1613
- "docker",
1614
- [
1615
- "compose",
1616
- "-p",
1617
- projectName,
1618
- "--project-directory",
1619
- meshDir,
1620
- "-f",
1621
- "-",
1622
- "config"
1623
- ],
1624
- {
1625
- cwd: meshDir,
1626
- input: generatedYaml,
1627
- encoding: "utf-8"
1628
- }
1629
- );
1630
- if (result.error) {
1631
- throw new ScriptError(
1632
- `Failed to run docker compose config: ${result.error.message}`,
1633
- { cause: result.error }
1634
- );
1635
- }
1636
- if (result.status !== 0) {
1637
- throw new ScriptError(
1638
- `\u274C Failed to validate mesh compose configuration:
1639
- ${result.stderr || result.stdout}`
1640
- );
1641
- }
1642
- return {
1643
- yaml: result.stdout || generatedYaml,
1644
- testerServiceName
1645
- };
1646
- }
1647
- function resolveVolumeEntry(vol, baseDir, meshDir) {
1648
- if (typeof vol === "string") {
1649
- if (!vol.includes(":")) {
1650
- return vol;
1651
- }
1652
- const parts = vol.split(":");
1653
- const host = parts[0];
1654
- if (isBindMount(host)) {
1655
- const absHost = path13.resolve(baseDir, host);
1656
- const formattedRel = toComposePath(meshDir, absHost);
1657
- return `${formattedRel}:${parts.slice(1).join(":")}`;
1658
- }
1659
- return vol;
1660
- }
1661
- if (vol && typeof vol === "object") {
1662
- const cloned = { ...vol };
1663
- if (cloned.type === "bind" && cloned.source && typeof cloned.source === "string") {
1664
- const absSource = path13.resolve(baseDir, cloned.source);
1665
- cloned.source = toComposePath(meshDir, absSource);
1666
- }
1667
- return cloned;
1668
- }
1669
- return vol;
1670
- }
1671
- function resolveServicePaths(service, baseDir, meshDir) {
1672
- const cloned = JSON.parse(JSON.stringify(service));
1673
- if (cloned.build) {
1674
- if (typeof cloned.build === "string") {
1675
- cloned.build = toComposePath(meshDir, path13.resolve(baseDir, cloned.build));
1676
- } else if (cloned.build.context) {
1677
- cloned.build.context = toComposePath(
1678
- meshDir,
1679
- path13.resolve(baseDir, cloned.build.context)
1680
- );
1681
- }
1682
- }
1683
- if (Array.isArray(cloned.volumes)) {
1684
- cloned.volumes = cloned.volumes.map(
1685
- (vol) => resolveVolumeEntry(vol, baseDir, meshDir)
1686
- );
1687
- }
1688
- if (Array.isArray(cloned.env_file)) {
1689
- cloned.env_file = cloned.env_file.map((ef) => {
1690
- if (typeof ef === "string") {
1691
- return toComposePath(meshDir, path13.resolve(baseDir, ef));
1692
- }
1693
- if (ef && typeof ef === "object" && ef.path) {
1694
- return {
1695
- ...ef,
1696
- path: toComposePath(meshDir, path13.resolve(baseDir, ef.path))
1697
- };
1698
- }
1699
- return ef;
1700
- });
1701
- } else if (typeof cloned.env_file === "string") {
1702
- cloned.env_file = toComposePath(meshDir, path13.resolve(baseDir, cloned.env_file));
1703
- }
1704
- normalizeDependsOn(cloned);
1705
- return cloned;
1706
- }
1707
- var activeComposeSet = /* @__PURE__ */ new Set();
1708
- var signalHandlersRegistered = false;
1709
- var activeChildProcess = null;
1710
- var isTearingDown = false;
1711
- var isShuttingDown = false;
1712
- var isProcessAlive = (c) => {
1713
- return Boolean(c && c.exitCode === null && c.signalCode === null);
1714
- };
1715
- function setActiveChild(child) {
1716
- activeChildProcess = child;
1717
- if (!child) {
1718
- isShuttingDown = false;
1719
- }
1720
- }
1721
- function setTearingDown(tearingDown) {
1722
- isTearingDown = tearingDown;
1723
- }
1724
- function registerActiveCompose(yamlConfig, projectDir, options = {}) {
1725
- const entry = {
1726
- yamlConfig,
1727
- projectDir,
1728
- removeVolumes: options.removeVolumes
1729
- };
1730
- activeComposeSet.add(entry);
1731
- ensureSignalHandlers();
1732
- return () => {
1733
- activeComposeSet.delete(entry);
1734
- };
1735
- }
1736
- function ensureSignalHandlers() {
1737
- if (signalHandlersRegistered) return;
1738
- signalHandlersRegistered = true;
1739
- const handleSignal = (signal) => {
1740
- if (isTearingDown) {
1741
- return;
1742
- }
1743
- if (activeChildProcess && isProcessAlive(activeChildProcess)) {
1744
- const child = activeChildProcess;
1745
- if (signal === "SIGINT") {
1746
- if (!isShuttingDown) {
1747
- isShuttingDown = true;
1748
- setTimeout(() => {
1749
- if (isProcessAlive(child)) {
1750
- try {
1751
- child.kill("SIGKILL");
1752
- } catch {
1753
- }
1754
- }
1755
- }, 1e4).unref();
1756
- return;
1757
- }
1758
- try {
1759
- child.kill("SIGINT");
1760
- } catch {
1761
- }
1762
- return;
1763
- }
1764
- try {
1765
- child.kill(signal);
1766
- } catch {
1767
- }
1768
- setTimeout(() => {
1769
- if (isProcessAlive(child)) {
1770
- try {
1771
- child.kill("SIGKILL");
1772
- } catch {
1773
- }
1774
- }
1775
- }, 1e4).unref();
1776
- return;
1777
- }
1778
- if (isShuttingDown) return;
1779
- isShuttingDown = true;
1780
- for (const item of activeComposeSet) {
1781
- try {
1782
- teardownCompose(item.yamlConfig, item.projectDir, {
1783
- removeVolumes: item.removeVolumes ?? false
1784
- }).catch(() => {
1785
- });
1786
- } catch {
1787
- }
1788
- }
1789
- activeComposeSet.clear();
1790
- const signalNumber = os.constants.signals[signal] ?? 0;
1791
- process.exit(128 + signalNumber);
1792
- };
1793
- const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1794
- for (const sig of SIGNALS) {
1795
- const listener = () => handleSignal(sig);
1796
- process.on(sig, listener);
1735
+ activeComposeSet.clear();
1736
+ const signalNumber = os.constants.signals[signal] ?? 0;
1737
+ process.exit(128 + signalNumber);
1738
+ };
1739
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1740
+ for (const sig of SIGNALS) {
1741
+ const listener = () => handleSignal(sig);
1742
+ process.on(sig, listener);
1797
1743
  }
1798
1744
  }
1799
1745
 
@@ -1915,12 +1861,12 @@ function redactYamlSecrets(yamlContent) {
1915
1861
  return redacted;
1916
1862
  }
1917
1863
  function getRunStatePath(projectDir) {
1918
- return path13.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
1864
+ return path4.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
1919
1865
  }
1920
1866
  function writeRunState(projectDir, state) {
1921
1867
  try {
1922
1868
  const absDir = resolveProjectDir(projectDir);
1923
- const builderDir = path13.resolve(absDir, ".builder");
1869
+ const builderDir = path4.resolve(absDir, ".builder");
1924
1870
  if (!existsSync(builderDir)) {
1925
1871
  mkdirSync(builderDir, { recursive: true });
1926
1872
  }
@@ -1929,7 +1875,7 @@ function writeRunState(projectDir, state) {
1929
1875
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
1930
1876
  };
1931
1877
  writeFileSync(
1932
- path13.resolve(builderDir, "run.state"),
1878
+ path4.resolve(builderDir, "run.state"),
1933
1879
  JSON.stringify(fullState, null, 2),
1934
1880
  "utf-8"
1935
1881
  );
@@ -1960,9 +1906,9 @@ function projectNamesForServiceStage(projectDir, stage) {
1960
1906
  let rawName;
1961
1907
  try {
1962
1908
  const buildJson = getBuildJson(absDir);
1963
- rawName = buildJson.name || path13.basename(absDir);
1909
+ rawName = buildJson.name || path4.basename(absDir);
1964
1910
  } catch {
1965
- rawName = path13.basename(absDir);
1911
+ rawName = path4.basename(absDir);
1966
1912
  }
1967
1913
  const s = stage.toLowerCase();
1968
1914
  if (s === "dev") {
@@ -1988,13 +1934,13 @@ function projectNamesForServiceStage(projectDir, stage) {
1988
1934
  function projectNamesForMeshStage(meshDir, stage) {
1989
1935
  const absDir = resolveProjectDir(meshDir);
1990
1936
  let rawMeshName;
1991
- let services = {};
1937
+ let serviceNames = [];
1992
1938
  try {
1993
1939
  const mesh = getMeshJson(absDir);
1994
- rawMeshName = mesh.name || path13.basename(absDir);
1995
- services = mesh.services || {};
1940
+ rawMeshName = mesh.name || path4.basename(absDir);
1941
+ serviceNames = Object.keys(resolveMeshStage(mesh, "test", path4.join(absDir, "mesh.json")).services);
1996
1942
  } catch {
1997
- rawMeshName = path13.basename(absDir);
1943
+ rawMeshName = path4.basename(absDir);
1998
1944
  }
1999
1945
  const s = stage.toLowerCase();
2000
1946
  if (s === "dev") {
@@ -2007,19 +1953,10 @@ function projectNamesForMeshStage(meshDir, stage) {
2007
1953
  return [deriveProjectName(rawMeshName, "e2e")];
2008
1954
  }
2009
1955
  if (s === "test-unit") {
2010
- return Object.values(services).map((svc) => {
2011
- const svcDir = path13.resolve(absDir, svc.path);
2012
- return projectNamesForServiceStage(svcDir, "test-unit")[0];
2013
- });
1956
+ return serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`);
2014
1957
  }
2015
1958
  if (s === "test") {
2016
- const list = [];
2017
- for (const svc of Object.values(services)) {
2018
- const svcDir = path13.resolve(absDir, svc.path);
2019
- list.push(...projectNamesForServiceStage(svcDir, "test"));
2020
- }
2021
- list.push(deriveProjectName(rawMeshName, "e2e"));
2022
- return Array.from(new Set(list));
1959
+ return [...serviceNames.map((name) => `${deriveProjectName(rawMeshName, "dev")}-${name}-test`), deriveProjectName(rawMeshName, "e2e")];
2023
1960
  }
2024
1961
  return [deriveProjectName(rawMeshName, s)];
2025
1962
  }
@@ -2040,9 +1977,8 @@ async function handleMeshDown(rawStage = "dev", options = {}) {
2040
1977
  );
2041
1978
  if (options.debug) {
2042
1979
  try {
2043
- const mode = stage === "dev" ? "dev" : "prod";
2044
- const includeTester = stage === "test" || stage === "test-e2e";
2045
- const { yaml } = compileMeshEnvironment(mode, meshDir, { includeTester });
1980
+ const mode = stage === "dev" ? "dev" : stage === "test-e2e" ? "e2e" : "prod";
1981
+ const { yaml } = compileMeshEnvironment(mode, meshDir, { validateWithDocker: false });
2046
1982
  console.log(
2047
1983
  pc22.yellow("\nFinal merged Mesh YAML configuration:\n"),
2048
1984
  redactYamlSecrets(yaml)
@@ -2146,13 +2082,7 @@ async function checkHostPortCollisions(ports) {
2146
2082
  if (port > 0 && port < 65536) {
2147
2083
  const inUse = await isPortInUse(port);
2148
2084
  if (inUse) {
2149
- console.warn(
2150
- pc22.yellow(
2151
- `
2152
- \u26A0\uFE0F Host Port Conflict Warning: Port ${port} is already in use on the host (e.g. by another running stage or process). Docker Compose may fail to bind to this port.
2153
- `
2154
- )
2155
- );
2085
+ throw new ScriptError(`Host port ${port} is already in use. Builder does not remap fixed public ports.`);
2156
2086
  }
2157
2087
  }
2158
2088
  }
@@ -2215,12 +2145,7 @@ async function runMeshDev(options = {}) {
2215
2145
  const meshDir = resolveProjectDir(options.projectDir);
2216
2146
  console.log(pc22.cyan(`
2217
2147
  \u{1F680} Starting Global DEV Mesh Environment...`));
2218
- if (!options.skipChecks) {
2219
- checkMesh(meshDir, { requireTester: false });
2220
- }
2221
- const { yaml } = compileMeshEnvironment("dev", meshDir, {
2222
- silenceWarnings: options.silenceWarnings
2223
- });
2148
+ const { yaml } = compileMeshEnvironment("dev", meshDir);
2224
2149
  const parsed = parse(yaml);
2225
2150
  const projectName = parsed?.name || "mesh-dev";
2226
2151
  if (options.debug) {
@@ -2259,1005 +2184,115 @@ async function runMeshDev(options = {}) {
2259
2184
  }
2260
2185
  async function runMeshProd(options = {}) {
2261
2186
  const meshDir = resolveProjectDir(options.projectDir);
2262
- console.log(pc22.cyan(`
2263
- \u{1F3ED} Starting Global PROD Mesh Environment...`));
2264
- if (!options.skipChecks) {
2265
- checkMesh(meshDir, { requireTester: false });
2266
- }
2267
- const { yaml } = compileMeshEnvironment("prod", meshDir, {
2268
- silenceWarnings: options.silenceWarnings
2269
- });
2270
- const parsed = parse(yaml);
2271
- const projectName = parsed?.name || "mesh-prod";
2272
- if (options.debug) {
2273
- console.log(
2274
- pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2275
- redactYamlSecrets(yaml)
2276
- );
2277
- }
2278
- if (options.dryRun) {
2279
- console.log(pc22.green("Dry run complete. Compose was not started."));
2280
- return 0;
2281
- }
2282
- const hostPorts = extractHostPorts(yaml);
2283
- await checkHostPortCollisions(hostPorts);
2284
- writeRunState(meshDir, {
2285
- projectName,
2286
- stage: "prod",
2287
- projectDir: meshDir
2288
- });
2289
- const upArgs = ["up", "--build"];
2290
- if (options.detach) {
2291
- upArgs.push("-d");
2292
- }
2293
- let status = 0;
2294
- try {
2295
- status = await runCompose(upArgs, yaml, meshDir, {
2296
- removeVolumes: false
2297
- });
2298
- } finally {
2299
- if (!options.detach) {
2300
- await teardownCompose(yaml, meshDir, { removeVolumes: false });
2301
- clearRunState(meshDir);
2302
- }
2303
- }
2304
- return status;
2305
- }
2306
-
2307
- // src/utils/ymlMods/addDependenciesToAppService.ts
2308
- var addDependenciesToAppService = (yml, dependencies) => {
2309
- if (!yml || !yml.services || !yml.services.app) {
2310
- throw new ScriptError("Invalid YAML structure. Missing 'services.app' field.");
2311
- }
2312
- if (!dependencies || dependencies.length === 0) {
2313
- return;
2314
- }
2315
- normalizeDependsOn(yml.services.app);
2316
- yml.services.app.depends_on = yml.services.app.depends_on || {};
2317
- dependencies.forEach((dep) => {
2318
- const targetSvc = yml.services[dep.name];
2319
- const hasHealthcheck = Boolean(targetSvc?.healthcheck);
2320
- yml.services.app.depends_on[dep.name] = {
2321
- condition: hasHealthcheck ? "service_healthy" : "service_started"
2322
- };
2323
- });
2324
- };
2325
-
2326
- // src/utils/ymlMods/attachName.ts
2327
- var attachName = (yml, nameOrBuildJson) => {
2328
- if (!yml) {
2329
- throw new ScriptError("Invalid YAML structure. Missing 'yml' field.");
2330
- }
2331
- const name = typeof nameOrBuildJson === "string" ? nameOrBuildJson : nameOrBuildJson?.name;
2332
- if (name) {
2333
- yml.name = name;
2334
- }
2335
- };
2336
-
2337
- // src/utils/ymlMods/makeE2eDependOnApp.ts
2338
- var makeE2eDependOnApp = (yml) => {
2339
- if (!yml || !yml.services) {
2340
- throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2341
- }
2342
- if (!yml.services.tester) {
2343
- throw new ScriptError("Tester service not found");
2344
- }
2345
- if (!yml.services.app) {
2346
- throw new ScriptError("App service not found");
2347
- }
2348
- normalizeDependsOn(yml.services.tester);
2349
- const appHasHealthcheck = Boolean(yml.services.app?.healthcheck);
2350
- yml.services.tester.depends_on = {
2351
- ...yml.services.tester.depends_on || {},
2352
- app: {
2353
- condition: appHasHealthcheck ? "service_healthy" : "service_started"
2354
- }
2355
- };
2356
- };
2357
-
2358
- // src/utils/ymlMods/renameServicesWithDependencies.ts
2359
- var renameServicesWithDependencies = (yml, dependencies) => {
2360
- if (!yml || !yml.services || typeof yml.services !== "object") {
2361
- throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2362
- }
2363
- if (!dependencies || dependencies.length === 0) {
2364
- return;
2365
- }
2366
- const renameMap = /* @__PURE__ */ new Map();
2367
- for (const dep of dependencies) {
2368
- if (dep.serviceName && dep.name && dep.serviceName !== dep.name) {
2369
- renameMap.set(dep.serviceName, dep.name);
2370
- }
2371
- }
2372
- if (renameMap.size === 0) {
2373
- return;
2374
- }
2375
- const currentKeys = new Set(Object.keys(yml.services));
2376
- for (const [oldName, newName] of renameMap.entries()) {
2377
- if (currentKeys.has(newName) && !renameMap.has(newName)) {
2378
- throw new ScriptError(
2379
- `Service collision: cannot rename "${oldName}" to "${newName}" because a service named "${newName}" already exists in the stack.`
2380
- );
2381
- }
2382
- }
2383
- const newServices = {};
2384
- for (const [name, service] of Object.entries(yml.services)) {
2385
- const targetName = renameMap.get(name) || name;
2386
- newServices[targetName] = service;
2387
- }
2388
- yml.services = newServices;
2389
- for (const service of Object.values(yml.services)) {
2390
- if (!service || typeof service !== "object") continue;
2391
- if (service.depends_on) {
2392
- if (Array.isArray(service.depends_on)) {
2393
- service.depends_on = service.depends_on.map(
2394
- (dep) => renameMap.get(dep) || dep
2395
- );
2396
- } else if (typeof service.depends_on === "object") {
2397
- const updatedDependsOn = {};
2398
- for (const [depName, depConfig] of Object.entries(service.depends_on)) {
2399
- const targetDepName = renameMap.get(depName) || depName;
2400
- updatedDependsOn[targetDepName] = depConfig;
2401
- }
2402
- service.depends_on = updatedDependsOn;
2403
- }
2404
- }
2405
- if (Array.isArray(service.links)) {
2406
- service.links = service.links.map((link) => {
2407
- const [targetSvc, alias] = link.split(":");
2408
- if (targetSvc && renameMap.has(targetSvc)) {
2409
- const newTarget = renameMap.get(targetSvc);
2410
- return alias ? `${newTarget}:${alias}` : newTarget;
2411
- }
2412
- return link;
2413
- });
2414
- }
2415
- if (typeof service.network_mode === "string" && service.network_mode.startsWith("service:")) {
2416
- const targetSvc = service.network_mode.slice("service:".length);
2417
- if (renameMap.has(targetSvc)) {
2418
- service.network_mode = `service:${renameMap.get(targetSvc)}`;
2419
- }
2420
- }
2421
- if (Array.isArray(service.volumes_from)) {
2422
- service.volumes_from = service.volumes_from.map((vf) => {
2423
- const [vfSvc, mode] = vf.split(":");
2424
- if (vfSvc && renameMap.has(vfSvc)) {
2425
- const newTarget = renameMap.get(vfSvc);
2426
- return mode ? `${newTarget}:${mode}` : newTarget;
2427
- }
2428
- return vf;
2429
- });
2430
- }
2431
- if (service.extends && typeof service.extends === "object") {
2432
- if (service.extends.service && renameMap.has(service.extends.service)) {
2433
- service.extends.service = renameMap.get(service.extends.service);
2434
- }
2435
- }
2436
- }
2437
- };
2438
- function findServiceDefinersInDeclaredFiles(buildJson, projectDir, serviceName) {
2439
- const declaredFiles = getDeclaredYamlFiles(buildJson, projectDir);
2440
- const hits = [];
2441
- for (const file of declaredFiles) {
2442
- if (!existsSync(file.absolutePath)) continue;
2443
- try {
2444
- const content = readFileSync(file.absolutePath, "utf-8");
2445
- const parsed = parse(content);
2446
- if (parsed && typeof parsed === "object" && parsed.services && typeof parsed.services === "object") {
2447
- const svc = parsed.services[serviceName];
2448
- if (svc) {
2449
- const hasImageOrBuild = Boolean(svc.image || svc.build);
2450
- hits.push(
2451
- ` - ${file.relativePath} (${file.source})${hasImageOrBuild ? " [defines image/build]" : " [no image/build]"}`
2452
- );
2453
- }
2454
- }
2455
- } catch {
2456
- }
2457
- }
2458
- return hits;
2459
- }
2460
- function explainComposeMergeFailure(buildJson, projectDir, envName, filesUsed, rawOutput) {
2461
- const lines = [];
2462
- const serviceMatch = rawOutput.match(
2463
- /service "([^"]+)" has neither an image nor a build context specified/
2464
- );
2465
- const envMissingMatch = /env file .* not found|no such file or directory.*\.env/i.test(rawOutput);
2466
- const actualComposeFiles = filesUsed.filter(
2467
- (f) => !f.startsWith("-") && (f.endsWith(".yml") || f.endsWith(".yaml"))
2468
- );
2469
- lines.push(`Environment : ${envName}`);
2470
- lines.push(`Compose files merged :`);
2471
- if (actualComposeFiles.length > 0) {
2472
- actualComposeFiles.forEach((f) => lines.push(` - ${f}`));
2473
- } else {
2474
- filesUsed.filter((f) => f !== "-f").forEach((f) => lines.push(` - ${f}`));
2475
- }
2476
- lines.push("");
2477
- if (serviceMatch && serviceMatch[1]) {
2478
- const serviceName = serviceMatch[1];
2479
- lines.push(
2480
- `ROOT CAUSE: Service "${serviceName}" is referenced in the merged stack, but none of the files provide an "image:" or "build:".`
2481
- );
2482
- lines.push("");
2483
- lines.push(
2484
- `Files declared in build.json that define a "${serviceName}:" service block:`
2485
- );
2486
- const definers = findServiceDefinersInDeclaredFiles(
2487
- buildJson,
2488
- projectDir,
2489
- serviceName
2490
- );
2491
- if (definers.length > 0) {
2492
- definers.forEach((d) => lines.push(d));
2493
- } else {
2494
- lines.push(
2495
- ` (none found \u2014 check spelling/indentation of "${serviceName}:" in files declared in build.json)`
2496
- );
2497
- }
2498
- lines.push("");
2499
- lines.push("HOW TO FIX:");
2500
- lines.push(
2501
- ` - Ensure the file declaring service "${serviceName}" with an "image:" or "build:" is referenced in build.json under dependencies or overrides.`
2502
- );
2503
- } else if (/env_file.*must be a string/i.test(rawOutput)) {
2504
- lines.push(
2505
- `ROOT CAUSE: Docker Compose schema error for env_file. Your Docker Compose version is likely older than 2.24.0, which does not support the object syntax { path, required: false }.`
2506
- );
2507
- lines.push("");
2508
- lines.push("HOW TO FIX:");
2509
- lines.push(
2510
- ` - Upgrade Docker Compose to version 2.24.0 or newer to support modern compose templates.`
2511
- );
2512
- } else if (/required variable "?([^"\s]+)"? is missing a value/i.test(rawOutput)) {
2513
- const varMatch = rawOutput.match(/required variable "?([^"\s]+)"? is missing a value/i);
2514
- const varName = varMatch ? varMatch[1] : "VARIABLE";
2515
- lines.push(
2516
- `ROOT CAUSE: Required environment variable "${varName}" is missing a value.`
2517
- );
2518
- lines.push("");
2519
- lines.push("HOW TO FIX:");
2520
- lines.push(
2521
- ` - Define "${varName}" in your shell environment or inside your .env file.`
2522
- );
2523
- } else if (/port is already allocated|address already in use/i.test(rawOutput)) {
2524
- lines.push(
2525
- `ROOT CAUSE: Host port collision. A requested host port is already allocated or in use by another running process or container.`
2526
- );
2527
- lines.push("");
2528
- lines.push("HOW TO FIX:");
2529
- lines.push(
2530
- ` - Stop the conflicting process or container, or change the exposed host port in build.json / compose overrides.`
2531
- );
2532
- } else if (envMissingMatch) {
2533
- lines.push(`ROOT CAUSE: A referenced .env file could not be found.`);
2534
- lines.push("");
2535
- lines.push("HOW TO FIX:");
2536
- lines.push(
2537
- ` - Create the missing env file at the project root (e.g. .env.dev, .env.prod, .env.test)`
2538
- );
2539
- } else {
2540
- lines.push(
2541
- "Docker Compose failed to resolve this merged stack. Common causes:"
2542
- );
2543
- lines.push(
2544
- ` - A "\${VAR}" substitution with no default and no value set in the shell or an env_file.`
2545
- );
2546
- lines.push(` - A YAML syntax error in one of the files listed in build.json.`);
2547
- lines.push(` - A duplicate or conflicting key across merged compose files.`);
2548
- }
2549
- lines.push("");
2550
- lines.push("Raw Docker Compose output:");
2551
- lines.push("-".repeat(60));
2552
- lines.push(rawOutput.trim());
2553
- lines.push("-".repeat(60));
2554
- return lines.join("\n");
2555
- }
2556
- var cachedTemplatesDir = null;
2557
- var lastEnvTemplatesDir = void 0;
2558
- function getTemplatesDir() {
2559
- const envVal = process.env.BUILDER_TEMPLATES_DIR;
2560
- if (envVal !== lastEnvTemplatesDir) {
2561
- cachedTemplatesDir = null;
2562
- lastEnvTemplatesDir = envVal;
2563
- }
2564
- if (envVal) {
2565
- const envDir = path13.resolve(envVal);
2566
- if (!fs.existsSync(envDir) || !fs.existsSync(path13.join(envDir, "docker"))) {
2567
- throw new ScriptError(
2568
- `BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
2569
- );
2570
- }
2571
- return envDir;
2572
- }
2573
- if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
2574
- return cachedTemplatesDir;
2575
- }
2576
- const currentDir = typeof __dirname !== "undefined" ? __dirname : path13.dirname(fileURLToPath(import.meta.url));
2577
- const candidates = [
2578
- // When executing compiled output in dist/ (e.g. dist/templates)
2579
- path13.resolve(currentDir, "templates"),
2580
- path13.resolve(currentDir, "../templates"),
2581
- // When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
2582
- path13.resolve(currentDir, "../../templates"),
2583
- // Fallback relative to cwd
2584
- path13.resolve(process.cwd(), "templates")
2585
- ];
2586
- for (const cand of candidates) {
2587
- if (fs.existsSync(cand) && fs.existsSync(path13.join(cand, "docker"))) {
2588
- cachedTemplatesDir = cand;
2589
- return cand;
2590
- }
2591
- }
2592
- throw new ScriptError(
2593
- `Templates directory not found. Searched candidates:
2594
- ${candidates.join("\n")}`
2595
- );
2596
- }
2597
- function getDockerComposeTemplate(filename) {
2598
- const templatesDir = getTemplatesDir();
2599
- const filePath = path13.join(templatesDir, "docker", filename);
2600
- if (!fs.existsSync(filePath)) {
2601
- throw new ScriptError(`Docker compose template not found: ${filePath}`);
2602
- }
2603
- return filePath;
2604
- }
2605
-
2606
- // src/core/compileEnvironment.ts
2607
- var compileEnvironment = (environment, projectDir = process.cwd(), options = {}) => {
2608
- const absProjectDir = resolveProjectDir(projectDir);
2609
- const buildJson = getBuildJson(absProjectDir);
2610
- const overrides = extractOverrides(buildJson, absProjectDir);
2611
- const dependencies = extractBuildDeps(buildJson, absProjectDir);
2612
- const rawProjectName = buildJson.name || path13.basename(absProjectDir);
2613
- const projectName = deriveProjectName(rawProjectName, environment);
2614
- const baseComposePath = getDockerComposeTemplate("docker-compose.base.yml");
2615
- const composeFlags = [
2616
- "compose",
2617
- "-p",
2618
- projectName,
2619
- "--project-directory",
2620
- absProjectDir,
2621
- "-f",
2622
- baseComposePath
2623
- ];
2624
- const filesUsed = [baseComposePath];
2625
- const defaultEnv = path13.resolve(absProjectDir, ".env");
2626
- if (existsSync(defaultEnv)) {
2627
- composeFlags.push("--env-file", defaultEnv);
2628
- }
2629
- if (environment === "e2e") {
2630
- const prodEnv = path13.resolve(absProjectDir, ".env.prod");
2631
- if (existsSync(prodEnv)) {
2632
- composeFlags.push("--env-file", prodEnv);
2633
- }
2634
- const e2eEnv = path13.resolve(absProjectDir, ".env.e2e");
2635
- if (existsSync(e2eEnv)) {
2636
- composeFlags.push("--env-file", e2eEnv);
2637
- }
2638
- } else {
2639
- const stageEnv = path13.resolve(absProjectDir, `.env.${environment}`);
2640
- if (existsSync(stageEnv)) {
2641
- composeFlags.push("--env-file", stageEnv);
2642
- }
2643
- }
2644
- switch (environment) {
2645
- case "dev": {
2646
- const devPath = getDockerComposeTemplate("docker-compose.dev.yml");
2647
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2648
- composeFlags.push("-f", devPath);
2649
- filesUsed.push(devPath);
2650
- if (overrides.dev) {
2651
- composeFlags.push("-f", overrides.dev.path);
2652
- filesUsed.push(overrides.dev.path);
2653
- }
2654
- if (options.full && dependencies.length > 0) {
2655
- for (const dep of dependencies) {
2656
- composeFlags.push("-f", dep.path);
2657
- filesUsed.push(dep.path);
2658
- }
2659
- }
2660
- composeFlags.push("-f", standalonePath);
2661
- filesUsed.push(standalonePath);
2662
- break;
2663
- }
2664
- case "test": {
2665
- const testPath = getDockerComposeTemplate("docker-compose.test.yml");
2666
- composeFlags.push("-f", testPath);
2667
- filesUsed.push(testPath);
2668
- if (overrides.test) {
2669
- composeFlags.push("-f", overrides.test.path);
2670
- filesUsed.push(overrides.test.path);
2671
- }
2672
- break;
2673
- }
2674
- case "prod": {
2675
- const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2676
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2677
- composeFlags.push("-f", prodPath);
2678
- filesUsed.push(prodPath);
2679
- if (overrides.prod) {
2680
- composeFlags.push("-f", overrides.prod.path);
2681
- filesUsed.push(overrides.prod.path);
2682
- }
2683
- if (dependencies.length > 0) {
2684
- for (const dep of dependencies) {
2685
- composeFlags.push("-f", dep.path);
2686
- filesUsed.push(dep.path);
2687
- }
2688
- }
2689
- composeFlags.push("-f", standalonePath);
2690
- filesUsed.push(standalonePath);
2691
- break;
2692
- }
2693
- case "e2e": {
2694
- const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2695
- const e2ePath = getDockerComposeTemplate("docker-compose.e2e.yml");
2696
- const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2697
- composeFlags.push("-f", prodPath);
2698
- filesUsed.push(prodPath);
2699
- if (overrides.prod) {
2700
- composeFlags.push("-f", overrides.prod.path);
2701
- filesUsed.push(overrides.prod.path);
2702
- }
2703
- if (dependencies.length > 0) {
2704
- for (const dep of dependencies) {
2705
- composeFlags.push("-f", dep.path);
2706
- filesUsed.push(dep.path);
2707
- }
2708
- }
2709
- composeFlags.push("-f", standalonePath);
2710
- filesUsed.push(standalonePath);
2711
- composeFlags.push("-f", e2ePath);
2712
- filesUsed.push(e2ePath);
2713
- if (overrides.e2e) {
2714
- composeFlags.push("-f", overrides.e2e.path);
2715
- filesUsed.push(overrides.e2e.path);
2716
- }
2717
- break;
2718
- }
2719
- }
2720
- composeFlags.push("config");
2721
- const envVars = { ...process.env };
2722
- if (buildJson.port) {
2723
- envVars.PUBLIC_PORT = String(buildJson.port);
2724
- }
2725
- envVars.PORT = "3000";
2726
- const result = spawnSync("docker", composeFlags, {
2727
- cwd: absProjectDir,
2728
- encoding: "utf-8",
2729
- env: envVars
2730
- });
2731
- if (result.error) {
2732
- throw new ScriptError(
2733
- `Failed to run docker compose: ${result.error.message}`,
2734
- { cause: result.error }
2735
- );
2736
- }
2737
- if (result.status !== 0) {
2738
- const rawOutput = result.stderr || result.stdout;
2739
- const explanation = explainComposeMergeFailure(
2740
- buildJson,
2741
- absProjectDir,
2742
- environment,
2743
- filesUsed,
2744
- rawOutput
2745
- );
2746
- throw new ScriptError(`\u274C Failed to merge compose files:
2747
- ${explanation}`);
2748
- }
2749
- const mergedYamlConfig = result.stdout;
2750
- const yml = parse(mergedYamlConfig);
2751
- if (environment === "prod" || environment === "e2e" || environment === "dev" && options.full) {
2752
- renameServicesWithDependencies(yml, dependencies);
2753
- addDependenciesToAppService(yml, dependencies);
2754
- }
2755
- if (environment === "e2e") {
2756
- makeE2eDependOnApp(yml);
2757
- }
2758
- const INTERNAL_PORT = 3e3;
2759
- const urlRegistry = /* @__PURE__ */ new Map();
2760
- const appPublicPort = buildJson.port ? Number(buildJson.port) : null;
2761
- urlRegistry.set("app", {
2762
- networkUrl: `http://app:${INTERNAL_PORT}`,
2763
- publicUrl: appPublicPort ? `http://localhost:${appPublicPort}` : null
2764
- });
2765
- if (buildJson.name && buildJson.name !== "app") {
2766
- urlRegistry.set(buildJson.name, urlRegistry.get("app"));
2767
- }
2768
- for (const dep of dependencies) {
2769
- const depPortStr = dep.port ? String(dep.port) : null;
2770
- const depHostPort = depPortStr ? depPortStr.includes(":") ? depPortStr.split(":")[0] : depPortStr : null;
2771
- urlRegistry.set(dep.name, {
2772
- networkUrl: `http://${dep.name}:${INTERNAL_PORT}`,
2773
- publicUrl: depHostPort ? `http://localhost:${depHostPort}` : null
2774
- });
2775
- }
2776
- const interpolateEnv = (val, context) => {
2777
- if (!options.silenceWarnings && context.includes("Tester") && val.includes(".network_url")) {
2778
- console.warn(
2779
- pc22.yellow(`
2780
- \u26A0\uFE0F WARNING: You are passing a '.network_url' template to the E2E tester ("${val}"). Since the tester runs in 'network_mode: host', it cannot resolve internal Docker DNS. Use '.public_url' instead. (Mute with --silence-warnings)
2781
- `)
2782
- );
2783
- }
2784
- let output = val;
2785
- for (const [sName, urls] of urlRegistry.entries()) {
2786
- const escaped = sName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2787
- output = output.replace(
2788
- new RegExp(`\\$\\{${escaped}\\.network_url\\}`, "g"),
2789
- urls.networkUrl
2790
- );
2791
- if (urls.publicUrl) {
2792
- output = output.replace(
2793
- new RegExp(`\\$\\{${escaped}\\.public_url\\}`, "g"),
2794
- urls.publicUrl
2795
- );
2796
- }
2797
- }
2798
- const unresolvedMatch = output.match(/\$\{([^}]+?)\.(network_url|public_url)\}/);
2799
- if (unresolvedMatch) {
2800
- const variable = unresolvedMatch[0];
2801
- const targetService = unresolvedMatch[1];
2802
- const type = unresolvedMatch[2];
2803
- if (!urlRegistry.has(targetService)) {
2804
- throw new ScriptError(
2805
- `[${context}] Unresolved template variable: ${variable}. Check build.json dependencies.`
2806
- );
2807
- } else if (type === "public_url") {
2808
- throw new ScriptError(
2809
- `[${context}] Unresolved template variable: ${variable}. Service "${targetService}" does not expose a public port (missing 'port' explicitly defined in build.json).`
2810
- );
2811
- } else {
2812
- throw new ScriptError(`[${context}] Unresolved template variable: ${variable}.`);
2813
- }
2814
- }
2815
- return output;
2816
- };
2817
- const normalizeEnvironment = (serviceConfig) => {
2818
- if (Array.isArray(serviceConfig.environment)) {
2819
- const envObj = {};
2820
- for (const item of serviceConfig.environment) {
2821
- if (typeof item === "string") {
2822
- const eqIdx = item.indexOf("=");
2823
- if (eqIdx !== -1) {
2824
- envObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
2825
- } else {
2826
- envObj[item] = process.env[item] ?? null;
2827
- }
2828
- }
2829
- }
2830
- serviceConfig.environment = envObj;
2831
- } else if (!serviceConfig.environment || typeof serviceConfig.environment !== "object") {
2832
- serviceConfig.environment = {};
2833
- }
2834
- };
2835
- const normalizeBuildArgs = (serviceConfig) => {
2836
- if (typeof serviceConfig.build === "string") {
2837
- serviceConfig.build = {
2838
- context: serviceConfig.build
2839
- };
2840
- }
2841
- if (serviceConfig.build && typeof serviceConfig.build === "object") {
2842
- if (Array.isArray(serviceConfig.build.args)) {
2843
- const argsObj = {};
2844
- for (const item of serviceConfig.build.args) {
2845
- if (typeof item === "string") {
2846
- const eqIdx = item.indexOf("=");
2847
- if (eqIdx !== -1) {
2848
- argsObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
2849
- } else {
2850
- argsObj[item] = process.env[item] ?? null;
2851
- }
2852
- }
2853
- }
2854
- serviceConfig.build.args = argsObj;
2855
- } else if (!serviceConfig.build.args || typeof serviceConfig.build.args !== "object") {
2856
- serviceConfig.build.args = {};
2857
- }
2858
- }
2859
- };
2860
- if (buildJson.envOverrides && yml.services && yml.services.app) {
2861
- normalizeEnvironment(yml.services.app);
2862
- normalizeBuildArgs(yml.services.app);
2863
- for (const [k, v] of Object.entries(buildJson.envOverrides)) {
2864
- const val = interpolateEnv(v, "App EnvOverrides");
2865
- yml.services.app.environment[k] = val;
2866
- if (yml.services.app.build?.args) {
2867
- yml.services.app.build.args[k] = val;
2868
- }
2869
- }
2870
- }
2871
- if (buildJson.tester?.envOverrides && yml.services && yml.services.tester) {
2872
- normalizeEnvironment(yml.services.tester);
2873
- normalizeBuildArgs(yml.services.tester);
2874
- for (const [k, v] of Object.entries(buildJson.tester.envOverrides)) {
2875
- const val = interpolateEnv(v, "Tester EnvOverrides");
2876
- yml.services.tester.environment[k] = val;
2877
- if (yml.services.tester.build?.args) {
2878
- yml.services.tester.build.args[k] = val;
2879
- }
2880
- }
2881
- }
2882
- if (yml.services) {
2883
- for (const dep of dependencies) {
2884
- if (dep.port) {
2885
- let targetSvc = dep.serviceName && yml.services[dep.serviceName] ? dep.serviceName : dep.name;
2886
- if (!yml.services[targetSvc]) {
2887
- targetSvc = Object.keys(yml.services).find((k) => k !== "app" && k !== "tester") || targetSvc;
2888
- }
2889
- if (yml.services[targetSvc]) {
2890
- const portMapping = String(dep.port).includes(":") ? String(dep.port) : `${dep.port}:3000`;
2891
- yml.services[targetSvc].ports = [...yml.services[targetSvc].ports || [], portMapping];
2892
- }
2893
- }
2894
- }
2895
- }
2896
- if (environment === "dev" && options.full && yml.services?.app) {
2897
- normalizeEnvironment(yml.services.app);
2898
- yml.services.app.environment.INFRA_MODE = "integrated";
2899
- }
2900
- attachName(yml, projectName);
2901
- const finalYamlConfig = stringify(yml);
2902
- return finalYamlConfig;
2903
- };
2904
-
2905
- // src/core/runners/runTestUnit.ts
2906
- var runTestUnit = async (options) => {
2907
- if (!options.skipBanner) {
2908
- console.log(pc22.bold(pc22.blue(`
2909
- ========================================`)));
2910
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2911
- console.log(pc22.bold(pc22.blue(`========================================
2912
- `)));
2913
- }
2914
- const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2915
- silenceWarnings: options.silenceWarnings
2916
- });
2917
- const parsed = parse(finalYamlConfig);
2918
- const projectName = parsed?.name || "test";
2919
- if (options.debug) {
2920
- console.log(
2921
- pc22.yellow("Final merged YAML configuration:\n"),
2922
- redactYamlSecrets(finalYamlConfig)
2923
- );
2924
- }
2925
- if (options.dryRun) {
2926
- console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2927
- return 0;
2928
- }
2929
- await teardownCompose(finalYamlConfig, options.projectDir, {
2930
- removeVolumes: true,
2931
- silent: true
2932
- });
2933
- writeRunState(options.projectDir, {
2934
- projectName,
2935
- stage: "test-unit",
2936
- projectDir: options.projectDir
2937
- });
2938
- let status = 0;
2939
- try {
2940
- status = await runCompose(
2941
- ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2942
- finalYamlConfig,
2943
- options.projectDir,
2944
- { removeVolumes: true }
2945
- );
2946
- } finally {
2947
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2948
- clearRunState(options.projectDir);
2949
- }
2950
- if (status === 0) {
2951
- console.log(pc22.bold(pc22.green(`
2952
- \u2705 Unit tests passed successfully.
2953
- `)));
2954
- } else {
2955
- console.error(pc22.red(`
2956
- \u274C Unit tests failed with exit code ${status}.
2957
- `));
2958
- }
2959
- return status;
2960
- };
2961
- var runTestE2e = async (options) => {
2962
- if (!options.skipBanner) {
2963
- console.log(pc22.bold(pc22.blue(`
2964
- ========================================`)));
2965
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2966
- console.log(pc22.bold(pc22.blue(`========================================
2967
- `)));
2968
- }
2969
- const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2970
- silenceWarnings: options.silenceWarnings
2971
- });
2972
- const parsed = parse(finalYamlConfig);
2973
- const projectName = parsed?.name || "e2e";
2974
- if (options.debug) {
2975
- console.log(
2976
- pc22.yellow("Final merged YAML configuration:\n"),
2977
- redactYamlSecrets(finalYamlConfig)
2978
- );
2979
- }
2980
- if (options.dryRun) {
2981
- console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2982
- return 0;
2983
- }
2984
- await teardownCompose(finalYamlConfig, options.projectDir, {
2985
- removeVolumes: true,
2986
- silent: true
2987
- });
2988
- writeRunState(options.projectDir, {
2989
- projectName,
2990
- stage: "test-e2e",
2991
- projectDir: options.projectDir
2992
- });
2993
- let status = 0;
2994
- try {
2995
- status = await runCompose(
2996
- [
2997
- "up",
2998
- "--build",
2999
- "--abort-on-container-exit",
3000
- "--exit-code-from",
3001
- "tester"
3002
- ],
3003
- finalYamlConfig,
3004
- options.projectDir,
3005
- { removeVolumes: true }
3006
- );
3007
- } finally {
3008
- await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
3009
- clearRunState(options.projectDir);
3010
- }
3011
- if (status === 0) {
3012
- console.log(pc22.bold(pc22.green(`
3013
- \u2705 E2E tests passed successfully.
3014
- `)));
3015
- } else {
3016
- console.error(pc22.red(`
3017
- \u274C E2E tests failed with exit code ${status}.
3018
- `));
3019
- }
3020
- return status;
3021
- };
3022
-
3023
- // src/core/runners/runTest.ts
3024
- var runTest = async (options) => {
3025
- console.log(pc22.bold(pc22.blue(`
3026
- ========================================`)));
3027
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
3028
- console.log(pc22.bold(pc22.blue(`========================================
3029
- `)));
3030
- const unitStatus = await runTestUnit({ ...options, skipBanner: true });
3031
- if (unitStatus !== 0) {
3032
- console.error(
3033
- pc22.red(
3034
- `
3035
- \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
3036
- `
3037
- )
3038
- );
3039
- return unitStatus;
3040
- }
3041
- console.log(
3042
- pc22.bold(pc22.green(`
3043
- \u2705 [1/2] Unit tests passed successfully.
3044
- `))
3045
- );
3046
- console.log(pc22.bold(pc22.blue(`========================================`)));
3047
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
3048
- console.log(pc22.bold(pc22.blue(`========================================
3049
- `)));
3050
- const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
3051
- if (e2eStatus !== 0) {
3052
- console.error(
3053
- pc22.red(`
3054
- \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
3055
- `)
3056
- );
3057
- return e2eStatus;
3058
- }
3059
- console.log(pc22.bold(pc22.green(`
3060
- \u2705 [2/2] E2E tests passed successfully.
3061
- `)));
3062
- console.log(
3063
- pc22.bold(
3064
- pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
3065
- `)
3066
- )
3067
- );
3068
- return 0;
3069
- };
3070
- async function runMeshTestE2e(options = {}) {
3071
- const meshDir = resolveProjectDir(options.projectDir);
3072
- console.log(pc22.bold(pc22.blue(`
3073
- ========================================`)));
3074
- console.log(pc22.bold(pc22.blue(`\u{1F6A6} [MESH] STAGE: GLOBAL INTEGRATED E2E TESTS`)));
3075
- console.log(pc22.bold(pc22.blue(`========================================
3076
- `)));
3077
- if (!options.skipChecks) {
3078
- checkMesh(meshDir, { requireTester: true });
3079
- }
3080
- const { yaml, testerServiceName } = compileMeshEnvironment("prod", meshDir, {
3081
- includeTester: true,
3082
- silenceWarnings: options.silenceWarnings
3083
- });
3084
- if (!testerServiceName) {
3085
- throw new ScriptError(
3086
- "No tester service could be identified in the tester docker compose configuration."
3087
- );
3088
- }
3089
- if (options.debug) {
3090
- console.log(
3091
- pc22.yellow("\nFinal merged Mesh E2E YAML configuration:\n"),
3092
- redactYamlSecrets(yaml)
3093
- );
3094
- }
3095
- if (options.dryRun) {
3096
- console.log(pc22.green("[DRY-RUN] Global E2E test simulated. Compose was not started."));
3097
- return 0;
3098
- }
3099
- const parsed = parse(yaml);
3100
- const projectName = parsed?.name || "mesh-e2e";
3101
- await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
3102
- writeRunState(meshDir, {
3103
- projectName,
3104
- stage: "test-e2e",
3105
- projectDir: meshDir
3106
- });
3107
- let status = 0;
3108
- try {
3109
- status = await runCompose(
3110
- [
3111
- "up",
3112
- "--build",
3113
- "--abort-on-container-exit",
3114
- "--exit-code-from",
3115
- testerServiceName
3116
- ],
3117
- yaml,
3118
- meshDir,
3119
- { removeVolumes: true }
3120
- );
3121
- } finally {
3122
- console.log(pc22.cyan("\n\u{1F9F9} Cleaning up global mesh containers and volumes..."));
3123
- await teardownCompose(yaml, meshDir, { removeVolumes: true });
3124
- clearRunState(meshDir);
3125
- }
3126
- if (status === 0) {
3127
- console.log(pc22.bold(pc22.green(`
3128
- \u2705 Global E2E tests passed successfully.
3129
- `)));
3130
- } else {
3131
- console.error(pc22.red(`
3132
- \u274C Global E2E tests failed with exit code ${status}.
3133
- `));
3134
- }
3135
- return status;
3136
- }
3137
-
3138
- // src/core/mesh/runners/runMeshTest.ts
3139
- async function runMeshTest(options = {}) {
3140
- const meshDir = resolveProjectDir(options.projectDir);
3141
- console.log(pc22.bold(pc22.blue(`
3142
- ========================================`)));
3143
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} GLOBAL MESH TEST PIPELINE`)));
3144
- console.log(pc22.bold(pc22.blue(`========================================
3145
- `)));
3146
- if (!options.skipChecks) {
3147
- checkMesh(meshDir, { requireTester: true });
3148
- }
3149
- const mesh = getMeshJson(meshDir);
3150
- console.log(pc22.bold(pc22.blue(`
3151
- ========================================`)));
3152
- console.log(
3153
- pc22.bold(
3154
- pc22.blue(`\u{1F9EA} [1/2] STAGE: LOCAL SUBMODULE TEST SUITES (Unit & Isolated E2E)`)
3155
- )
3156
- );
3157
- console.log(pc22.bold(pc22.blue(`========================================
3158
- `)));
3159
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
3160
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
3161
- console.log(
3162
- pc22.bold(pc22.cyan(`
3163
- -> Running full test suite for [${serviceName}] in isolation...`))
3164
- );
3165
- if (options.dryRun) {
3166
- console.log(
3167
- pc22.green(`[DRY-RUN] Full isolated tests for ${serviceName} simulated.`)
3168
- );
3169
- continue;
3170
- }
3171
- const serviceStatus = await runTest({
3172
- projectDir: serviceDir,
3173
- debug: Boolean(options.debug),
3174
- detach: Boolean(options.detach),
3175
- silenceWarnings: options.silenceWarnings
3176
- });
3177
- if (serviceStatus !== 0) {
3178
- console.error(
3179
- pc22.red(
3180
- `
3181
- \u274C Isolated tests failed for service [${serviceName}] with exit code ${serviceStatus}. Aborting global E2E tests.
3182
- `
3183
- )
3184
- );
3185
- return serviceStatus;
3186
- }
2187
+ console.log(pc22.cyan(`
2188
+ \u{1F3ED} Starting Global PROD Mesh Environment...`));
2189
+ const { yaml } = compileMeshEnvironment("prod", meshDir);
2190
+ const parsed = parse(yaml);
2191
+ const projectName = parsed?.name || "mesh-prod";
2192
+ if (options.debug) {
3187
2193
  console.log(
3188
- pc22.bold(pc22.green(`
3189
- \u2705 Isolated tests passed for service: [${serviceName}]
3190
- `))
2194
+ pc22.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2195
+ redactYamlSecrets(yaml)
3191
2196
  );
3192
2197
  }
3193
- console.log(pc22.bold(pc22.blue(`
3194
- ========================================`)));
3195
- console.log(
3196
- pc22.bold(
3197
- pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED PRODUCTION MESH & GLOBAL E2E ASSERTIONS`)
3198
- )
3199
- );
3200
- console.log(pc22.bold(pc22.blue(`========================================
3201
- `)));
3202
- const e2eStatus = await runMeshTestE2e({ ...options, skipChecks: true });
3203
- if (e2eStatus !== 0) {
3204
- return e2eStatus;
2198
+ if (options.dryRun) {
2199
+ console.log(pc22.green("Dry run complete. Compose was not started."));
2200
+ return 0;
3205
2201
  }
3206
- console.log(
3207
- pc22.bold(
3208
- pc22.green(`\u{1F389} Entire global mesh test pipeline (unit, local e2e, and global e2e) completed successfully!
3209
- `)
3210
- )
3211
- );
3212
- return 0;
2202
+ const hostPorts = extractHostPorts(yaml);
2203
+ await checkHostPortCollisions(hostPorts);
2204
+ writeRunState(meshDir, {
2205
+ projectName,
2206
+ stage: "prod",
2207
+ projectDir: meshDir
2208
+ });
2209
+ const upArgs = ["up", "--build"];
2210
+ if (options.detach) {
2211
+ upArgs.push("-d");
2212
+ }
2213
+ let status = 0;
2214
+ try {
2215
+ status = await runCompose(upArgs, yaml, meshDir, {
2216
+ removeVolumes: false
2217
+ });
2218
+ } finally {
2219
+ if (!options.detach) {
2220
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2221
+ clearRunState(meshDir);
2222
+ }
2223
+ }
2224
+ return status;
3213
2225
  }
3214
2226
  async function runMeshTestUnit(options = {}) {
3215
- const meshDir = resolveProjectDir(options.projectDir);
3216
- console.log(pc22.bold(pc22.blue(`
3217
- ========================================`)));
3218
- console.log(pc22.bold(pc22.blue(`\u{1F9EA} [MESH] STAGE: ISOLATED UNIT TESTS`)));
3219
- console.log(pc22.bold(pc22.blue(`========================================
3220
- `)));
3221
- if (!options.skipChecks) {
3222
- checkMesh(meshDir, { requireTester: false });
3223
- }
3224
- const mesh = getMeshJson(meshDir);
3225
- for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
3226
- const serviceDir = path13.resolve(meshDir, serviceConfig.path);
3227
- console.log(
3228
- pc22.cyan(`
3229
- -> Running isolated unit tests for service: [${serviceName}]...`)
3230
- );
2227
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path4.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
2228
+ console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2229
+ for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2230
+ console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
2231
+ const compiled = compileServiceComposition("test", svc.absolutePath, { meshMode: true, full: false, externalAppEnv: {}, deferReferenceResolution: true, appServiceName: "app" });
2232
+ const endpoints = { app: { [name]: compiled.endpoints.app }, dependencies: { [name]: compiled.endpoints.dependencies } };
2233
+ const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2234
+ const env = svc.meshEnv;
2235
+ 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" });
2236
+ const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2237
+ for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2238
+ const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2239
+ const app = compiled.compose.services.app;
2240
+ app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2241
+ const projectName = `${deriveProjectName(raw.name ?? path4.basename(meshDir), "dev")}-${name}-test`;
2242
+ compiled.compose.name = projectName;
2243
+ const yaml = stringify(compiled.compose);
2244
+ if (options.debug) console.log(yaml);
3231
2245
  if (options.dryRun) {
3232
- console.log(pc22.green(`[DRY-RUN] Unit tests for ${serviceName} simulated.`));
2246
+ console.log(pc22.green(`[DRY-RUN] Unit tests for ${name} compiled.`));
3233
2247
  continue;
3234
2248
  }
3235
- const unitStatus = await runTestUnit({
3236
- projectDir: serviceDir,
3237
- debug: Boolean(options.debug),
3238
- detach: Boolean(options.detach),
3239
- skipBanner: true
3240
- });
3241
- if (unitStatus !== 0) {
3242
- console.error(
3243
- pc22.red(`
3244
- \u274C Unit tests failed for service [${serviceName}] with exit code ${unitStatus}.
3245
- `)
3246
- );
3247
- return unitStatus;
2249
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true, silent: true });
2250
+ writeRunState(svc.absolutePath, { projectName, stage: "test-unit", projectDir: svc.absolutePath });
2251
+ let status;
2252
+ try {
2253
+ status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"], yaml, svc.absolutePath, { removeVolumes: true });
2254
+ } finally {
2255
+ await teardownCompose(yaml, svc.absolutePath, { removeVolumes: true });
2256
+ clearRunState(svc.absolutePath);
3248
2257
  }
3249
- console.log(
3250
- pc22.bold(pc22.green(`
3251
- \u2705 Isolated unit tests passed for service: [${serviceName}]
3252
- `))
3253
- );
2258
+ if (status !== 0) return status;
3254
2259
  }
3255
- console.log(
3256
- pc22.bold(pc22.green(`\u{1F389} All mesh service unit tests completed successfully!
3257
- `))
3258
- );
3259
2260
  return 0;
3260
2261
  }
2262
+ async function runMeshTestE2e(options = {}) {
2263
+ const meshDir = resolveProjectDir(options.projectDir), mesh = getMeshJson(meshDir);
2264
+ if (!options.skipChecks) checkMesh(meshDir, { requireTester: true });
2265
+ if (!mesh.tester) throw new ScriptError("Global mesh E2E requires root mesh.json.tester { compose, service, env? }");
2266
+ const { yaml, testerServiceName } = compileMeshEnvironment("e2e", meshDir);
2267
+ if (!testerServiceName) throw new ScriptError("Global mesh E2E tester runner could not be compiled.");
2268
+ if (options.debug) console.log(pc22.yellow("\nFinal global mesh E2E YAML configuration:\n"), redactYamlSecrets(yaml));
2269
+ if (options.dryRun) {
2270
+ console.log(pc22.green("[DRY-RUN] Global mesh E2E compiled; Compose was not started."));
2271
+ return 0;
2272
+ }
2273
+ await checkHostPortCollisions(extractHostPorts(yaml));
2274
+ const projectName = parse(yaml)?.name || "mesh-e2e";
2275
+ await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2276
+ writeRunState(meshDir, { projectName, stage: "test-e2e", projectDir: meshDir });
2277
+ let status = 0;
2278
+ try {
2279
+ status = await runCompose(["up", "--build", "--abort-on-container-exit", "--exit-code-from", testerServiceName], yaml, meshDir, { removeVolumes: true });
2280
+ } finally {
2281
+ await teardownCompose(yaml, meshDir, { removeVolumes: true });
2282
+ clearRunState(meshDir);
2283
+ }
2284
+ return status;
2285
+ }
2286
+
2287
+ // src/core/mesh/runners/runMeshTest.ts
2288
+ async function runMeshTest(options = {}) {
2289
+ console.log(pc22.bold(pc22.blue("\n========================================\nMESH TEST PIPELINE\n========================================\n")));
2290
+ console.log(pc22.bold(pc22.blue("[1/2] MESH SERVICE UNIT/ISOLATED TESTS")));
2291
+ const unitStatus = await runMeshTestUnit(options);
2292
+ if (unitStatus !== 0) return unitStatus;
2293
+ console.log(pc22.bold(pc22.blue("[2/2] GLOBAL MESH E2E")));
2294
+ return runMeshTestE2e(options);
2295
+ }
3261
2296
 
3262
2297
  // src/commands/mesh/commands/up/handler.ts
3263
2298
  async function handleMeshUp(rawStage = "dev", options = {}) {
@@ -3309,7 +2344,10 @@ Examples:
3309
2344
  $ builder mesh up prod
3310
2345
  $ builder mesh up test
3311
2346
  $ builder mesh up test-unit
3312
- $ builder mesh up test-e2e`
2347
+ $ builder mesh up test-e2e
2348
+
2349
+ JSON overlays: test-unit uses mesh/build test; test-e2e uses mesh/build e2e.
2350
+ The test command runs per-service unit tests before global E2E.`
3313
2351
  ).action(
3314
2352
  async (stage = "dev", options = {}) => {
3315
2353
  const exitCode = await handleMeshUp(stage, {
@@ -3317,8 +2355,7 @@ Examples:
3317
2355
  debug: options.debug,
3318
2356
  detach: options.detach,
3319
2357
  dryRun: options.dryRun,
3320
- skipChecks: options.skipChecks,
3321
- silenceWarnings: options.silenceWarnings
2358
+ skipChecks: options.skipChecks
3322
2359
  });
3323
2360
  if (exitCode !== 0) {
3324
2361
  process.exit(exitCode);
@@ -3379,6 +2416,9 @@ var registerPruneCommand = (cmd) => {
3379
2416
  }
3380
2417
  });
3381
2418
  };
2419
+ var compileEnvironment = (stage, projectDir = process.cwd(), options = {}) => stringify(compileServiceComposition(stage, projectDir, { full: Boolean(options.full), silenceWarnings: options.silenceWarnings }).compose);
2420
+
2421
+ // src/commands/service/commands/down/handler.ts
3382
2422
  async function handleServiceDown(rawStage = "dev", options = {}) {
3383
2423
  const projectDir = resolveProjectDir(options.projectDir);
3384
2424
  const stage = (rawStage || "dev").toLowerCase();
@@ -3548,12 +2588,178 @@ var runProd = async (options) => {
3548
2588
  }
3549
2589
  return status;
3550
2590
  };
2591
+ var runTestUnit = async (options) => {
2592
+ if (!options.skipBanner) {
2593
+ console.log(pc22.bold(pc22.blue(`
2594
+ ========================================`)));
2595
+ console.log(pc22.bold(pc22.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2596
+ console.log(pc22.bold(pc22.blue(`========================================
2597
+ `)));
2598
+ }
2599
+ const finalYamlConfig = compileEnvironment("test", options.projectDir, {
2600
+ silenceWarnings: options.silenceWarnings
2601
+ });
2602
+ const parsed = parse(finalYamlConfig);
2603
+ const projectName = parsed?.name || "test";
2604
+ if (options.debug) {
2605
+ console.log(
2606
+ pc22.yellow("Final merged YAML configuration:\n"),
2607
+ redactYamlSecrets(finalYamlConfig)
2608
+ );
2609
+ }
2610
+ if (options.dryRun) {
2611
+ console.log(pc22.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2612
+ return 0;
2613
+ }
2614
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2615
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2616
+ removeVolumes: true,
2617
+ silent: true
2618
+ });
2619
+ writeRunState(options.projectDir, {
2620
+ projectName,
2621
+ stage: "test-unit",
2622
+ projectDir: options.projectDir
2623
+ });
2624
+ let status = 0;
2625
+ try {
2626
+ status = await runCompose(
2627
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2628
+ finalYamlConfig,
2629
+ options.projectDir,
2630
+ { removeVolumes: true }
2631
+ );
2632
+ } finally {
2633
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2634
+ clearRunState(options.projectDir);
2635
+ }
2636
+ if (status === 0) {
2637
+ console.log(pc22.bold(pc22.green(`
2638
+ \u2705 Unit tests passed successfully.
2639
+ `)));
2640
+ } else {
2641
+ console.error(pc22.red(`
2642
+ \u274C Unit tests failed with exit code ${status}.
2643
+ `));
2644
+ }
2645
+ return status;
2646
+ };
2647
+ var runTestE2e = async (options) => {
2648
+ if (!options.skipBanner) {
2649
+ console.log(pc22.bold(pc22.blue(`
2650
+ ========================================`)));
2651
+ console.log(pc22.bold(pc22.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2652
+ console.log(pc22.bold(pc22.blue(`========================================
2653
+ `)));
2654
+ }
2655
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir, {
2656
+ silenceWarnings: options.silenceWarnings
2657
+ });
2658
+ const parsed = parse(finalYamlConfig);
2659
+ const projectName = parsed?.name || "e2e";
2660
+ if (options.debug) {
2661
+ console.log(
2662
+ pc22.yellow("Final merged YAML configuration:\n"),
2663
+ redactYamlSecrets(finalYamlConfig)
2664
+ );
2665
+ }
2666
+ if (options.dryRun) {
2667
+ console.log(pc22.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2668
+ return 0;
2669
+ }
2670
+ await checkHostPortCollisions(extractHostPorts(finalYamlConfig));
2671
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2672
+ removeVolumes: true,
2673
+ silent: true
2674
+ });
2675
+ writeRunState(options.projectDir, {
2676
+ projectName,
2677
+ stage: "test-e2e",
2678
+ projectDir: options.projectDir
2679
+ });
2680
+ let status = 0;
2681
+ try {
2682
+ status = await runCompose(
2683
+ [
2684
+ "up",
2685
+ "--build",
2686
+ "--abort-on-container-exit",
2687
+ "--exit-code-from",
2688
+ "tester"
2689
+ ],
2690
+ finalYamlConfig,
2691
+ options.projectDir,
2692
+ { removeVolumes: true }
2693
+ );
2694
+ } finally {
2695
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2696
+ clearRunState(options.projectDir);
2697
+ }
2698
+ if (status === 0) {
2699
+ console.log(pc22.bold(pc22.green(`
2700
+ \u2705 E2E tests passed successfully.
2701
+ `)));
2702
+ } else {
2703
+ console.error(pc22.red(`
2704
+ \u274C E2E tests failed with exit code ${status}.
2705
+ `));
2706
+ }
2707
+ return status;
2708
+ };
2709
+
2710
+ // src/core/runners/runTest.ts
2711
+ var runTest = async (options) => {
2712
+ console.log(pc22.bold(pc22.blue(`
2713
+ ========================================`)));
2714
+ console.log(pc22.bold(pc22.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
2715
+ console.log(pc22.bold(pc22.blue(`========================================
2716
+ `)));
2717
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
2718
+ if (unitStatus !== 0) {
2719
+ console.error(
2720
+ pc22.red(
2721
+ `
2722
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
2723
+ `
2724
+ )
2725
+ );
2726
+ return unitStatus;
2727
+ }
2728
+ console.log(
2729
+ pc22.bold(pc22.green(`
2730
+ \u2705 [1/2] Unit tests passed successfully.
2731
+ `))
2732
+ );
2733
+ console.log(pc22.bold(pc22.blue(`========================================`)));
2734
+ console.log(pc22.bold(pc22.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
2735
+ console.log(pc22.bold(pc22.blue(`========================================
2736
+ `)));
2737
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
2738
+ if (e2eStatus !== 0) {
2739
+ console.error(
2740
+ pc22.red(`
2741
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
2742
+ `)
2743
+ );
2744
+ return e2eStatus;
2745
+ }
2746
+ console.log(pc22.bold(pc22.green(`
2747
+ \u2705 [2/2] E2E tests passed successfully.
2748
+ `)));
2749
+ console.log(
2750
+ pc22.bold(
2751
+ pc22.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
2752
+ `)
2753
+ )
2754
+ );
2755
+ return 0;
2756
+ };
3551
2757
 
3552
2758
  // src/commands/service/commands/up/handler.ts
3553
2759
  async function handleServiceUp(rawStage, options = {}) {
3554
2760
  const projectDir = resolveProjectDir(options.projectDir);
3555
2761
  const stage = (rawStage || "dev").toLowerCase();
3556
- const isFull = Boolean(options.full || options.integrated);
2762
+ const isFull = Boolean(options.full);
3557
2763
  const runOptions = {
3558
2764
  projectDir,
3559
2765
  debug: Boolean(options.debug),
@@ -3597,10 +2803,7 @@ var registerUpCommand = (cmd) => {
3597
2803
  "Silence non-critical warnings like URL templating hints"
3598
2804
  ).option(
3599
2805
  "--full",
3600
- "Run dev environment with mock dependencies and integrated infra mode"
3601
- ).option(
3602
- "--integrated",
3603
- "Alias for --full"
2806
+ "Run dev with all declared local dependencies integrated"
3604
2807
  ).option(
3605
2808
  "-C, --project-dir <dir>",
3606
2809
  "Service project directory (defaults to cwd)"
@@ -3613,7 +2816,10 @@ Examples:
3613
2816
  $ builder service up prod
3614
2817
  $ builder service up test
3615
2818
  $ builder service up test-unit
3616
- $ builder service up test-e2e`
2819
+ $ builder service up test-e2e
2820
+
2821
+ JSON overlays: test-unit uses build.json test; test-e2e uses build.json e2e.
2822
+ The test command runs unit tests before E2E.`
3617
2823
  ).action(
3618
2824
  async (stage = "dev", options = {}) => {
3619
2825
  const exitCode = await handleServiceUp(stage, {
@@ -3623,7 +2829,7 @@ Examples:
3623
2829
  dryRun: options.dryRun,
3624
2830
  skipChecks: options.skipChecks,
3625
2831
  silenceWarnings: options.silenceWarnings,
3626
- full: Boolean(options.full || options.integrated)
2832
+ full: Boolean(options.full)
3627
2833
  });
3628
2834
  if (exitCode !== 0) {
3629
2835
  process.exit(exitCode);
@@ -3696,7 +2902,7 @@ async function handleExportEnv(rawStage, options = {}) {
3696
2902
  const files = [];
3697
2903
  try {
3698
2904
  for (const snapshot of snapshots) {
3699
- let filename = path13.join(projectDir, `.env.${snapshot.stage}`);
2905
+ let filename = path4.join(projectDir, `.env.${snapshot.stage}`);
3700
2906
  while (true) {
3701
2907
  let overwrite = false;
3702
2908
  if (existsSync(filename)) {
@@ -3705,11 +2911,11 @@ async function handleExportEnv(rawStage, options = {}) {
3705
2911
  if (!overwrite) {
3706
2912
  const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3707
2913
  if (!name) continue;
3708
- filename = path13.resolve(projectDir, name);
2914
+ filename = path4.resolve(projectDir, name);
3709
2915
  continue;
3710
2916
  }
3711
2917
  }
3712
- mkdirSync(path13.dirname(filename), { recursive: true });
2918
+ mkdirSync(path4.dirname(filename), { recursive: true });
3713
2919
  try {
3714
2920
  writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
3715
2921
  } catch (error) {
@@ -3730,7 +2936,7 @@ async function handleExportEnv(rawStage, options = {}) {
3730
2936
  // src/commands/service/commands/export/command.ts
3731
2937
  function registerExportCommand(service) {
3732
2938
  const command = service.command("export").description("Export service configuration");
3733
- command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--integrated", "Alias for --full").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
2939
+ command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
3734
2940
  Examples:
3735
2941
  $ builder service export env
3736
2942
  $ builder service export env dev
@@ -3738,7 +2944,7 @@ Examples:
3738
2944
  $ builder service export env dev --full`).action(async (stage, options) => {
3739
2945
  await handleExportEnv(stage, {
3740
2946
  projectDir: options.projectDir,
3741
- full: Boolean(options.full || options.integrated),
2947
+ full: Boolean(options.full),
3742
2948
  silenceWarnings: options.silenceWarnings
3743
2949
  });
3744
2950
  });
@@ -3841,43 +3047,7 @@ ${formatted}
3841
3047
  process.exit(exitCode);
3842
3048
  }
3843
3049
  }
3844
- var buildPolicyConfigSchema = z.object({
3845
- dockerfile: z.string().optional().describe("Relative path to policy directory for Dockerfile checks"),
3846
- compose: z.string().optional().describe("Relative path to policy directory for Compose contract checks")
3847
- }).strict().describe("Policy configurations for infra/contract verification");
3848
- var buildDependencySchema = z.object({
3849
- path: z.string({ required_error: 'Dependency "path" is required' }).describe("Relative path to mock Docker Compose file"),
3850
- service: z.string().optional().describe("Target service name in the mock compose file"),
3851
- port: z.union([z.number(), z.string()]).optional().describe("Host port to map to this dependency locally")
3852
- }).strict().describe("Service dependency specification");
3853
- var buildOverrideSchema = z.object({
3854
- path: z.string({ required_error: 'Override "path" is required' }).describe("Relative path to the environment stage override file")
3855
- }).strict().describe("Environment override specification");
3856
- var buildTesterSchema = z.object({
3857
- envOverrides: z.record(z.string(), z.string()).optional().describe(
3858
- "Environment variable overrides for the individual E2E tester with URL templating"
3859
- )
3860
- }).strict().describe("E2E tester configuration");
3861
- var buildJsonSchema = z.object({
3862
- $schema: z.string().optional().describe("JSON Schema URL or relative path"),
3863
- name: z.string().optional().describe("Service project name"),
3864
- dockerfile: z.string().optional().describe("Relative path to the Dockerfile (defaults to 'Dockerfile')"),
3865
- port: z.union([z.number(), z.string()]).optional().describe(
3866
- "Host port exposed by this service when listening publicly"
3867
- ),
3868
- policy: buildPolicyConfigSchema.optional(),
3869
- policies: buildPolicyConfigSchema.optional(),
3870
- composeFiles: z.array(z.string()).optional().describe("Additional compose files to merge"),
3871
- dependencies: z.record(z.string(), buildDependencySchema).optional().describe("Service dependencies and mocks"),
3872
- envOverrides: z.record(z.string(), z.string()).optional().describe("Environment variable overrides for the app service with URL templating"),
3873
- overrides: z.record(
3874
- z.enum(["dev", "prod", "test", "e2e"]),
3875
- buildOverrideSchema
3876
- ).optional().describe("Stage overrides (dev, prod, test, e2e)"),
3877
- services: z.record(z.string(), z.any()).optional().describe("Additional Docker Compose service overrides"),
3878
- tester: buildTesterSchema.optional()
3879
- }).strict().describe("Solid Stack service build and deployment configuration");
3880
-
3881
- export { NotFoundError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3050
+
3051
+ export { ConfigError, NotFoundError, PortConflictError, SERVICE_STAGES, ScriptError, buildJsonSchema, compileApplicationEnv, compileEnvironment, compileMeshEnvironment, createCli, meshSchema, runCli, runCompose, serializeApplicationEnv, teardownCompose, version };
3882
3052
  //# sourceMappingURL=index.js.map
3883
3053
  //# sourceMappingURL=index.js.map