@solid-stack/builder 1.0.6 → 1.0.7

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 (257) hide show
  1. package/dist/bin.js +3430 -3
  2. package/dist/bin.js.map +1 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/commands/check/handler.d.ts.map +1 -1
  5. package/dist/commands/mesh/command.d.ts.map +1 -1
  6. package/dist/commands/mesh/commands/check/handler.d.ts +2 -2
  7. package/dist/commands/mesh/commands/check/handler.d.ts.map +1 -1
  8. package/dist/commands/mesh/commands/down/command.d.ts +3 -0
  9. package/dist/commands/mesh/commands/down/command.d.ts.map +1 -0
  10. package/dist/commands/mesh/commands/down/handler.d.ts +3 -0
  11. package/dist/commands/mesh/commands/down/handler.d.ts.map +1 -0
  12. package/dist/commands/mesh/commands/up/command.d.ts.map +1 -1
  13. package/dist/commands/mesh/commands/up/handler.d.ts.map +1 -1
  14. package/dist/commands/prune/command.d.ts +3 -0
  15. package/dist/commands/prune/command.d.ts.map +1 -0
  16. package/dist/commands/prune/handler.d.ts +5 -0
  17. package/dist/commands/prune/handler.d.ts.map +1 -0
  18. package/dist/commands/service/command.d.ts.map +1 -1
  19. package/dist/commands/service/commands/down/command.d.ts +3 -0
  20. package/dist/commands/service/commands/down/command.d.ts.map +1 -0
  21. package/dist/commands/service/commands/down/handler.d.ts +3 -0
  22. package/dist/commands/service/commands/down/handler.d.ts.map +1 -0
  23. package/dist/commands/service/commands/up/command.d.ts.map +1 -1
  24. package/dist/commands/service/commands/up/handler.d.ts +1 -1
  25. package/dist/commands/service/commands/up/handler.d.ts.map +1 -1
  26. package/dist/core/RunOptions.d.ts +2 -0
  27. package/dist/core/RunOptions.d.ts.map +1 -1
  28. package/dist/core/checkers/checkComposeContract.d.ts.map +1 -1
  29. package/dist/core/checkers/checkDockerfile.d.ts.map +1 -1
  30. package/dist/core/checkers/checkDockerfileContract.d.ts.map +1 -1
  31. package/dist/core/checkers/checkInfra.d.ts.map +1 -1
  32. package/dist/core/checkers/checkYamlFiles.d.ts.map +1 -1
  33. package/dist/core/checkers/constants.d.ts +3 -0
  34. package/dist/core/checkers/constants.d.ts.map +1 -0
  35. package/dist/core/checkers/explainComposeMergeFailure.d.ts.map +1 -1
  36. package/dist/core/checkers/runStep.d.ts +2 -1
  37. package/dist/core/checkers/runStep.d.ts.map +1 -1
  38. package/dist/core/compileEnvironment.d.ts.map +1 -1
  39. package/dist/core/composeCleanup.d.ts +9 -0
  40. package/dist/core/composeCleanup.d.ts.map +1 -0
  41. package/dist/core/mesh/MeshRunOptions.d.ts +10 -4
  42. package/dist/core/mesh/MeshRunOptions.d.ts.map +1 -1
  43. package/dist/core/mesh/checkers/checkMesh.d.ts +1 -1
  44. package/dist/core/mesh/checkers/checkMesh.d.ts.map +1 -1
  45. package/dist/core/mesh/checkers/checkMeshJson.d.ts.map +1 -1
  46. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  47. package/dist/core/mesh/checkers/checkMeshTester.d.ts.map +1 -1
  48. package/dist/core/mesh/compileMeshEnvironment.d.ts +2 -2
  49. package/dist/core/mesh/compileMeshEnvironment.d.ts.map +1 -1
  50. package/dist/core/mesh/getMeshJson.d.ts.map +1 -1
  51. package/dist/core/mesh/meshSchema.d.ts +353 -0
  52. package/dist/core/mesh/meshSchema.d.ts.map +1 -0
  53. package/dist/core/mesh/runners/runMeshDev.d.ts +1 -1
  54. package/dist/core/mesh/runners/runMeshDev.d.ts.map +1 -1
  55. package/dist/core/mesh/runners/runMeshProd.d.ts +1 -1
  56. package/dist/core/mesh/runners/runMeshProd.d.ts.map +1 -1
  57. package/dist/core/mesh/runners/runMeshTest.d.ts +1 -1
  58. package/dist/core/mesh/runners/runMeshTest.d.ts.map +1 -1
  59. package/dist/core/mesh/runners/runMeshTestE2e.d.ts +1 -1
  60. package/dist/core/mesh/runners/runMeshTestE2e.d.ts.map +1 -1
  61. package/dist/core/mesh/runners/runMeshTestUnit.d.ts +1 -1
  62. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  63. package/dist/core/mesh/types.d.ts +32 -18
  64. package/dist/core/mesh/types.d.ts.map +1 -1
  65. package/dist/core/runCompose.d.ts +4 -1
  66. package/dist/core/runCompose.d.ts.map +1 -1
  67. package/dist/core/runners/runDev.d.ts +1 -1
  68. package/dist/core/runners/runDev.d.ts.map +1 -1
  69. package/dist/core/runners/runProd.d.ts +1 -1
  70. package/dist/core/runners/runProd.d.ts.map +1 -1
  71. package/dist/core/runners/runTest.d.ts +1 -1
  72. package/dist/core/runners/runTest.d.ts.map +1 -1
  73. package/dist/core/runners/runTestE2e.d.ts +1 -1
  74. package/dist/core/runners/runTestE2e.d.ts.map +1 -1
  75. package/dist/core/runners/runTestUnit.d.ts +1 -1
  76. package/dist/core/runners/runTestUnit.d.ts.map +1 -1
  77. package/dist/core/teardownCompose.d.ts +6 -1
  78. package/dist/core/teardownCompose.d.ts.map +1 -1
  79. package/dist/core/templates.d.ts.map +1 -1
  80. package/dist/errors/NotFoundError.d.ts +2 -2
  81. package/dist/errors/NotFoundError.d.ts.map +1 -1
  82. package/dist/errors/ScriptError.d.ts +6 -1
  83. package/dist/errors/ScriptError.d.ts.map +1 -1
  84. package/dist/index.d.ts +10 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +3429 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/templates/docker/docker-compose.dev.yml +4 -1
  89. package/dist/templates/docker/docker-compose.e2e.yml +3 -1
  90. package/dist/templates/docker/docker-compose.prod.yml +3 -1
  91. package/dist/templates/docker/docker-compose.standalone.yml +2 -1
  92. package/dist/templates/docker/docker-compose.test.yml +3 -1
  93. package/dist/types/index.d.ts +26 -10
  94. package/dist/types/index.d.ts.map +1 -1
  95. package/dist/utils/checkDependencies.d.ts.map +1 -1
  96. package/dist/utils/checkPortCollision.d.ts +4 -0
  97. package/dist/utils/checkPortCollision.d.ts.map +1 -0
  98. package/dist/utils/errorMessage.d.ts +2 -0
  99. package/dist/utils/errorMessage.d.ts.map +1 -0
  100. package/dist/utils/extractBuildDeps.d.ts.map +1 -1
  101. package/dist/utils/extractOverrides.d.ts.map +1 -1
  102. package/dist/utils/getBuildJson.d.ts.map +1 -1
  103. package/dist/utils/paths.d.ts +20 -0
  104. package/dist/utils/paths.d.ts.map +1 -0
  105. package/dist/utils/projectName.d.ts +20 -0
  106. package/dist/utils/projectName.d.ts.map +1 -0
  107. package/dist/utils/redactSecrets.d.ts +6 -0
  108. package/dist/utils/redactSecrets.d.ts.map +1 -0
  109. package/dist/utils/runState.d.ts +13 -0
  110. package/dist/utils/runState.d.ts.map +1 -0
  111. package/dist/utils/ymlMods/addDependenciesToAppService.d.ts.map +1 -1
  112. package/dist/utils/ymlMods/attachName.d.ts +3 -1
  113. package/dist/utils/ymlMods/attachName.d.ts.map +1 -1
  114. package/dist/utils/ymlMods/makeE2eDependOnApp.d.ts.map +1 -1
  115. package/dist/utils/ymlMods/normalizeDependsOn.d.ts +6 -0
  116. package/dist/utils/ymlMods/normalizeDependsOn.d.ts.map +1 -0
  117. package/dist/utils/ymlMods/renameServicesWithDependencies.d.ts.map +1 -1
  118. package/package.json +12 -6
  119. package/templates/docker/docker-compose.dev.yml +4 -1
  120. package/templates/docker/docker-compose.e2e.yml +3 -1
  121. package/templates/docker/docker-compose.prod.yml +3 -1
  122. package/templates/docker/docker-compose.standalone.yml +2 -1
  123. package/templates/docker/docker-compose.test.yml +3 -1
  124. package/dist/bin.cjs +0 -802
  125. package/dist/bin.cjs.map +0 -1
  126. package/dist/cli.js +0 -45
  127. package/dist/cli.js.map +0 -1
  128. package/dist/commands/check/command.js +0 -19
  129. package/dist/commands/check/command.js.map +0 -1
  130. package/dist/commands/check/handler.js +0 -7
  131. package/dist/commands/check/handler.js.map +0 -1
  132. package/dist/commands/checkInfra.d.ts +0 -8
  133. package/dist/commands/checkInfra.d.ts.map +0 -1
  134. package/dist/commands/checkInfra.js +0 -8
  135. package/dist/commands/checkInfra.js.map +0 -1
  136. package/dist/commands/mesh/command.js +0 -10
  137. package/dist/commands/mesh/command.js.map +0 -1
  138. package/dist/commands/mesh/commands/check/command.js +0 -21
  139. package/dist/commands/mesh/commands/check/command.js.map +0 -1
  140. package/dist/commands/mesh/commands/check/handler.js +0 -10
  141. package/dist/commands/mesh/commands/check/handler.js.map +0 -1
  142. package/dist/commands/mesh/commands/up/command.js +0 -28
  143. package/dist/commands/mesh/commands/up/command.js.map +0 -1
  144. package/dist/commands/mesh/commands/up/handler.js +0 -24
  145. package/dist/commands/mesh/commands/up/handler.js.map +0 -1
  146. package/dist/commands/service/command.js +0 -17
  147. package/dist/commands/service/command.js.map +0 -1
  148. package/dist/commands/service/commands/up/command.js +0 -26
  149. package/dist/commands/service/commands/up/command.js.map +0 -1
  150. package/dist/commands/service/commands/up/handler.js +0 -40
  151. package/dist/commands/service/commands/up/handler.js.map +0 -1
  152. package/dist/commands/service/commands/up/serviceUp.d.ts +0 -3
  153. package/dist/commands/service/commands/up/serviceUp.d.ts.map +0 -1
  154. package/dist/commands/service/commands/up/serviceUp.js +0 -62
  155. package/dist/commands/service/commands/up/serviceUp.js.map +0 -1
  156. package/dist/core/RunOptions.js +0 -2
  157. package/dist/core/RunOptions.js.map +0 -1
  158. package/dist/core/checkers/checkComposeContract.js +0 -29
  159. package/dist/core/checkers/checkComposeContract.js.map +0 -1
  160. package/dist/core/checkers/checkDockerfile.js +0 -19
  161. package/dist/core/checkers/checkDockerfile.js.map +0 -1
  162. package/dist/core/checkers/checkDockerfileContract.js +0 -18
  163. package/dist/core/checkers/checkDockerfileContract.js.map +0 -1
  164. package/dist/core/checkers/checkInfra.js +0 -16
  165. package/dist/core/checkers/checkInfra.js.map +0 -1
  166. package/dist/core/checkers/checkYamlFiles.js +0 -31
  167. package/dist/core/checkers/checkYamlFiles.js.map +0 -1
  168. package/dist/core/checkers/explainComposeMergeFailure.js +0 -63
  169. package/dist/core/checkers/explainComposeMergeFailure.js.map +0 -1
  170. package/dist/core/checkers/getDeclaredYamlFiles.js +0 -39
  171. package/dist/core/checkers/getDeclaredYamlFiles.js.map +0 -1
  172. package/dist/core/checkers/runStep.js +0 -32
  173. package/dist/core/checkers/runStep.js.map +0 -1
  174. package/dist/core/compileEnvironment.js +0 -110
  175. package/dist/core/compileEnvironment.js.map +0 -1
  176. package/dist/core/mesh/MeshRunOptions.js +0 -2
  177. package/dist/core/mesh/MeshRunOptions.js.map +0 -1
  178. package/dist/core/mesh/checkers/checkMesh.js +0 -15
  179. package/dist/core/mesh/checkers/checkMesh.js.map +0 -1
  180. package/dist/core/mesh/checkers/checkMeshJson.js +0 -19
  181. package/dist/core/mesh/checkers/checkMeshJson.js.map +0 -1
  182. package/dist/core/mesh/checkers/checkMeshServices.js +0 -29
  183. package/dist/core/mesh/checkers/checkMeshServices.js.map +0 -1
  184. package/dist/core/mesh/checkers/checkMeshTester.js +0 -59
  185. package/dist/core/mesh/checkers/checkMeshTester.js.map +0 -1
  186. package/dist/core/mesh/compileMeshEnvironment.js +0 -329
  187. package/dist/core/mesh/compileMeshEnvironment.js.map +0 -1
  188. package/dist/core/mesh/getMeshJson.js +0 -36
  189. package/dist/core/mesh/getMeshJson.js.map +0 -1
  190. package/dist/core/mesh/runners/runMeshDev.js +0 -25
  191. package/dist/core/mesh/runners/runMeshDev.js.map +0 -1
  192. package/dist/core/mesh/runners/runMeshProd.js +0 -25
  193. package/dist/core/mesh/runners/runMeshProd.js.map +0 -1
  194. package/dist/core/mesh/runners/runMeshTest.js +0 -48
  195. package/dist/core/mesh/runners/runMeshTest.js.map +0 -1
  196. package/dist/core/mesh/runners/runMeshTestE2e.js +0 -49
  197. package/dist/core/mesh/runners/runMeshTestE2e.js.map +0 -1
  198. package/dist/core/mesh/runners/runMeshTestUnit.js +0 -34
  199. package/dist/core/mesh/runners/runMeshTestUnit.js.map +0 -1
  200. package/dist/core/mesh/types.js +0 -2
  201. package/dist/core/mesh/types.js.map +0 -1
  202. package/dist/core/runCompose.js +0 -15
  203. package/dist/core/runCompose.js.map +0 -1
  204. package/dist/core/runDev.d.ts +0 -3
  205. package/dist/core/runDev.d.ts.map +0 -1
  206. package/dist/core/runDev.js +0 -17
  207. package/dist/core/runDev.js.map +0 -1
  208. package/dist/core/runProd.d.ts +0 -3
  209. package/dist/core/runProd.d.ts.map +0 -1
  210. package/dist/core/runProd.js +0 -17
  211. package/dist/core/runProd.js.map +0 -1
  212. package/dist/core/runTestE2e.d.ts +0 -3
  213. package/dist/core/runTestE2e.d.ts.map +0 -1
  214. package/dist/core/runTestE2e.js +0 -34
  215. package/dist/core/runTestE2e.js.map +0 -1
  216. package/dist/core/runTestUnit.d.ts +0 -3
  217. package/dist/core/runTestUnit.d.ts.map +0 -1
  218. package/dist/core/runTestUnit.js +0 -28
  219. package/dist/core/runTestUnit.js.map +0 -1
  220. package/dist/core/runners/runDev.js +0 -17
  221. package/dist/core/runners/runDev.js.map +0 -1
  222. package/dist/core/runners/runProd.js +0 -17
  223. package/dist/core/runners/runProd.js.map +0 -1
  224. package/dist/core/runners/runTest.js +0 -28
  225. package/dist/core/runners/runTest.js.map +0 -1
  226. package/dist/core/runners/runTestE2e.js +0 -34
  227. package/dist/core/runners/runTestE2e.js.map +0 -1
  228. package/dist/core/runners/runTestUnit.js +0 -28
  229. package/dist/core/runners/runTestUnit.js.map +0 -1
  230. package/dist/core/teardownCompose.js +0 -23
  231. package/dist/core/teardownCompose.js.map +0 -1
  232. package/dist/core/templates.js +0 -40
  233. package/dist/core/templates.js.map +0 -1
  234. package/dist/errors/NotFoundError.js +0 -9
  235. package/dist/errors/NotFoundError.js.map +0 -1
  236. package/dist/errors/ScriptError.js +0 -8
  237. package/dist/errors/ScriptError.js.map +0 -1
  238. package/dist/types/index.js +0 -2
  239. package/dist/types/index.js.map +0 -1
  240. package/dist/utils/checkDependencies.js +0 -9
  241. package/dist/utils/checkDependencies.js.map +0 -1
  242. package/dist/utils/extractBuildDeps.js +0 -32
  243. package/dist/utils/extractBuildDeps.js.map +0 -1
  244. package/dist/utils/extractOverrides.js +0 -28
  245. package/dist/utils/extractOverrides.js.map +0 -1
  246. package/dist/utils/getBuildJson.js +0 -39
  247. package/dist/utils/getBuildJson.js.map +0 -1
  248. package/dist/utils/ymlMods/addDependenciesToAppService.js +0 -16
  249. package/dist/utils/ymlMods/addDependenciesToAppService.js.map +0 -1
  250. package/dist/utils/ymlMods/attachName.js +0 -8
  251. package/dist/utils/ymlMods/attachName.js.map +0 -1
  252. package/dist/utils/ymlMods/makeE2eDependOnApp.js +0 -19
  253. package/dist/utils/ymlMods/makeE2eDependOnApp.js.map +0 -1
  254. package/dist/utils/ymlMods/renameServicesWithDependencies.js +0 -13
  255. package/dist/utils/ymlMods/renameServicesWithDependencies.js.map +0 -1
  256. package/dist/version.js +0 -12
  257. package/dist/version.js.map +0 -1
package/dist/index.js ADDED
@@ -0,0 +1,3429 @@
1
+ import { Command } from 'commander';
2
+ import pc20 from 'picocolors';
3
+ import fs, { existsSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, statSync } from 'fs';
4
+ import path13 from 'path';
5
+ import { spawnSync, spawn } from 'child_process';
6
+ import { parse, stringify, parseAllDocuments } from 'yaml';
7
+ import { z } from 'zod';
8
+ import 'crypto';
9
+ import os from 'os';
10
+ import net from 'net';
11
+ import { fileURLToPath } from 'url';
12
+ import { createRequire } from 'module';
13
+
14
+ // src/types/index.ts
15
+ var SERVICE_STAGES = [
16
+ "dev",
17
+ "prod",
18
+ "test",
19
+ "test-unit",
20
+ "test-e2e"
21
+ ];
22
+
23
+ // src/errors/ScriptError.ts
24
+ var ScriptError = class extends Error {
25
+ exitCode;
26
+ constructor(message, options) {
27
+ super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
28
+ this.name = "ScriptError";
29
+ this.exitCode = options?.exitCode ?? 1;
30
+ }
31
+ };
32
+
33
+ // src/errors/NotFoundError.ts
34
+ var NotFoundError = class extends ScriptError {
35
+ constructor(message, options) {
36
+ super(message, options);
37
+ this.name = "NotFoundError";
38
+ }
39
+ };
40
+
41
+ // src/utils/errorMessage.ts
42
+ function errorMessage(err) {
43
+ if (err instanceof Error) {
44
+ return err.message;
45
+ }
46
+ if (typeof err === "string") {
47
+ return err;
48
+ }
49
+ return String(err);
50
+ }
51
+ function resolveProjectDir(projectDir) {
52
+ return path13.resolve(projectDir ?? process.cwd());
53
+ }
54
+ function toComposePath(baseDir, targetPath) {
55
+ const absBase = path13.resolve(baseDir);
56
+ const absTarget = path13.resolve(absBase, targetPath);
57
+ let rel = path13.relative(absBase, absTarget);
58
+ if (!rel || rel === ".") {
59
+ return ".";
60
+ }
61
+ rel = rel.replace(/\\/g, "/");
62
+ if (path13.isAbsolute(rel) || /^[a-zA-Z]:\//.test(rel)) {
63
+ return rel;
64
+ }
65
+ if (rel.startsWith("./") || rel.startsWith("../") || rel.startsWith("/")) {
66
+ return rel;
67
+ }
68
+ return `./${rel}`;
69
+ }
70
+ function isBindMount(source) {
71
+ if (!source) return false;
72
+ if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~")) {
73
+ return true;
74
+ }
75
+ if (/^[a-zA-Z]:[\\/]/.test(source)) {
76
+ return true;
77
+ }
78
+ return false;
79
+ }
80
+ function isPathInside(parentDir, childPath) {
81
+ const absParent = path13.resolve(parentDir);
82
+ const absChild = path13.resolve(absParent, childPath);
83
+ const rel = path13.relative(absParent, absChild);
84
+ return rel !== ".." && !rel.startsWith(".." + path13.sep) && !rel.startsWith("../") && !path13.isAbsolute(rel);
85
+ }
86
+
87
+ // src/utils/ymlMods/normalizeDependsOn.ts
88
+ function normalizeDependsOn(service) {
89
+ if (!service || typeof service !== "object" || !service.depends_on) {
90
+ return;
91
+ }
92
+ if (Array.isArray(service.depends_on)) {
93
+ const obj = {};
94
+ for (const dep of service.depends_on) {
95
+ if (typeof dep === "string") {
96
+ obj[dep] = { condition: "service_started" };
97
+ }
98
+ }
99
+ service.depends_on = obj;
100
+ }
101
+ }
102
+
103
+ // src/utils/getBuildJson.ts
104
+ var getBuildJson = (projectDir = process.cwd()) => {
105
+ const absProjectDir = resolveProjectDir(projectDir);
106
+ const buildJsonPath = path13.join(absProjectDir, "build.json");
107
+ if (!existsSync(buildJsonPath)) {
108
+ throw new NotFoundError(
109
+ `Build JSON file not found at ${buildJsonPath}. Please make sure build.json exists in the project root.`
110
+ );
111
+ }
112
+ let rawData;
113
+ try {
114
+ rawData = readFileSync(buildJsonPath, "utf-8");
115
+ } catch (error) {
116
+ throw new ScriptError(
117
+ `Failed to read build.json at ${buildJsonPath}: ${errorMessage(error)}`
118
+ );
119
+ }
120
+ let buildJson;
121
+ try {
122
+ buildJson = JSON.parse(rawData);
123
+ } catch (error) {
124
+ throw new ScriptError(
125
+ `Failed to parse build.json at ${buildJsonPath}: ${errorMessage(error)}`
126
+ );
127
+ }
128
+ if (!buildJson || typeof buildJson !== "object" || Array.isArray(buildJson)) {
129
+ throw new ScriptError(
130
+ `Invalid build.json at ${buildJsonPath}: root must be a JSON object.`
131
+ );
132
+ }
133
+ const typedBuildJson = buildJson;
134
+ if (typedBuildJson.services && typeof typedBuildJson.services === "object") {
135
+ for (const serviceConfig of Object.values(typedBuildJson.services)) {
136
+ if (serviceConfig && typeof serviceConfig === "object") {
137
+ normalizeDependsOn(serviceConfig);
138
+ }
139
+ }
140
+ }
141
+ return typedBuildJson;
142
+ };
143
+
144
+ // src/core/checkers/constants.ts
145
+ var HADOLINT_IMAGE = process.env.HADOLINT_IMAGE || "hadolint/hadolint:v2.12.0";
146
+ var CONFTEST_IMAGE = process.env.CONFTEST_IMAGE || "openpolicyagent/conftest:v0.56.0";
147
+ function runStep(executable, args, projectDir, ctx) {
148
+ const options = {
149
+ cwd: projectDir,
150
+ stdio: [ctx.input !== void 0 ? "pipe" : "inherit", "pipe", "pipe"],
151
+ encoding: "utf-8",
152
+ maxBuffer: 20 * 1024 * 1024,
153
+ input: ctx.input
154
+ };
155
+ const result = spawnSync(executable, args, options);
156
+ const stdout = result.stdout ?? "";
157
+ const stderr = result.stderr ?? "";
158
+ if (stdout) process.stdout.write(stdout);
159
+ if (stderr) process.stderr.write(stderr);
160
+ if (result.error || result.status !== 0) {
161
+ console.error("\n" + "=".repeat(60));
162
+ console.error(pc20.red(`\u{1F6A8} INFRASTRUCTURE CHECK FAILED \u{1F6A8}`));
163
+ console.error("=".repeat(60));
164
+ console.error(`Failed Step : ${ctx.stepName}`);
165
+ if (ctx.targetFile) {
166
+ console.error(`Target File : ${ctx.targetFile} <-- FIX THIS FILE`);
167
+ }
168
+ if (result.error) {
169
+ console.error(`Cause : ${result.error.message}`);
170
+ }
171
+ if (ctx.detail) {
172
+ console.error(`
173
+ ${ctx.detail}`);
174
+ }
175
+ console.error("=".repeat(60) + "\n");
176
+ const causeMsg = result.error ? ` (${result.error.message})` : "";
177
+ throw new ScriptError(
178
+ `Infrastructure check failed at step: ${ctx.stepName}${causeMsg}`,
179
+ { cause: result.error, exitCode: result.status ?? 1 }
180
+ );
181
+ }
182
+ }
183
+
184
+ // src/core/checkers/checkDockerfile.ts
185
+ function checkDockerfile(buildJson, projectDir) {
186
+ const dockerfileRel = buildJson.dockerfile || "Dockerfile";
187
+ const dockerfilePath = path13.resolve(projectDir, dockerfileRel);
188
+ if (!isPathInside(projectDir, dockerfilePath)) {
189
+ throw new ScriptError(
190
+ `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
191
+ );
192
+ }
193
+ if (!existsSync(dockerfilePath)) {
194
+ if (buildJson.dockerfile) {
195
+ throw new ScriptError(
196
+ `Dockerfile declared in build.json not found at: ${dockerfilePath}`
197
+ );
198
+ }
199
+ console.log(
200
+ pc20.yellow(`\u26A0\uFE0F No ${dockerfileRel} found in project directory. Skipping Dockerfile checks.`)
201
+ );
202
+ return;
203
+ }
204
+ const content = readFileSync(dockerfilePath, "utf-8");
205
+ console.log(pc20.cyan(`
206
+ \u{1F50D} Linting Dockerfile (${dockerfileRel})...`));
207
+ runStep(
208
+ "docker",
209
+ ["run", "--rm", "-i", "--network", "none", HADOLINT_IMAGE, "hadolint", "--failure-threshold", "error", "-"],
210
+ projectDir,
211
+ { stepName: "Dockerfile Linting", targetFile: dockerfileRel, input: content }
212
+ );
213
+ }
214
+ function checkDockerfileContract(buildJson, projectDir) {
215
+ const absProjectDir = resolveProjectDir(projectDir);
216
+ const dockerfileRel = buildJson.dockerfile || "Dockerfile";
217
+ const dockerfilePath = path13.resolve(absProjectDir, dockerfileRel);
218
+ const policyRel = buildJson.policy?.dockerfile || buildJson.policies?.dockerfile || "policy/dockerfile";
219
+ const policyDir = path13.resolve(absProjectDir, policyRel);
220
+ if (!isPathInside(absProjectDir, dockerfilePath)) {
221
+ throw new ScriptError(
222
+ `Security error: Dockerfile path "${dockerfileRel}" escapes the project directory.`
223
+ );
224
+ }
225
+ if (!existsSync(dockerfilePath) || !existsSync(policyDir)) {
226
+ return;
227
+ }
228
+ console.log(pc20.cyan(`
229
+ \u{1F50D} Validating Dockerfile Contract (${policyRel})...`));
230
+ runStep(
231
+ "docker",
232
+ [
233
+ "run",
234
+ "--rm",
235
+ "--network",
236
+ "none",
237
+ "--mount",
238
+ `type=bind,src=${absProjectDir},dst=/project,readonly`,
239
+ "-w",
240
+ "/project",
241
+ CONFTEST_IMAGE,
242
+ "test",
243
+ dockerfileRel,
244
+ "-p",
245
+ `${policyRel}/`
246
+ ],
247
+ absProjectDir,
248
+ { stepName: "Dockerfile Contract", targetFile: dockerfileRel }
249
+ );
250
+ }
251
+ function getDeclaredYamlFiles(buildJson, projectDir) {
252
+ const files = [];
253
+ const seen = /* @__PURE__ */ new Set();
254
+ const addFile = (relPath, source) => {
255
+ const normalized = path13.normalize(relPath);
256
+ if (seen.has(normalized)) return;
257
+ seen.add(normalized);
258
+ files.push({
259
+ relativePath: relPath,
260
+ absolutePath: path13.resolve(projectDir, relPath),
261
+ source
262
+ });
263
+ };
264
+ if (buildJson.dependencies && typeof buildJson.dependencies === "object") {
265
+ for (const [depName, dep] of Object.entries(buildJson.dependencies)) {
266
+ if (dep && typeof dep === "object" && typeof dep.path === "string") {
267
+ addFile(dep.path, `dependency "${depName}"`);
268
+ }
269
+ }
270
+ }
271
+ if (buildJson.overrides && typeof buildJson.overrides === "object") {
272
+ for (const [stage, ovr] of Object.entries(buildJson.overrides)) {
273
+ if (ovr && typeof ovr === "object" && typeof ovr.path === "string") {
274
+ addFile(ovr.path, `override "${stage}"`);
275
+ }
276
+ }
277
+ }
278
+ if (Array.isArray(buildJson.composeFiles)) {
279
+ for (const item of buildJson.composeFiles) {
280
+ if (typeof item === "string") {
281
+ addFile(item, "composeFiles");
282
+ }
283
+ }
284
+ }
285
+ return files;
286
+ }
287
+
288
+ // src/core/checkers/checkYamlFiles.ts
289
+ function checkYamlFiles(buildJson, projectDir) {
290
+ const absProjectDir = resolveProjectDir(projectDir);
291
+ const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
292
+ if (declaredFiles.length === 0) {
293
+ return;
294
+ }
295
+ console.log(
296
+ pc20.cyan(
297
+ `
298
+ \u{1F50D} Validating Declared YAML Files (${declaredFiles.length} file${declaredFiles.length === 1 ? "" : "s"})...`
299
+ )
300
+ );
301
+ const errors = [];
302
+ for (const file of declaredFiles) {
303
+ if (!existsSync(file.absolutePath)) {
304
+ errors.push(
305
+ `File "${file.relativePath}" declared in build.json (${file.source}) does not exist (expected at ${file.absolutePath}).`
306
+ );
307
+ continue;
308
+ }
309
+ try {
310
+ const content = readFileSync(file.absolutePath, "utf-8");
311
+ const docs = parseAllDocuments(content);
312
+ const docErrors = docs.flatMap((doc) => doc.errors);
313
+ if (docErrors.length > 0) {
314
+ const errorText = docErrors.map((e) => e.message).join("\n");
315
+ errors.push(
316
+ `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${errorText}`
317
+ );
318
+ }
319
+ } catch (err) {
320
+ const msg = errorMessage(err);
321
+ errors.push(
322
+ `YAML Syntax Error in "${file.relativePath}" (${file.source}): ${msg}`
323
+ );
324
+ }
325
+ }
326
+ if (errors.length > 0) {
327
+ throw new ScriptError(errors.join("\n"));
328
+ }
329
+ }
330
+ function checkComposeContract(buildJson, projectDir) {
331
+ const absProjectDir = resolveProjectDir(projectDir);
332
+ const policyRel = buildJson.policy?.compose || buildJson.policies?.compose;
333
+ if (!policyRel) {
334
+ return;
335
+ }
336
+ const policyDir = path13.resolve(absProjectDir, policyRel);
337
+ if (!existsSync(policyDir)) {
338
+ return;
339
+ }
340
+ const declaredFiles = getDeclaredYamlFiles(buildJson, absProjectDir);
341
+ const existingFiles = declaredFiles.filter((f) => existsSync(f.absolutePath));
342
+ if (existingFiles.length === 0) {
343
+ return;
344
+ }
345
+ for (const f of existingFiles) {
346
+ if (!isPathInside(absProjectDir, f.absolutePath)) {
347
+ throw new ScriptError(
348
+ `Security error: Compose file path "${f.relativePath}" escapes the project directory.`
349
+ );
350
+ }
351
+ }
352
+ const relativePaths = existingFiles.map((f) => f.relativePath);
353
+ console.log(pc20.cyan(`
354
+ \u{1F50D} Validating Compose Contract (${policyRel})...`));
355
+ runStep(
356
+ "docker",
357
+ [
358
+ "run",
359
+ "--rm",
360
+ "--network",
361
+ "none",
362
+ "--mount",
363
+ `type=bind,src=${absProjectDir},dst=/project,readonly`,
364
+ "-w",
365
+ "/project",
366
+ CONFTEST_IMAGE,
367
+ "test",
368
+ ...relativePaths,
369
+ "-p",
370
+ `${policyRel}/`,
371
+ "--all-namespaces"
372
+ ],
373
+ absProjectDir,
374
+ {
375
+ stepName: "Compose Contract Validation",
376
+ targetFile: relativePaths.join(", ")
377
+ }
378
+ );
379
+ }
380
+
381
+ // src/core/checkers/checkInfra.ts
382
+ function checkInfra(projectDir = process.cwd()) {
383
+ const absProjectDir = resolveProjectDir(projectDir);
384
+ const buildJson = getBuildJson(absProjectDir);
385
+ checkDockerfile(buildJson, absProjectDir);
386
+ checkDockerfileContract(buildJson, absProjectDir);
387
+ checkYamlFiles(buildJson, absProjectDir);
388
+ checkComposeContract(buildJson, absProjectDir);
389
+ console.log(pc20.green("\n\u2705 All infrastructure and contract checks passed.\n"));
390
+ }
391
+ function checkDependencies() {
392
+ const composeCheck = spawnSync(
393
+ "docker",
394
+ ["compose", "version", "--short"],
395
+ {
396
+ stdio: "pipe",
397
+ encoding: "utf-8"
398
+ }
399
+ );
400
+ if (composeCheck.error || composeCheck.status !== 0) {
401
+ throw new ScriptError(
402
+ "Error: Docker Compose v2 is not installed or docker is not in PATH. Please install Docker and Compose v2 first."
403
+ );
404
+ }
405
+ const rawVersion = (composeCheck.stdout || "").trim().replace(/^v/, "");
406
+ const versionParts = rawVersion.split(".").map((p) => parseInt(p, 10));
407
+ const major = versionParts[0] ?? 0;
408
+ const minor = versionParts[1] ?? 0;
409
+ if (major < 2 || major === 2 && minor < 24) {
410
+ throw new ScriptError(
411
+ `Error: Docker Compose version >= 2.24.0 is required (found ${rawVersion}). Please upgrade Docker Compose to support optional env_file syntax.`
412
+ );
413
+ }
414
+ const daemonCheck = spawnSync("docker", ["info"], {
415
+ stdio: "pipe",
416
+ encoding: "utf-8"
417
+ });
418
+ if (daemonCheck.error || daemonCheck.status !== 0) {
419
+ throw new ScriptError(
420
+ "Error: Docker daemon is not running or not accessible. Please start the Docker daemon first."
421
+ );
422
+ }
423
+ const networkCheck = spawnSync("docker", ["network", "ls", "-q"], {
424
+ stdio: "pipe",
425
+ encoding: "utf-8"
426
+ });
427
+ if (!networkCheck.error && networkCheck.status === 0) {
428
+ const count = (networkCheck.stdout || "").trim().split("\n").filter(Boolean).length;
429
+ if (count > 25) {
430
+ console.warn(
431
+ pc20.yellow(
432
+ `
433
+ \u26A0\uFE0F High Docker Network Count Warning: Detected ${count} networks. Docker's default address pool can become exhausted, resulting in "could not find an available, non-overlapping IPv4 address pool" errors.
434
+ To resolve, run "builder prune" or "docker network prune -f", or configure default-address-pools in /etc/docker/daemon.json.
435
+ `
436
+ )
437
+ );
438
+ }
439
+ }
440
+ }
441
+
442
+ // src/commands/check/handler.ts
443
+ async function handleCheck(options = {}) {
444
+ const projectDir = resolveProjectDir(options.projectDir);
445
+ checkDependencies();
446
+ checkInfra(projectDir);
447
+ return 0;
448
+ }
449
+
450
+ // src/commands/check/command.ts
451
+ var registerCheckCommand = (cmd) => {
452
+ cmd.command("check").description("Run infrastructure and contract checks (hadolint, conftest)").option(
453
+ "-C, --project-dir <dir>",
454
+ "Service project directory (defaults to cwd)"
455
+ ).addHelpText(
456
+ "after",
457
+ `
458
+ Examples:
459
+ $ builder check
460
+ $ builder check -C ./services/backend`
461
+ ).action(async (options = {}) => {
462
+ const exitCode = await handleCheck({
463
+ projectDir: options.projectDir
464
+ });
465
+ if (exitCode !== 0) {
466
+ process.exit(exitCode);
467
+ }
468
+ });
469
+ };
470
+ var meshHealthcheckSchema = z.union([
471
+ z.object({
472
+ type: z.literal("tcp"),
473
+ port: z.union([z.number(), z.string()]).optional()
474
+ }).strict(),
475
+ z.object({
476
+ test: z.union([z.string(), z.array(z.string())]),
477
+ interval: z.string().optional(),
478
+ timeout: z.string().optional(),
479
+ retries: z.number().optional(),
480
+ start_period: z.string().optional(),
481
+ disable: z.boolean().optional()
482
+ }).passthrough()
483
+ ]);
484
+ var meshServiceSchema = z.object({
485
+ path: z.string({ required_error: 'Service "path" is required' }),
486
+ port: z.union([z.number(), z.string()]).optional(),
487
+ provideDependency: z.record(z.string(), z.string()).optional(),
488
+ replaceMocks: z.record(z.string(), z.string()).optional(),
489
+ envOverrides: z.record(z.string(), z.string()).optional(),
490
+ healthcheck: meshHealthcheckSchema.optional()
491
+ }).strict();
492
+ var meshTesterSchema = z.object({
493
+ path: z.string({ required_error: 'Tester "path" is required' }),
494
+ compose: z.string().optional(),
495
+ dockerfile: z.string().optional(),
496
+ policy: z.object({
497
+ dockerfile: z.string().optional(),
498
+ compose: z.string().optional()
499
+ }).strict().optional()
500
+ }).strict();
501
+ var meshServiceNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
502
+ var meshSchema = z.object({
503
+ name: z.string().optional(),
504
+ services: z.record(
505
+ z.string().regex(meshServiceNameRegex, {
506
+ message: "Service name must start with a lowercase letter or digit and contain only lowercase letters, digits, '-', '_', or '.'"
507
+ }),
508
+ meshServiceSchema
509
+ ).refine((services) => Object.keys(services).length > 0, {
510
+ message: 'At least one service must be defined in "services".'
511
+ }),
512
+ dependencies: z.record(
513
+ z.string(),
514
+ z.object({
515
+ path: z.string(),
516
+ service: z.string().optional()
517
+ }).strict()
518
+ ).optional(),
519
+ tester: meshTesterSchema.optional()
520
+ }).strict();
521
+
522
+ // src/core/mesh/checkers/checkMeshJson.ts
523
+ function checkMeshJson(mesh) {
524
+ const result = meshSchema.safeParse(mesh);
525
+ if (!result.success) {
526
+ const errorDetails = result.error.issues.map(
527
+ (issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message
528
+ ).join("; ");
529
+ throw new ScriptError(`Invalid mesh.json: ${errorDetails}`);
530
+ }
531
+ const services = result.data.services;
532
+ const serviceKeys = new Set(Object.keys(services));
533
+ const seenPorts = /* @__PURE__ */ new Map();
534
+ for (const [serviceName, serviceConfig] of Object.entries(services)) {
535
+ if (serviceConfig.port) {
536
+ const portNum = Number(serviceConfig.port);
537
+ if (!isNaN(portNum)) {
538
+ if (seenPorts.has(portNum)) {
539
+ throw new ScriptError(
540
+ `Host port collision in mesh.json: Port ${portNum} is declared by both "${seenPorts.get(portNum)}" and "${serviceName}".`
541
+ );
542
+ }
543
+ seenPorts.set(portNum, serviceName);
544
+ }
545
+ }
546
+ }
547
+ const graph = /* @__PURE__ */ new Map();
548
+ for (const sName of serviceKeys) {
549
+ graph.set(sName, /* @__PURE__ */ new Set());
550
+ }
551
+ for (const [serviceName, serviceConfig] of Object.entries(services)) {
552
+ const provideMap = {
553
+ ...serviceConfig.replaceMocks || {},
554
+ ...serviceConfig.provideDependency || {}
555
+ };
556
+ for (const [depKey, targetSvc] of Object.entries(provideMap)) {
557
+ if (!serviceKeys.has(targetSvc)) {
558
+ throw new ScriptError(
559
+ `Invalid mesh.json: Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetSvc}".`
560
+ );
561
+ }
562
+ graph.get(serviceName).add(targetSvc);
563
+ }
564
+ }
565
+ const visited = /* @__PURE__ */ new Map();
566
+ function dfs(node, pathStack) {
567
+ visited.set(node, "visiting");
568
+ pathStack.push(node);
569
+ const neighbors = graph.get(node) || /* @__PURE__ */ new Set();
570
+ for (const neighbor of neighbors) {
571
+ const state = visited.get(neighbor);
572
+ if (state === "visiting") {
573
+ const cycleStart = pathStack.indexOf(neighbor);
574
+ const cycle = [...pathStack.slice(cycleStart), neighbor];
575
+ throw new ScriptError(
576
+ `Dependency cycle detected in mesh.json: ${cycle.join(" -> ")}`
577
+ );
578
+ }
579
+ if (!state) {
580
+ dfs(neighbor, pathStack);
581
+ }
582
+ }
583
+ pathStack.pop();
584
+ visited.set(node, "visited");
585
+ }
586
+ for (const sName of serviceKeys) {
587
+ if (!visited.has(sName)) {
588
+ dfs(sName, []);
589
+ }
590
+ }
591
+ }
592
+
593
+ // src/core/mesh/getMeshJson.ts
594
+ function getMeshJson(projectDir = process.cwd()) {
595
+ const absDir = resolveProjectDir(projectDir);
596
+ const meshPath = path13.resolve(absDir, "mesh.json");
597
+ if (!existsSync(meshPath)) {
598
+ throw new NotFoundError(`mesh.json not found in directory: ${absDir}`);
599
+ }
600
+ let content;
601
+ try {
602
+ content = readFileSync(meshPath, "utf-8");
603
+ } catch (err) {
604
+ throw new ScriptError(
605
+ `Failed to read mesh.json at ${meshPath}: ${errorMessage(err)}`
606
+ );
607
+ }
608
+ let parsed;
609
+ try {
610
+ parsed = JSON.parse(content);
611
+ } catch (err) {
612
+ throw new ScriptError(
613
+ `Failed to parse mesh.json at ${meshPath}: ${errorMessage(err)}`
614
+ );
615
+ }
616
+ if (!parsed || typeof parsed !== "object") {
617
+ throw new ScriptError(`Invalid mesh.json: root must be an object.`);
618
+ }
619
+ const meshConfig = parsed;
620
+ checkMeshJson(meshConfig);
621
+ return meshConfig;
622
+ }
623
+ function checkMeshServices(mesh, meshDir = process.cwd()) {
624
+ const absMeshDir = resolveProjectDir(meshDir);
625
+ const serviceNames = Object.keys(mesh.services);
626
+ console.log(
627
+ pc20.bold(
628
+ pc20.cyan(
629
+ `
630
+ \u{1F50D} Checking Mesh Services (${serviceNames.length} service${serviceNames.length === 1 ? "" : "s"})...`
631
+ )
632
+ )
633
+ );
634
+ for (const serviceName of serviceNames) {
635
+ const serviceConfig = mesh.services[serviceName];
636
+ if (!serviceConfig) {
637
+ throw new ScriptError(`Service "${serviceName}" configuration is missing.`);
638
+ }
639
+ const serviceDir = path13.resolve(absMeshDir, serviceConfig.path);
640
+ if (!isPathInside(absMeshDir, serviceDir)) {
641
+ throw new ScriptError(
642
+ `Security error: Service "${serviceName}" directory escapes the mesh directory: ${serviceDir}`
643
+ );
644
+ }
645
+ if (!existsSync(serviceDir)) {
646
+ throw new ScriptError(
647
+ `Service "${serviceName}" directory does not exist: ${serviceDir} (declared path: "${serviceConfig.path}")`
648
+ );
649
+ }
650
+ if (!statSync(serviceDir).isDirectory()) {
651
+ throw new ScriptError(
652
+ `Service "${serviceName}" path is not a directory: ${serviceDir}`
653
+ );
654
+ }
655
+ const buildJsonPath = path13.resolve(serviceDir, "build.json");
656
+ if (!existsSync(buildJsonPath)) {
657
+ throw new ScriptError(
658
+ `Service "${serviceName}" is missing a valid build.json at: ${buildJsonPath}`
659
+ );
660
+ }
661
+ console.log(
662
+ pc20.bold(pc20.blue(`
663
+ --- Validating Infrastructure for [${serviceName}] ---`))
664
+ );
665
+ checkInfra(serviceDir);
666
+ }
667
+ }
668
+ function checkMeshTester(mesh, meshDir = process.cwd(), options = {}) {
669
+ if (!mesh.tester) {
670
+ if (options.required) {
671
+ throw new ScriptError(
672
+ 'E2E tester not configured in mesh.json: Missing "tester" configuration.'
673
+ );
674
+ }
675
+ return;
676
+ }
677
+ const absMeshDir = resolveProjectDir(meshDir);
678
+ const testerConfig = mesh.tester;
679
+ if (!testerConfig.path || typeof testerConfig.path !== "string") {
680
+ throw new ScriptError(
681
+ 'Invalid tester configuration in mesh.json: Missing or invalid "path".'
682
+ );
683
+ }
684
+ const absTesterDir = path13.resolve(absMeshDir, testerConfig.path);
685
+ if (!isPathInside(absMeshDir, absTesterDir)) {
686
+ throw new ScriptError(
687
+ `Security error: Tester directory path "${testerConfig.path}" escapes the mesh project directory.`
688
+ );
689
+ }
690
+ if (!existsSync(absTesterDir)) {
691
+ throw new ScriptError(
692
+ `E2E tester directory does not exist: ${absTesterDir} (declared path: "${testerConfig.path}")`
693
+ );
694
+ }
695
+ console.log(
696
+ pc20.bold(pc20.cyan(`
697
+ \u{1F50D} Checking E2E Tester (${testerConfig.path})...`))
698
+ );
699
+ const composeRel = testerConfig.compose || "docker-compose.yml";
700
+ const composePath = path13.resolve(absTesterDir, composeRel);
701
+ if (!existsSync(composePath)) {
702
+ throw new ScriptError(
703
+ `E2E tester docker compose file not found at: ${composePath}`
704
+ );
705
+ }
706
+ try {
707
+ const composeContent = readFileSync(composePath, "utf-8");
708
+ const docs = parseAllDocuments(composeContent);
709
+ const docErrors = docs.flatMap((doc) => doc.errors);
710
+ if (docErrors.length > 0) {
711
+ throw new Error(docErrors.map((e) => e.message).join("\n"));
712
+ }
713
+ } catch (err) {
714
+ throw new ScriptError(
715
+ `Invalid YAML syntax in tester docker compose (${composeRel}): ${errorMessage(err)}`
716
+ );
717
+ }
718
+ const dockerfileRel = testerConfig.dockerfile || "Dockerfile";
719
+ const dockerfilePath = path13.resolve(absTesterDir, dockerfileRel);
720
+ if (!existsSync(dockerfilePath)) {
721
+ throw new ScriptError(
722
+ `E2E tester Dockerfile not found at: ${dockerfilePath}`
723
+ );
724
+ }
725
+ const dockerfileContent = readFileSync(dockerfilePath, "utf-8");
726
+ console.log(pc20.cyan(`
727
+ \u{1F50D} Linting E2E Tester Dockerfile (${dockerfileRel})...`));
728
+ runStep(
729
+ "docker",
730
+ ["run", "--rm", "-i", "--network", "none", HADOLINT_IMAGE, "hadolint", "--failure-threshold", "error", "-"],
731
+ absTesterDir,
732
+ {
733
+ stepName: "E2E Tester Dockerfile Linting",
734
+ targetFile: dockerfileRel,
735
+ input: dockerfileContent
736
+ }
737
+ );
738
+ const dockerfilePolicyRel = testerConfig.policy?.dockerfile || "policy/dockerfile";
739
+ const dockerfilePolicyDir = path13.resolve(absTesterDir, dockerfilePolicyRel);
740
+ if (existsSync(dockerfilePolicyDir)) {
741
+ console.log(
742
+ pc20.cyan(
743
+ `
744
+ \u{1F50D} Validating Tester Dockerfile Contract (${dockerfilePolicyRel})...`
745
+ )
746
+ );
747
+ runStep(
748
+ "docker",
749
+ [
750
+ "run",
751
+ "--rm",
752
+ "--network",
753
+ "none",
754
+ "--mount",
755
+ `type=bind,src=${absTesterDir},dst=/project,readonly`,
756
+ "-w",
757
+ "/project",
758
+ CONFTEST_IMAGE,
759
+ "test",
760
+ dockerfileRel,
761
+ "-p",
762
+ `${dockerfilePolicyRel}/`
763
+ ],
764
+ absTesterDir,
765
+ { stepName: "E2E Tester Dockerfile Contract", targetFile: dockerfileRel }
766
+ );
767
+ }
768
+ const composePolicyRel = testerConfig.policy?.compose || "policy/compose";
769
+ const composePolicyDir = path13.resolve(absTesterDir, composePolicyRel);
770
+ if (existsSync(composePolicyDir)) {
771
+ console.log(
772
+ pc20.cyan(`
773
+ \u{1F50D} Validating Tester Compose Contract (${composePolicyRel})...`)
774
+ );
775
+ runStep(
776
+ "docker",
777
+ [
778
+ "run",
779
+ "--rm",
780
+ "--network",
781
+ "none",
782
+ "--mount",
783
+ `type=bind,src=${absTesterDir},dst=/project,readonly`,
784
+ "-w",
785
+ "/project",
786
+ CONFTEST_IMAGE,
787
+ "test",
788
+ composeRel,
789
+ "-p",
790
+ `${composePolicyRel}/`,
791
+ "--all-namespaces"
792
+ ],
793
+ absTesterDir,
794
+ { stepName: "E2E Tester Compose Contract", targetFile: composeRel }
795
+ );
796
+ }
797
+ console.log(pc20.green(`\u2705 E2E tester configuration and contracts verified.
798
+ `));
799
+ }
800
+
801
+ // src/core/mesh/checkers/checkMesh.ts
802
+ function checkMesh(meshDir = process.cwd(), options = {}) {
803
+ const absMeshDir = resolveProjectDir(meshDir);
804
+ const mesh = getMeshJson(absMeshDir);
805
+ checkMeshServices(mesh, absMeshDir);
806
+ checkMeshTester(mesh, absMeshDir, { required: Boolean(options.requireTester) });
807
+ console.log(
808
+ pc20.bold(
809
+ pc20.green("\n\u{1F389} All mesh infrastructure, services, and contract checks passed!\n")
810
+ )
811
+ );
812
+ }
813
+
814
+ // src/commands/mesh/commands/check/handler.ts
815
+ async function handleMeshCheck(options = {}) {
816
+ const meshDir = resolveProjectDir(options.projectDir);
817
+ checkDependencies();
818
+ checkMesh(meshDir, { requireTester: options.requireTester });
819
+ return 0;
820
+ }
821
+
822
+ // src/commands/mesh/commands/check/command.ts
823
+ var registerMeshCheckCommand = (cmd) => {
824
+ cmd.command("check").description(
825
+ "Validate mesh.json, all services, build.json contracts, and e2e tester contracts"
826
+ ).option(
827
+ "-C, --project-dir <dir>",
828
+ "Mesh project directory (defaults to cwd)"
829
+ ).option(
830
+ "--require-tester",
831
+ "Fail if an e2e tester is not configured in mesh.json"
832
+ ).addHelpText(
833
+ "after",
834
+ `
835
+ Examples:
836
+ $ builder mesh check
837
+ $ builder mesh check -C ./examples/largeProject`
838
+ ).action(async (options = {}) => {
839
+ const exitCode = await handleMeshCheck({
840
+ projectDir: options.projectDir,
841
+ requireTester: options.requireTester
842
+ });
843
+ if (exitCode !== 0) {
844
+ process.exit(exitCode);
845
+ }
846
+ });
847
+ };
848
+ var extractBuildDeps = (buildJson, projectDir = process.cwd()) => {
849
+ if (!buildJson || typeof buildJson !== "object") {
850
+ return [];
851
+ }
852
+ if (!("dependencies" in buildJson) || !buildJson.dependencies) {
853
+ return [];
854
+ }
855
+ const schema = z.object({
856
+ dependencies: z.record(
857
+ z.string(),
858
+ z.object({
859
+ path: z.string(),
860
+ service: z.string().optional()
861
+ })
862
+ )
863
+ });
864
+ const result = schema.safeParse(buildJson);
865
+ if (!result.success) {
866
+ const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
867
+ throw new ScriptError(
868
+ `Invalid build.json structure for dependencies: ${errorDetails}`
869
+ );
870
+ }
871
+ const dependenciesData = result.data.dependencies;
872
+ const dependencies = Object.entries(dependenciesData || {}).map(
873
+ ([name, service]) => {
874
+ return {
875
+ path: path13.resolve(projectDir, service.path),
876
+ name,
877
+ serviceName: service.service
878
+ };
879
+ }
880
+ );
881
+ return dependencies;
882
+ };
883
+ var VALID_STAGES = ["dev", "prod", "test", "e2e"];
884
+ var extractOverrides = (buildJson, projectDir = process.cwd()) => {
885
+ if (!buildJson || typeof buildJson !== "object") {
886
+ return {};
887
+ }
888
+ if (!("overrides" in buildJson) || !buildJson.overrides) {
889
+ return {};
890
+ }
891
+ const schema = z.object({
892
+ overrides: z.record(
893
+ z.enum(VALID_STAGES, {
894
+ errorMap: () => ({
895
+ message: `Unknown stage override. Supported stages are: ${VALID_STAGES.join(", ")}`
896
+ })
897
+ }),
898
+ z.object({
899
+ path: z.string({ required_error: "Override 'path' is required" })
900
+ })
901
+ )
902
+ });
903
+ const result = schema.safeParse(buildJson);
904
+ if (!result.success) {
905
+ const errorDetails = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
906
+ throw new ScriptError(
907
+ `Invalid build.json structure for overrides: ${errorDetails}`
908
+ );
909
+ }
910
+ const resolvedOverrides = {};
911
+ for (const [key, value] of Object.entries(result.data.overrides)) {
912
+ resolvedOverrides[key] = {
913
+ path: path13.resolve(projectDir, value.path)
914
+ };
915
+ }
916
+ return resolvedOverrides;
917
+ };
918
+ function normalizeProjectName(name, projectDir) {
919
+ let normalized = name.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").replace(/[-_]+$/, "");
920
+ if (!normalized || !/^[a-z0-9]/.test(normalized)) {
921
+ return "project";
922
+ }
923
+ return normalized;
924
+ }
925
+ function deriveProjectName(name, stage, projectDir, options = {}) {
926
+ let base = normalizeProjectName(name);
927
+ if (options.hash && projectDir) ;
928
+ if (!stage) {
929
+ return base;
930
+ }
931
+ const s = stage.toLowerCase();
932
+ if (s === "dev") {
933
+ return base;
934
+ }
935
+ if (s === "prod") {
936
+ return `${base}-prod`;
937
+ }
938
+ if (s === "test" || s === "test-unit") {
939
+ return `${base}-test`;
940
+ }
941
+ if (s === "e2e" || s === "test-e2e") {
942
+ return `${base}-e2e`;
943
+ }
944
+ return `${base}-${s}`;
945
+ }
946
+
947
+ // src/core/mesh/compileMeshEnvironment.ts
948
+ function compileMeshEnvironment(mode, rawMeshDir = process.cwd(), options = {}) {
949
+ const meshDir = resolveProjectDir(rawMeshDir);
950
+ const mesh = getMeshJson(meshDir);
951
+ const rawProjectName = mesh.name || path13.basename(meshDir);
952
+ const projectName = deriveProjectName(
953
+ rawProjectName,
954
+ options.includeTester ? "e2e" : mode
955
+ );
956
+ const composeConfig = {
957
+ name: projectName,
958
+ networks: {
959
+ mesh: {}
960
+ },
961
+ services: {}
962
+ };
963
+ function mergeTopLevelResources(parsed) {
964
+ if (!parsed || typeof parsed !== "object") return;
965
+ for (const key of ["volumes", "secrets", "configs"]) {
966
+ if (parsed[key] && typeof parsed[key] === "object") {
967
+ composeConfig[key] = {
968
+ ...composeConfig[key] || {},
969
+ ...parsed[key]
970
+ };
971
+ }
972
+ }
973
+ }
974
+ function rewriteServiceVolume(svc, oldKey, newKey) {
975
+ if (!svc || !Array.isArray(svc.volumes)) return;
976
+ svc.volumes = svc.volumes.map((vol) => {
977
+ if (typeof vol === "string") {
978
+ if (vol === oldKey) return newKey;
979
+ if (vol.startsWith(`${oldKey}:`)) {
980
+ return `${newKey}:${vol.slice(oldKey.length + 1)}`;
981
+ }
982
+ return vol;
983
+ }
984
+ if (vol && typeof vol === "object" && vol.source === oldKey) {
985
+ return { ...vol, source: newKey };
986
+ }
987
+ return vol;
988
+ });
989
+ }
990
+ function rewriteServiceSecret(svc, oldKey, newKey) {
991
+ if (!svc || !svc.secrets) return;
992
+ if (Array.isArray(svc.secrets)) {
993
+ svc.secrets = svc.secrets.map((sec) => {
994
+ if (sec === oldKey) return newKey;
995
+ if (typeof sec === "object" && sec.source === oldKey) {
996
+ return { ...sec, source: newKey };
997
+ }
998
+ return sec;
999
+ });
1000
+ }
1001
+ }
1002
+ function rewriteServiceConfig(svc, oldKey, newKey) {
1003
+ if (!svc || !svc.configs) return;
1004
+ if (Array.isArray(svc.configs)) {
1005
+ svc.configs = svc.configs.map((cfg) => {
1006
+ if (cfg === oldKey) return newKey;
1007
+ if (typeof cfg === "object" && cfg.source === oldKey) {
1008
+ return { ...cfg, source: newKey };
1009
+ }
1010
+ return cfg;
1011
+ });
1012
+ }
1013
+ }
1014
+ function mergeAndNamespaceMockResources(parsed, namespacePrefix, baseDir, targetMeshDir) {
1015
+ if (!parsed || typeof parsed !== "object") return;
1016
+ if (parsed.volumes && typeof parsed.volumes === "object") {
1017
+ composeConfig.volumes = composeConfig.volumes || {};
1018
+ for (const [volKey, volDef] of Object.entries(parsed.volumes)) {
1019
+ const namespacedVolKey = `${namespacePrefix}_${volKey}`;
1020
+ composeConfig.volumes[namespacedVolKey] = volDef ?? {};
1021
+ if (parsed.services && typeof parsed.services === "object") {
1022
+ for (const svc of Object.values(parsed.services)) {
1023
+ rewriteServiceVolume(svc, volKey, namespacedVolKey);
1024
+ }
1025
+ }
1026
+ }
1027
+ }
1028
+ if (parsed.secrets && typeof parsed.secrets === "object") {
1029
+ composeConfig.secrets = composeConfig.secrets || {};
1030
+ for (const [secKey, secDef] of Object.entries(parsed.secrets)) {
1031
+ const namespacedSecKey = `${namespacePrefix}_${secKey}`;
1032
+ const clonedDef = { ...secDef };
1033
+ if (clonedDef.file) {
1034
+ clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1035
+ }
1036
+ composeConfig.secrets[namespacedSecKey] = clonedDef;
1037
+ if (parsed.services && typeof parsed.services === "object") {
1038
+ for (const svc of Object.values(parsed.services)) {
1039
+ rewriteServiceSecret(svc, secKey, namespacedSecKey);
1040
+ }
1041
+ }
1042
+ }
1043
+ }
1044
+ if (parsed.configs && typeof parsed.configs === "object") {
1045
+ composeConfig.configs = composeConfig.configs || {};
1046
+ for (const [cfgKey, cfgDef] of Object.entries(parsed.configs)) {
1047
+ const namespacedCfgKey = `${namespacePrefix}_${cfgKey}`;
1048
+ const clonedDef = { ...cfgDef };
1049
+ if (clonedDef.file) {
1050
+ clonedDef.file = toComposePath(targetMeshDir, path13.resolve(baseDir, clonedDef.file));
1051
+ }
1052
+ composeConfig.configs[namespacedCfgKey] = clonedDef;
1053
+ if (parsed.services && typeof parsed.services === "object") {
1054
+ for (const svc of Object.values(parsed.services)) {
1055
+ rewriteServiceConfig(svc, cfgKey, namespacedCfgKey);
1056
+ }
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+ function applyInternalMockDependsOnMapping(svc, mapping) {
1062
+ if (!svc.depends_on) return;
1063
+ if (Array.isArray(svc.depends_on)) {
1064
+ svc.depends_on = svc.depends_on.map((d) => mapping.get(d) || d);
1065
+ } else if (typeof svc.depends_on === "object") {
1066
+ const newDepends = {};
1067
+ for (const [k, v] of Object.entries(svc.depends_on)) {
1068
+ newDepends[mapping.get(k) || k] = v;
1069
+ }
1070
+ svc.depends_on = newDepends;
1071
+ }
1072
+ }
1073
+ function registerService(key, serviceDef, origin) {
1074
+ if (composeConfig.services[key]) {
1075
+ throw new ScriptError(
1076
+ `Service name collision in mesh compose configuration: Service "${key}" from ${origin} conflicts with an existing service definition.`
1077
+ );
1078
+ }
1079
+ composeConfig.services[key] = serviceDef;
1080
+ }
1081
+ for (const serviceName of Object.keys(mesh.services)) {
1082
+ composeConfig.networks[`${serviceName}_net`] = {};
1083
+ }
1084
+ if (mesh.dependencies && typeof mesh.dependencies === "object") {
1085
+ for (const [depKey, depDef] of Object.entries(mesh.dependencies)) {
1086
+ const depComposePath = path13.resolve(meshDir, depDef.path);
1087
+ if (!existsSync(depComposePath)) {
1088
+ throw new ScriptError(
1089
+ `Root dependency compose file not found: ${depComposePath}`
1090
+ );
1091
+ }
1092
+ const raw = readFileSync(depComposePath, "utf-8");
1093
+ const parsed = parse(raw);
1094
+ if (!parsed?.services || typeof parsed.services !== "object") {
1095
+ throw new ScriptError(
1096
+ `Root dependency compose file "${depDef.path}" does not define any services.`
1097
+ );
1098
+ }
1099
+ mergeAndNamespaceMockResources(parsed, `mesh_${depKey}`, meshDir, meshDir);
1100
+ const targetServiceName = depDef.service || Object.keys(parsed.services)[0];
1101
+ const serviceEntry = targetServiceName ? parsed.services[targetServiceName] : void 0;
1102
+ if (!serviceEntry) {
1103
+ throw new ScriptError(
1104
+ `Service "${targetServiceName}" not found in root dependency compose file: ${depComposePath}`
1105
+ );
1106
+ }
1107
+ const sidecarMapping = /* @__PURE__ */ new Map();
1108
+ for (const sName of Object.keys(parsed.services)) {
1109
+ if (sName === targetServiceName) {
1110
+ sidecarMapping.set(sName, depKey);
1111
+ } else {
1112
+ const companionKey = `${depKey}-${sName}`;
1113
+ sidecarMapping.set(sName, composeConfig.services[sName] ? companionKey : sName);
1114
+ }
1115
+ }
1116
+ const resolvedService = resolveServicePaths(serviceEntry, meshDir, meshDir);
1117
+ delete resolvedService.container_name;
1118
+ normalizeDependsOn(resolvedService);
1119
+ applyInternalMockDependsOnMapping(resolvedService, sidecarMapping);
1120
+ resolvedService.networks = {
1121
+ mesh: {
1122
+ aliases: [depKey, targetServiceName].filter(Boolean)
1123
+ }
1124
+ };
1125
+ registerService(depKey, resolvedService, `root dependency "${depKey}"`);
1126
+ for (const [sName, sDef] of Object.entries(parsed.services)) {
1127
+ if (sName !== targetServiceName) {
1128
+ const finalKey = sidecarMapping.get(sName);
1129
+ const companion = resolveServicePaths(sDef, meshDir, meshDir);
1130
+ delete companion.container_name;
1131
+ normalizeDependsOn(companion);
1132
+ applyInternalMockDependsOnMapping(companion, sidecarMapping);
1133
+ companion.networks = {
1134
+ mesh: {
1135
+ aliases: [sName, finalKey]
1136
+ }
1137
+ };
1138
+ registerService(finalKey, companion, `companion of root dependency "${depKey}"`);
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1143
+ const providerAliases = /* @__PURE__ */ new Map();
1144
+ for (const sName of Object.keys(mesh.services)) {
1145
+ providerAliases.set(sName, /* @__PURE__ */ new Set());
1146
+ }
1147
+ const globalDepAliasToProvider = /* @__PURE__ */ new Map();
1148
+ for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
1149
+ const serviceDir = path13.resolve(meshDir, serviceConfig.path);
1150
+ const serviceBuildJson = getBuildJson(serviceDir);
1151
+ const serviceOverrides = extractOverrides(serviceBuildJson, serviceDir);
1152
+ const serviceDeps = extractBuildDeps(serviceBuildJson, serviceDir);
1153
+ const relServiceDir = toComposePath(meshDir, serviceDir);
1154
+ const dockerfile = serviceBuildJson.dockerfile || "Dockerfile";
1155
+ const environment = {
1156
+ INFRA_MODE: "integrated",
1157
+ EXEC_MODE: mode
1158
+ };
1159
+ if (serviceConfig.port) {
1160
+ environment.PORT = String(serviceConfig.port);
1161
+ }
1162
+ let overrideVolumes = [];
1163
+ let overrideHealthcheck = void 0;
1164
+ let overrideCommand = void 0;
1165
+ const stageOverride = serviceOverrides[mode];
1166
+ if (stageOverride && existsSync(stageOverride.path)) {
1167
+ try {
1168
+ const overrideYaml = parse(readFileSync(stageOverride.path, "utf-8"));
1169
+ mergeTopLevelResources(overrideYaml);
1170
+ const overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
1171
+ if (!overrideApp && overrideYaml?.services && Object.keys(overrideYaml.services).length > 0) {
1172
+ throw new ScriptError(
1173
+ `Override file "${stageOverride.path}" must define service "app" or "${serviceName}".`
1174
+ );
1175
+ }
1176
+ if (overrideApp) {
1177
+ if (Array.isArray(overrideApp.environment)) {
1178
+ for (const item of overrideApp.environment) {
1179
+ const eqIdx = item.indexOf("=");
1180
+ if (eqIdx !== -1) {
1181
+ environment[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1182
+ } else {
1183
+ environment[item] = process.env[item] ?? null;
1184
+ }
1185
+ }
1186
+ } else if (overrideApp.environment && typeof overrideApp.environment === "object") {
1187
+ Object.assign(environment, overrideApp.environment);
1188
+ }
1189
+ if (overrideApp.command) {
1190
+ overrideCommand = overrideApp.command;
1191
+ }
1192
+ if (Array.isArray(overrideApp.volumes)) {
1193
+ overrideVolumes = overrideApp.volumes.map(
1194
+ (vol) => resolveVolumeEntry(vol, serviceDir, meshDir)
1195
+ );
1196
+ }
1197
+ if (overrideApp.healthcheck) {
1198
+ overrideHealthcheck = overrideApp.healthcheck;
1199
+ }
1200
+ }
1201
+ } catch (err) {
1202
+ if (err instanceof ScriptError) throw err;
1203
+ const msg = err instanceof Error ? err.message : String(err);
1204
+ throw new ScriptError(
1205
+ `Failed to parse override file ${stageOverride.path}: ${msg}`
1206
+ );
1207
+ }
1208
+ }
1209
+ if (serviceConfig.envOverrides) {
1210
+ Object.assign(environment, serviceConfig.envOverrides);
1211
+ }
1212
+ const dockerfilePath = path13.resolve(serviceDir, dockerfile);
1213
+ const envFilePort = extractPortFromEnvFile(path13.resolve(serviceDir, `.env.${mode}`)) || extractPortFromEnvFile(path13.resolve(serviceDir, ".env"));
1214
+ const dockerfilePort = extractPortFromDockerfile(dockerfilePath);
1215
+ const resolvedPort = serviceConfig.port || serviceConfig.healthcheck?.port || (environment.PORT ? parseInt(String(environment.PORT), 10) : void 0) || envFilePort || dockerfilePort || 3e3;
1216
+ if (!environment.PORT) {
1217
+ environment.PORT = String(resolvedPort);
1218
+ }
1219
+ const serviceDef = {
1220
+ build: {
1221
+ context: relServiceDir,
1222
+ dockerfile,
1223
+ target: mode
1224
+ },
1225
+ init: true,
1226
+ logging: {
1227
+ driver: "json-file",
1228
+ options: {
1229
+ "max-size": "10m",
1230
+ "max-file": "3"
1231
+ }
1232
+ },
1233
+ environment,
1234
+ depends_on: {}
1235
+ };
1236
+ const envFilePath = path13.resolve(serviceDir, `.env.${mode}`);
1237
+ if (existsSync(envFilePath)) {
1238
+ serviceDef.env_file = [toComposePath(meshDir, envFilePath)];
1239
+ }
1240
+ if (mode === "dev") {
1241
+ const volSet = /* @__PURE__ */ new Set();
1242
+ volSet.add(`${relServiceDir}:/app`);
1243
+ volSet.add("/app/node_modules");
1244
+ for (const v of overrideVolumes) {
1245
+ if (typeof v === "string") {
1246
+ volSet.add(v);
1247
+ }
1248
+ }
1249
+ serviceDef.volumes = Array.from(volSet);
1250
+ }
1251
+ if (serviceConfig.port) {
1252
+ serviceDef.ports = [`${serviceConfig.port}:${serviceConfig.port}`];
1253
+ }
1254
+ if (overrideCommand) {
1255
+ serviceDef.command = overrideCommand;
1256
+ }
1257
+ if (serviceConfig.healthcheck) {
1258
+ if (serviceConfig.healthcheck.type === "tcp") {
1259
+ const hcPort = serviceConfig.healthcheck.port || resolvedPort;
1260
+ serviceDef.healthcheck = {
1261
+ test: [
1262
+ "CMD-SHELL",
1263
+ `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`
1264
+ ],
1265
+ interval: "2s",
1266
+ timeout: "2s",
1267
+ start_period: "3s",
1268
+ retries: 10
1269
+ };
1270
+ } else {
1271
+ serviceDef.healthcheck = serviceConfig.healthcheck;
1272
+ }
1273
+ } else if (overrideHealthcheck) {
1274
+ serviceDef.healthcheck = overrideHealthcheck;
1275
+ } else {
1276
+ const portValue = resolvedPort;
1277
+ serviceDef.healthcheck = {
1278
+ test: [
1279
+ "CMD-SHELL",
1280
+ `nc -z 127.0.0.1 ${portValue} || node -e "require('net').connect(${portValue},'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))" || exit 1`
1281
+ ],
1282
+ interval: "2s",
1283
+ timeout: "2s",
1284
+ start_period: "3s",
1285
+ retries: 10
1286
+ };
1287
+ }
1288
+ const namespacedAppKey = `${serviceName}-app`;
1289
+ serviceDef.networks = {
1290
+ mesh: {
1291
+ aliases: [serviceName, namespacedAppKey]
1292
+ },
1293
+ [`${serviceName}_net`]: {
1294
+ aliases: ["app", serviceName, namespacedAppKey]
1295
+ }
1296
+ };
1297
+ const provideMap = {
1298
+ ...serviceConfig.replaceMocks || {},
1299
+ ...serviceConfig.provideDependency || {}
1300
+ };
1301
+ const declaredDepNames = new Set(serviceDeps.map((d) => d.name));
1302
+ for (const [depKey, targetProvider] of Object.entries(provideMap)) {
1303
+ if (!declaredDepNames.has(depKey)) {
1304
+ throw new ScriptError(
1305
+ `Service "${serviceName}" declares provideDependency/replaceMocks for "${depKey}", but "${depKey}" is not declared in its build.json dependencies.`
1306
+ );
1307
+ }
1308
+ if (!mesh.services[targetProvider]) {
1309
+ throw new ScriptError(
1310
+ `Service "${serviceName}" maps dependency "${depKey}" to nonexistent service "${targetProvider}".`
1311
+ );
1312
+ }
1313
+ if (globalDepAliasToProvider.has(depKey) && globalDepAliasToProvider.get(depKey) !== targetProvider) {
1314
+ throw new ScriptError(
1315
+ `Dependency alias collision: Dependency key "${depKey}" is mapped to multiple different provider services ("${globalDepAliasToProvider.get(
1316
+ depKey
1317
+ )}" and "${targetProvider}").`
1318
+ );
1319
+ }
1320
+ if (mesh.services[depKey] && depKey !== targetProvider) {
1321
+ throw new ScriptError(
1322
+ `Dependency alias conflict: Dependency key "${depKey}" collides with declared mesh service "${depKey}".`
1323
+ );
1324
+ }
1325
+ globalDepAliasToProvider.set(depKey, targetProvider);
1326
+ }
1327
+ for (const dep of serviceDeps) {
1328
+ const depKey = dep.name;
1329
+ if (provideMap[depKey]) {
1330
+ const fellowService = provideMap[depKey];
1331
+ const fellowAppKey = `${fellowService}-app`;
1332
+ serviceDef.depends_on[fellowAppKey] = {
1333
+ condition: "service_healthy"
1334
+ };
1335
+ providerAliases.get(fellowService)?.add(depKey);
1336
+ } else if (mesh.dependencies && mesh.dependencies[depKey]) {
1337
+ serviceDef.depends_on[depKey] = {
1338
+ condition: "service_healthy"
1339
+ };
1340
+ } else {
1341
+ const namespacedDepKey = `${serviceName}-${depKey}`;
1342
+ serviceDef.depends_on[namespacedDepKey] = {
1343
+ condition: "service_healthy"
1344
+ };
1345
+ const depComposePath = dep.path;
1346
+ if (!existsSync(depComposePath)) {
1347
+ throw new ScriptError(
1348
+ `Mock compose file for dependency "${depKey}" not found: ${depComposePath}`
1349
+ );
1350
+ }
1351
+ const raw = readFileSync(depComposePath, "utf-8");
1352
+ const parsed = parse(raw);
1353
+ if (!parsed?.services || typeof parsed.services !== "object") {
1354
+ throw new ScriptError(
1355
+ `Invalid compose file for dependency "${depKey}": missing "services"`
1356
+ );
1357
+ }
1358
+ mergeAndNamespaceMockResources(parsed, `${serviceName}_${depKey}`, serviceDir, meshDir);
1359
+ if (dep.serviceName && !parsed.services[dep.serviceName]) {
1360
+ throw new ScriptError(
1361
+ `Service "${dep.serviceName}" declared in build.json not found in mock compose ${depComposePath}`
1362
+ );
1363
+ }
1364
+ const targetMockService = dep.serviceName ? parsed.services[dep.serviceName] : Object.values(parsed.services)[0];
1365
+ if (!targetMockService) {
1366
+ throw new ScriptError(
1367
+ `No services found in mock compose ${depComposePath}`
1368
+ );
1369
+ }
1370
+ const sidecarMapping = /* @__PURE__ */ new Map();
1371
+ for (const mName of Object.keys(parsed.services)) {
1372
+ if (parsed.services[mName] === targetMockService) {
1373
+ sidecarMapping.set(mName, namespacedDepKey);
1374
+ } else {
1375
+ sidecarMapping.set(mName, `${serviceName}-${mName}`);
1376
+ }
1377
+ }
1378
+ const resolvedMock = resolveServicePaths(
1379
+ targetMockService,
1380
+ serviceDir,
1381
+ meshDir
1382
+ );
1383
+ delete resolvedMock.ports;
1384
+ delete resolvedMock.container_name;
1385
+ normalizeDependsOn(resolvedMock);
1386
+ applyInternalMockDependsOnMapping(resolvedMock, sidecarMapping);
1387
+ resolvedMock.networks = {
1388
+ [`${serviceName}_net`]: {
1389
+ aliases: [depKey, namespacedDepKey]
1390
+ }
1391
+ };
1392
+ registerService(namespacedDepKey, resolvedMock, `mock dependency for "${serviceName}"`);
1393
+ for (const [mName, mDef] of Object.entries(parsed.services)) {
1394
+ if (mDef !== targetMockService) {
1395
+ const sidecarKey = sidecarMapping.get(mName);
1396
+ if (!composeConfig.services[sidecarKey]) {
1397
+ const resolvedSidecar = resolveServicePaths(mDef, serviceDir, meshDir);
1398
+ delete resolvedSidecar.ports;
1399
+ delete resolvedSidecar.container_name;
1400
+ normalizeDependsOn(resolvedSidecar);
1401
+ applyInternalMockDependsOnMapping(resolvedSidecar, sidecarMapping);
1402
+ resolvedSidecar.networks = {
1403
+ [`${serviceName}_net`]: {
1404
+ aliases: [mName, sidecarKey]
1405
+ }
1406
+ };
1407
+ registerService(sidecarKey, resolvedSidecar, `sidecar of mock "${depKey}"`);
1408
+ }
1409
+ }
1410
+ }
1411
+ }
1412
+ }
1413
+ if (Object.keys(serviceDef.depends_on).length === 0) {
1414
+ delete serviceDef.depends_on;
1415
+ }
1416
+ registerService(namespacedAppKey, serviceDef, `mesh service "${serviceName}"`);
1417
+ }
1418
+ for (const [providerName, aliases] of providerAliases.entries()) {
1419
+ const appKey = `${providerName}-app`;
1420
+ const serviceDef = composeConfig.services[appKey];
1421
+ if (serviceDef && serviceDef.networks?.mesh) {
1422
+ const existingAliases = new Set(serviceDef.networks.mesh.aliases || []);
1423
+ for (const alias of aliases) {
1424
+ existingAliases.add(alias);
1425
+ }
1426
+ serviceDef.networks.mesh.aliases = Array.from(existingAliases);
1427
+ }
1428
+ }
1429
+ let testerServiceName;
1430
+ if (options.includeTester && mesh.tester) {
1431
+ const testerDir = path13.resolve(meshDir, mesh.tester.path);
1432
+ const composeRel = mesh.tester.compose || "docker-compose.yml";
1433
+ const testerComposePath = path13.resolve(testerDir, composeRel);
1434
+ if (existsSync(testerComposePath)) {
1435
+ const raw = readFileSync(testerComposePath, "utf-8");
1436
+ const parsed = parse(raw);
1437
+ mergeTopLevelResources(parsed);
1438
+ if (parsed?.services && typeof parsed.services === "object") {
1439
+ const firstKey = Object.keys(parsed.services)[0];
1440
+ if (firstKey && parsed.services[firstKey]) {
1441
+ testerServiceName = firstKey;
1442
+ for (const [tKey, tDef] of Object.entries(parsed.services)) {
1443
+ const resolvedTester = resolveServicePaths(
1444
+ tDef,
1445
+ testerDir,
1446
+ meshDir
1447
+ );
1448
+ delete resolvedTester.container_name;
1449
+ normalizeDependsOn(resolvedTester);
1450
+ resolvedTester.networks = {
1451
+ mesh: {
1452
+ aliases: [tKey, ...tKey === firstKey ? ["tester"] : []]
1453
+ }
1454
+ };
1455
+ if (tKey === firstKey) {
1456
+ resolvedTester.depends_on = resolvedTester.depends_on || {};
1457
+ for (const sName of Object.keys(mesh.services)) {
1458
+ resolvedTester.depends_on[`${sName}-app`] = {
1459
+ condition: "service_healthy"
1460
+ };
1461
+ }
1462
+ }
1463
+ registerService(tKey, resolvedTester, `tester service "${tKey}"`);
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+ }
1469
+ for (const svc of Object.values(composeConfig.services)) {
1470
+ if (svc.depends_on && typeof svc.depends_on === "object") {
1471
+ for (const [depTarget, depOpts] of Object.entries(svc.depends_on)) {
1472
+ const targetSvc = composeConfig.services[depTarget];
1473
+ if (targetSvc && (!targetSvc.healthcheck || targetSvc.healthcheck.disable) && depOpts && depOpts.condition === "service_healthy") {
1474
+ depOpts.condition = "service_started";
1475
+ }
1476
+ }
1477
+ }
1478
+ }
1479
+ const generatedYaml = stringify(composeConfig);
1480
+ if (options.validateWithDocker === false) {
1481
+ return { yaml: generatedYaml, testerServiceName };
1482
+ }
1483
+ const result = spawnSync(
1484
+ "docker",
1485
+ [
1486
+ "compose",
1487
+ "-p",
1488
+ projectName,
1489
+ "--project-directory",
1490
+ meshDir,
1491
+ "-f",
1492
+ "-",
1493
+ "config"
1494
+ ],
1495
+ {
1496
+ cwd: meshDir,
1497
+ input: generatedYaml,
1498
+ encoding: "utf-8"
1499
+ }
1500
+ );
1501
+ if (result.error) {
1502
+ throw new ScriptError(
1503
+ `Failed to run docker compose config: ${result.error.message}`,
1504
+ { cause: result.error }
1505
+ );
1506
+ }
1507
+ if (result.status !== 0) {
1508
+ throw new ScriptError(
1509
+ `\u274C Failed to validate mesh compose configuration:
1510
+ ${result.stderr || result.stdout}`
1511
+ );
1512
+ }
1513
+ return {
1514
+ yaml: result.stdout || generatedYaml,
1515
+ testerServiceName
1516
+ };
1517
+ }
1518
+ function resolveVolumeEntry(vol, baseDir, meshDir) {
1519
+ if (typeof vol === "string") {
1520
+ if (!vol.includes(":")) {
1521
+ return vol;
1522
+ }
1523
+ const parts = vol.split(":");
1524
+ const host = parts[0];
1525
+ if (isBindMount(host)) {
1526
+ const absHost = path13.resolve(baseDir, host);
1527
+ const formattedRel = toComposePath(meshDir, absHost);
1528
+ return `${formattedRel}:${parts.slice(1).join(":")}`;
1529
+ }
1530
+ return vol;
1531
+ }
1532
+ if (vol && typeof vol === "object") {
1533
+ const cloned = { ...vol };
1534
+ if (cloned.type === "bind" && cloned.source && typeof cloned.source === "string") {
1535
+ const absSource = path13.resolve(baseDir, cloned.source);
1536
+ cloned.source = toComposePath(meshDir, absSource);
1537
+ }
1538
+ return cloned;
1539
+ }
1540
+ return vol;
1541
+ }
1542
+ function resolveServicePaths(service, baseDir, meshDir) {
1543
+ const cloned = JSON.parse(JSON.stringify(service));
1544
+ if (cloned.build) {
1545
+ if (typeof cloned.build === "string") {
1546
+ cloned.build = toComposePath(meshDir, path13.resolve(baseDir, cloned.build));
1547
+ } else if (cloned.build.context) {
1548
+ cloned.build.context = toComposePath(
1549
+ meshDir,
1550
+ path13.resolve(baseDir, cloned.build.context)
1551
+ );
1552
+ }
1553
+ }
1554
+ if (Array.isArray(cloned.volumes)) {
1555
+ cloned.volumes = cloned.volumes.map(
1556
+ (vol) => resolveVolumeEntry(vol, baseDir, meshDir)
1557
+ );
1558
+ }
1559
+ if (Array.isArray(cloned.env_file)) {
1560
+ cloned.env_file = cloned.env_file.map((ef) => {
1561
+ if (typeof ef === "string") {
1562
+ return toComposePath(meshDir, path13.resolve(baseDir, ef));
1563
+ }
1564
+ if (ef && typeof ef === "object" && ef.path) {
1565
+ return {
1566
+ ...ef,
1567
+ path: toComposePath(meshDir, path13.resolve(baseDir, ef.path))
1568
+ };
1569
+ }
1570
+ return ef;
1571
+ });
1572
+ } else if (typeof cloned.env_file === "string") {
1573
+ cloned.env_file = toComposePath(meshDir, path13.resolve(baseDir, cloned.env_file));
1574
+ }
1575
+ normalizeDependsOn(cloned);
1576
+ return cloned;
1577
+ }
1578
+ function extractPortFromEnvFile(filePath) {
1579
+ if (!existsSync(filePath)) return void 0;
1580
+ try {
1581
+ const content = readFileSync(filePath, "utf-8");
1582
+ for (const line of content.split("\n")) {
1583
+ const trimmed = line.trim();
1584
+ if (trimmed.startsWith("#") || !trimmed.includes("=")) continue;
1585
+ const [k, ...vParts] = trimmed.split("=");
1586
+ if (k && k.trim() === "PORT") {
1587
+ const rawVal = vParts.join("=").trim().replace(/^["']|["']$/g, "");
1588
+ const val = parseInt(rawVal, 10);
1589
+ if (!isNaN(val) && val > 0) return val;
1590
+ }
1591
+ }
1592
+ } catch {
1593
+ }
1594
+ return void 0;
1595
+ }
1596
+ function extractPortFromDockerfile(dockerfilePath) {
1597
+ if (!existsSync(dockerfilePath)) return void 0;
1598
+ try {
1599
+ const content = readFileSync(dockerfilePath, "utf-8");
1600
+ const portMatch = content.match(/process\.env\.PORT\s*\|\|\s*(\d+)/) || content.match(/EXPOSE\s+(\d+)/);
1601
+ if (portMatch && portMatch[1]) {
1602
+ const val = parseInt(portMatch[1], 10);
1603
+ if (!isNaN(val) && val > 0) return val;
1604
+ }
1605
+ } catch {
1606
+ }
1607
+ return void 0;
1608
+ }
1609
+ var activeComposeSet = /* @__PURE__ */ new Set();
1610
+ var signalHandlersRegistered = false;
1611
+ var activeChildProcess = null;
1612
+ var isTearingDown = false;
1613
+ var isShuttingDown = false;
1614
+ var isProcessAlive = (c) => {
1615
+ return Boolean(c && c.exitCode === null && c.signalCode === null);
1616
+ };
1617
+ function setActiveChild(child) {
1618
+ activeChildProcess = child;
1619
+ if (!child) {
1620
+ isShuttingDown = false;
1621
+ }
1622
+ }
1623
+ function setTearingDown(tearingDown) {
1624
+ isTearingDown = tearingDown;
1625
+ }
1626
+ function registerActiveCompose(yamlConfig, projectDir, options = {}) {
1627
+ const entry = {
1628
+ yamlConfig,
1629
+ projectDir,
1630
+ removeVolumes: options.removeVolumes
1631
+ };
1632
+ activeComposeSet.add(entry);
1633
+ ensureSignalHandlers();
1634
+ return () => {
1635
+ activeComposeSet.delete(entry);
1636
+ };
1637
+ }
1638
+ function ensureSignalHandlers() {
1639
+ if (signalHandlersRegistered) return;
1640
+ signalHandlersRegistered = true;
1641
+ const handleSignal = (signal) => {
1642
+ if (isTearingDown) {
1643
+ return;
1644
+ }
1645
+ if (activeChildProcess && isProcessAlive(activeChildProcess)) {
1646
+ const child = activeChildProcess;
1647
+ if (signal === "SIGINT") {
1648
+ if (!isShuttingDown) {
1649
+ isShuttingDown = true;
1650
+ setTimeout(() => {
1651
+ if (isProcessAlive(child)) {
1652
+ try {
1653
+ child.kill("SIGKILL");
1654
+ } catch {
1655
+ }
1656
+ }
1657
+ }, 1e4).unref();
1658
+ return;
1659
+ }
1660
+ try {
1661
+ child.kill("SIGINT");
1662
+ } catch {
1663
+ }
1664
+ return;
1665
+ }
1666
+ try {
1667
+ child.kill(signal);
1668
+ } catch {
1669
+ }
1670
+ setTimeout(() => {
1671
+ if (isProcessAlive(child)) {
1672
+ try {
1673
+ child.kill("SIGKILL");
1674
+ } catch {
1675
+ }
1676
+ }
1677
+ }, 1e4).unref();
1678
+ return;
1679
+ }
1680
+ if (isShuttingDown) return;
1681
+ isShuttingDown = true;
1682
+ for (const item of activeComposeSet) {
1683
+ try {
1684
+ teardownCompose(item.yamlConfig, item.projectDir, {
1685
+ removeVolumes: item.removeVolumes ?? false
1686
+ }).catch(() => {
1687
+ });
1688
+ } catch {
1689
+ }
1690
+ }
1691
+ activeComposeSet.clear();
1692
+ const signalNumber = os.constants.signals[signal] ?? 0;
1693
+ process.exit(128 + signalNumber);
1694
+ };
1695
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1696
+ for (const sig of SIGNALS) {
1697
+ const listener = () => handleSignal(sig);
1698
+ process.on(sig, listener);
1699
+ }
1700
+ }
1701
+
1702
+ // src/core/teardownCompose.ts
1703
+ function runSpawn(executable, args, cwd, input, silent = false, timeoutMs = 6e4) {
1704
+ return new Promise((resolve) => {
1705
+ let child;
1706
+ try {
1707
+ child = spawn(executable, args, {
1708
+ cwd,
1709
+ stdio: [
1710
+ input ? "pipe" : "ignore",
1711
+ silent ? "ignore" : "inherit",
1712
+ silent ? "ignore" : "inherit"
1713
+ ]
1714
+ });
1715
+ } catch (err) {
1716
+ return resolve({ status: null, error: err });
1717
+ }
1718
+ let timer = null;
1719
+ if (timeoutMs) {
1720
+ timer = setTimeout(() => {
1721
+ try {
1722
+ child.kill("SIGKILL");
1723
+ } catch {
1724
+ }
1725
+ resolve({
1726
+ status: null,
1727
+ error: new Error(`Teardown timed out after ${timeoutMs}ms`)
1728
+ });
1729
+ }, timeoutMs);
1730
+ timer.unref();
1731
+ }
1732
+ if (input && child.stdin) {
1733
+ child.stdin.on("error", () => {
1734
+ });
1735
+ child.stdin.write(input);
1736
+ child.stdin.end();
1737
+ }
1738
+ child.on("error", (err) => {
1739
+ if (timer) clearTimeout(timer);
1740
+ resolve({ status: null, error: err });
1741
+ });
1742
+ child.on("close", (code) => {
1743
+ if (timer) clearTimeout(timer);
1744
+ resolve({ status: code });
1745
+ });
1746
+ });
1747
+ }
1748
+ async function teardownCompose(yamlConfig, projectDir, options = {}) {
1749
+ const absProjectDir = resolveProjectDir(projectDir);
1750
+ const removeVolumes = options.removeVolumes ?? true;
1751
+ const silent = Boolean(options.silent);
1752
+ setTearingDown(true);
1753
+ try {
1754
+ const baseArgs = ["compose"];
1755
+ if (options.projectName) {
1756
+ baseArgs.push("-p", options.projectName);
1757
+ } else {
1758
+ baseArgs.push("--project-directory", absProjectDir, "-f", "-");
1759
+ }
1760
+ const inputData = options.projectName ? void 0 : yamlConfig;
1761
+ if (!removeVolumes) {
1762
+ const rmArgs = [...baseArgs, "rm", "-f", "-v", "app"];
1763
+ await runSpawn("docker", rmArgs, absProjectDir, inputData, true, 15e3);
1764
+ }
1765
+ const downArgs = [...baseArgs, "down"];
1766
+ if (removeVolumes) {
1767
+ downArgs.push("-v");
1768
+ }
1769
+ downArgs.push("--remove-orphans");
1770
+ let result = await runSpawn(
1771
+ "docker",
1772
+ downArgs,
1773
+ absProjectDir,
1774
+ inputData,
1775
+ silent,
1776
+ 6e4
1777
+ );
1778
+ if (result.error || result.status !== 0) {
1779
+ await new Promise((r) => setTimeout(r, 1e3));
1780
+ result = await runSpawn(
1781
+ "docker",
1782
+ downArgs,
1783
+ absProjectDir,
1784
+ inputData,
1785
+ silent,
1786
+ 6e4
1787
+ );
1788
+ }
1789
+ if (result.error) {
1790
+ if (!silent) {
1791
+ console.error(
1792
+ pc20.red(`Failed to run docker compose down: ${result.error.message}`)
1793
+ );
1794
+ }
1795
+ } else if (result.status !== 0 && !silent) {
1796
+ console.error(
1797
+ pc20.red(
1798
+ `Docker compose down exited with non-zero status code: ${result.status}`
1799
+ )
1800
+ );
1801
+ }
1802
+ } finally {
1803
+ setTearingDown(false);
1804
+ }
1805
+ }
1806
+
1807
+ // src/utils/redactSecrets.ts
1808
+ function redactYamlSecrets(yamlContent) {
1809
+ let redacted = yamlContent.replace(
1810
+ /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/:\s]+:)([^@\s]+)(@)/g,
1811
+ "$1********$3"
1812
+ );
1813
+ redacted = redacted.replace(
1814
+ /((?:^|[ \t])[A-Za-z0-9_]*(?:SECRET|PASSWORD|PASSWD|TOKEN|CREDENTIAL|_KEY|APIKEY)[A-Za-z0-9_]*[ \t]*[:=][ \t]*)(["']?[^\r\n"']+["']?)/gi,
1815
+ "$1********"
1816
+ );
1817
+ return redacted;
1818
+ }
1819
+ function getRunStatePath(projectDir) {
1820
+ return path13.resolve(resolveProjectDir(projectDir), ".builder", "run.state");
1821
+ }
1822
+ function writeRunState(projectDir, state) {
1823
+ try {
1824
+ const absDir = resolveProjectDir(projectDir);
1825
+ const builderDir = path13.resolve(absDir, ".builder");
1826
+ if (!existsSync(builderDir)) {
1827
+ mkdirSync(builderDir, { recursive: true });
1828
+ }
1829
+ const fullState = {
1830
+ ...state,
1831
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1832
+ };
1833
+ writeFileSync(
1834
+ path13.resolve(builderDir, "run.state"),
1835
+ JSON.stringify(fullState, null, 2),
1836
+ "utf-8"
1837
+ );
1838
+ } catch {
1839
+ }
1840
+ }
1841
+ function readRunState(projectDir) {
1842
+ try {
1843
+ const statePath = getRunStatePath(projectDir);
1844
+ if (!existsSync(statePath)) return null;
1845
+ const content = readFileSync(statePath, "utf-8");
1846
+ return JSON.parse(content);
1847
+ } catch {
1848
+ return null;
1849
+ }
1850
+ }
1851
+ function clearRunState(projectDir) {
1852
+ try {
1853
+ const statePath = getRunStatePath(projectDir);
1854
+ if (existsSync(statePath)) {
1855
+ unlinkSync(statePath);
1856
+ }
1857
+ } catch {
1858
+ }
1859
+ }
1860
+ function projectNamesForServiceStage(projectDir, stage) {
1861
+ const absDir = resolveProjectDir(projectDir);
1862
+ let rawName;
1863
+ try {
1864
+ const buildJson = getBuildJson(absDir);
1865
+ rawName = buildJson.name || path13.basename(absDir);
1866
+ } catch {
1867
+ rawName = path13.basename(absDir);
1868
+ }
1869
+ const s = stage.toLowerCase();
1870
+ if (s === "dev") {
1871
+ return [deriveProjectName(rawName, "dev")];
1872
+ }
1873
+ if (s === "prod") {
1874
+ return [deriveProjectName(rawName, "prod")];
1875
+ }
1876
+ if (s === "test-unit") {
1877
+ return [deriveProjectName(rawName, "test")];
1878
+ }
1879
+ if (s === "test-e2e") {
1880
+ return [deriveProjectName(rawName, "e2e")];
1881
+ }
1882
+ if (s === "test") {
1883
+ return [
1884
+ deriveProjectName(rawName, "test"),
1885
+ deriveProjectName(rawName, "e2e")
1886
+ ];
1887
+ }
1888
+ return [deriveProjectName(rawName, s)];
1889
+ }
1890
+ function projectNamesForMeshStage(meshDir, stage) {
1891
+ const absDir = resolveProjectDir(meshDir);
1892
+ let rawMeshName;
1893
+ let services = {};
1894
+ try {
1895
+ const mesh = getMeshJson(absDir);
1896
+ rawMeshName = mesh.name || path13.basename(absDir);
1897
+ services = mesh.services || {};
1898
+ } catch {
1899
+ rawMeshName = path13.basename(absDir);
1900
+ }
1901
+ const s = stage.toLowerCase();
1902
+ if (s === "dev") {
1903
+ return [deriveProjectName(rawMeshName, "dev")];
1904
+ }
1905
+ if (s === "prod") {
1906
+ return [deriveProjectName(rawMeshName, "prod")];
1907
+ }
1908
+ if (s === "test-e2e") {
1909
+ return [deriveProjectName(rawMeshName, "e2e")];
1910
+ }
1911
+ if (s === "test-unit") {
1912
+ return Object.values(services).map((svc) => {
1913
+ const svcDir = path13.resolve(absDir, svc.path);
1914
+ return projectNamesForServiceStage(svcDir, "test-unit")[0];
1915
+ });
1916
+ }
1917
+ if (s === "test") {
1918
+ const list = [];
1919
+ for (const svc of Object.values(services)) {
1920
+ const svcDir = path13.resolve(absDir, svc.path);
1921
+ list.push(...projectNamesForServiceStage(svcDir, "test"));
1922
+ }
1923
+ list.push(deriveProjectName(rawMeshName, "e2e"));
1924
+ return Array.from(new Set(list));
1925
+ }
1926
+ return [deriveProjectName(rawMeshName, s)];
1927
+ }
1928
+
1929
+ // src/commands/mesh/commands/down/handler.ts
1930
+ async function handleMeshDown(rawStage = "dev", options = {}) {
1931
+ const stage = (rawStage || "dev").toLowerCase();
1932
+ const meshDir = resolveProjectDir(options.projectDir);
1933
+ const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
1934
+ if (!validStages.includes(stage)) {
1935
+ throw new ScriptError(
1936
+ `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
1937
+ );
1938
+ }
1939
+ console.log(
1940
+ pc20.cyan(`
1941
+ \u{1F9F9} Stopping and tearing down global mesh environment [${stage}]...`)
1942
+ );
1943
+ if (options.debug) {
1944
+ try {
1945
+ const mode = stage === "dev" ? "dev" : "prod";
1946
+ const includeTester = stage === "test" || stage === "test-e2e";
1947
+ const { yaml } = compileMeshEnvironment(mode, meshDir, { includeTester });
1948
+ console.log(
1949
+ pc20.yellow("\nFinal merged Mesh YAML configuration:\n"),
1950
+ redactYamlSecrets(yaml)
1951
+ );
1952
+ } catch {
1953
+ }
1954
+ }
1955
+ const runState = readRunState(meshDir);
1956
+ const candidateProjects = projectNamesForMeshStage(meshDir, stage);
1957
+ if (runState?.projectName) {
1958
+ candidateProjects.unshift(runState.projectName);
1959
+ }
1960
+ const uniqueProjects = Array.from(new Set(candidateProjects));
1961
+ for (const proj of uniqueProjects) {
1962
+ await teardownCompose("", meshDir, {
1963
+ projectName: proj,
1964
+ removeVolumes: Boolean(options.volumes)
1965
+ });
1966
+ }
1967
+ clearRunState(meshDir);
1968
+ console.log(
1969
+ pc20.green(`\u2705 Global mesh environment [${stage}] stopped and removed.
1970
+ `)
1971
+ );
1972
+ return 0;
1973
+ }
1974
+
1975
+ // src/commands/mesh/commands/down/command.ts
1976
+ var registerMeshDownCommand = (cmd) => {
1977
+ cmd.command("down [stage]").description(
1978
+ "Stop and remove containers and networks for the global mesh environment (dev, prod, test, test-e2e)"
1979
+ ).option(
1980
+ "-v, --volumes",
1981
+ "Remove named volumes declared in the mesh configuration"
1982
+ ).option(
1983
+ "-C, --project-dir <dir>",
1984
+ "Mesh project directory containing mesh.json (defaults to cwd)"
1985
+ ).option("--debug", "Output the merged Docker Compose YAML configuration").addHelpText(
1986
+ "after",
1987
+ `
1988
+ Examples:
1989
+ $ builder mesh down
1990
+ $ builder mesh down dev
1991
+ $ builder mesh down prod
1992
+ $ builder mesh down -v`
1993
+ ).action(
1994
+ async (stage = "dev", options = {}) => {
1995
+ const exitCode = await handleMeshDown(stage, {
1996
+ projectDir: options.projectDir,
1997
+ volumes: options.volumes,
1998
+ debug: options.debug
1999
+ });
2000
+ if (exitCode !== 0) {
2001
+ process.exit(exitCode);
2002
+ }
2003
+ }
2004
+ );
2005
+ };
2006
+ function extractHostPorts(yamlConfig) {
2007
+ const ports = [];
2008
+ try {
2009
+ const parsed = parse(yamlConfig);
2010
+ if (parsed?.services && typeof parsed.services === "object") {
2011
+ for (const svc of Object.values(parsed.services)) {
2012
+ if (Array.isArray(svc?.ports)) {
2013
+ for (const p of svc.ports) {
2014
+ if (typeof p === "string") {
2015
+ const parts = p.split(":");
2016
+ const hostPort = parts.length > 1 ? parseInt(parts[0], 10) : parseInt(p, 10);
2017
+ if (!isNaN(hostPort)) ports.push(hostPort);
2018
+ } else if (typeof p === "object" && p.published) {
2019
+ const hostPort = parseInt(p.published, 10);
2020
+ if (!isNaN(hostPort)) ports.push(hostPort);
2021
+ }
2022
+ }
2023
+ }
2024
+ }
2025
+ }
2026
+ } catch {
2027
+ }
2028
+ return ports;
2029
+ }
2030
+ async function isPortInUse(port) {
2031
+ return new Promise((resolve) => {
2032
+ const server = net.createServer();
2033
+ server.once("error", (err) => {
2034
+ if (err.code === "EADDRINUSE" || err.code === "EACCES") {
2035
+ resolve(true);
2036
+ } else {
2037
+ resolve(false);
2038
+ }
2039
+ });
2040
+ server.once("listening", () => {
2041
+ server.close(() => resolve(false));
2042
+ });
2043
+ server.listen(port, "0.0.0.0");
2044
+ });
2045
+ }
2046
+ async function checkHostPortCollisions(ports) {
2047
+ for (const port of ports) {
2048
+ if (port > 0 && port < 65536) {
2049
+ const inUse = await isPortInUse(port);
2050
+ if (inUse) {
2051
+ console.warn(
2052
+ pc20.yellow(
2053
+ `
2054
+ \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.
2055
+ `
2056
+ )
2057
+ );
2058
+ }
2059
+ }
2060
+ }
2061
+ }
2062
+ async function runCompose(args, yamlConfig, projectDir, options = {}) {
2063
+ const absProjectDir = resolveProjectDir(projectDir);
2064
+ const unregister = registerActiveCompose(yamlConfig, absProjectDir, {
2065
+ removeVolumes: options.removeVolumes ?? false
2066
+ });
2067
+ return new Promise((resolve, reject) => {
2068
+ let child;
2069
+ try {
2070
+ child = spawn(
2071
+ "docker",
2072
+ ["compose", "--project-directory", absProjectDir, "-f", "-", ...args],
2073
+ {
2074
+ cwd: absProjectDir,
2075
+ stdio: ["pipe", "inherit", "inherit"]
2076
+ }
2077
+ );
2078
+ } catch (err) {
2079
+ unregister();
2080
+ return reject(
2081
+ new ScriptError(`Failed to spawn docker compose: ${err.message}`, {
2082
+ cause: err
2083
+ })
2084
+ );
2085
+ }
2086
+ setActiveChild(child);
2087
+ child.stdin?.on("error", () => {
2088
+ });
2089
+ if (child.stdin) {
2090
+ child.stdin.write(yamlConfig);
2091
+ child.stdin.end();
2092
+ }
2093
+ child.on("error", (err) => {
2094
+ setActiveChild(null);
2095
+ unregister();
2096
+ reject(
2097
+ new ScriptError(`Failed to run docker compose: ${err.message}`, {
2098
+ cause: err
2099
+ })
2100
+ );
2101
+ });
2102
+ child.on("close", (code, signal) => {
2103
+ setActiveChild(null);
2104
+ unregister();
2105
+ if (signal) {
2106
+ const signalNumber = os.constants.signals[signal] ?? 0;
2107
+ resolve(128 + signalNumber);
2108
+ } else {
2109
+ resolve(code ?? 1);
2110
+ }
2111
+ });
2112
+ });
2113
+ }
2114
+
2115
+ // src/core/mesh/runners/runMeshDev.ts
2116
+ async function runMeshDev(options = {}) {
2117
+ const meshDir = resolveProjectDir(options.projectDir);
2118
+ console.log(pc20.cyan(`
2119
+ \u{1F680} Starting Global DEV Mesh Environment...`));
2120
+ if (!options.skipChecks) {
2121
+ checkMesh(meshDir, { requireTester: false });
2122
+ }
2123
+ const { yaml } = compileMeshEnvironment("dev", meshDir);
2124
+ const parsed = parse(yaml);
2125
+ const projectName = parsed?.name || "mesh-dev";
2126
+ if (options.debug) {
2127
+ console.log(
2128
+ pc20.yellow("\nFinal merged Mesh Dev YAML configuration:\n"),
2129
+ redactYamlSecrets(yaml)
2130
+ );
2131
+ }
2132
+ if (options.dryRun) {
2133
+ console.log(pc20.green("Dry run complete. Compose was not started."));
2134
+ return 0;
2135
+ }
2136
+ const hostPorts = extractHostPorts(yaml);
2137
+ await checkHostPortCollisions(hostPorts);
2138
+ writeRunState(meshDir, {
2139
+ projectName,
2140
+ stage: "dev",
2141
+ projectDir: meshDir
2142
+ });
2143
+ const upArgs = ["up", "--build"];
2144
+ if (options.detach) {
2145
+ upArgs.push("-d");
2146
+ }
2147
+ let status = 0;
2148
+ try {
2149
+ status = await runCompose(upArgs, yaml, meshDir, {
2150
+ removeVolumes: false
2151
+ });
2152
+ } finally {
2153
+ if (!options.detach) {
2154
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2155
+ clearRunState(meshDir);
2156
+ }
2157
+ }
2158
+ return status;
2159
+ }
2160
+ async function runMeshProd(options = {}) {
2161
+ const meshDir = resolveProjectDir(options.projectDir);
2162
+ console.log(pc20.cyan(`
2163
+ \u{1F3ED} Starting Global PROD Mesh Environment...`));
2164
+ if (!options.skipChecks) {
2165
+ checkMesh(meshDir, { requireTester: false });
2166
+ }
2167
+ const { yaml } = compileMeshEnvironment("prod", meshDir);
2168
+ const parsed = parse(yaml);
2169
+ const projectName = parsed?.name || "mesh-prod";
2170
+ if (options.debug) {
2171
+ console.log(
2172
+ pc20.yellow("\nFinal merged Mesh Prod YAML configuration:\n"),
2173
+ redactYamlSecrets(yaml)
2174
+ );
2175
+ }
2176
+ if (options.dryRun) {
2177
+ console.log(pc20.green("Dry run complete. Compose was not started."));
2178
+ return 0;
2179
+ }
2180
+ const hostPorts = extractHostPorts(yaml);
2181
+ await checkHostPortCollisions(hostPorts);
2182
+ writeRunState(meshDir, {
2183
+ projectName,
2184
+ stage: "prod",
2185
+ projectDir: meshDir
2186
+ });
2187
+ const upArgs = ["up", "--build"];
2188
+ if (options.detach) {
2189
+ upArgs.push("-d");
2190
+ }
2191
+ let status = 0;
2192
+ try {
2193
+ status = await runCompose(upArgs, yaml, meshDir, {
2194
+ removeVolumes: false
2195
+ });
2196
+ } finally {
2197
+ if (!options.detach) {
2198
+ await teardownCompose(yaml, meshDir, { removeVolumes: false });
2199
+ clearRunState(meshDir);
2200
+ }
2201
+ }
2202
+ return status;
2203
+ }
2204
+
2205
+ // src/utils/ymlMods/addDependenciesToAppService.ts
2206
+ var addDependenciesToAppService = (yml, dependencies) => {
2207
+ if (!yml || !yml.services || !yml.services.app) {
2208
+ throw new ScriptError("Invalid YAML structure. Missing 'services.app' field.");
2209
+ }
2210
+ if (!dependencies || dependencies.length === 0) {
2211
+ return;
2212
+ }
2213
+ normalizeDependsOn(yml.services.app);
2214
+ yml.services.app.depends_on = yml.services.app.depends_on || {};
2215
+ dependencies.forEach((dep) => {
2216
+ const targetSvc = yml.services[dep.name];
2217
+ const hasHealthcheck = Boolean(targetSvc?.healthcheck);
2218
+ yml.services.app.depends_on[dep.name] = {
2219
+ condition: hasHealthcheck ? "service_healthy" : "service_started"
2220
+ };
2221
+ });
2222
+ };
2223
+
2224
+ // src/utils/ymlMods/attachName.ts
2225
+ var attachName = (yml, nameOrBuildJson) => {
2226
+ if (!yml) {
2227
+ throw new ScriptError("Invalid YAML structure. Missing 'yml' field.");
2228
+ }
2229
+ const name = typeof nameOrBuildJson === "string" ? nameOrBuildJson : nameOrBuildJson?.name;
2230
+ if (name) {
2231
+ yml.name = name;
2232
+ }
2233
+ };
2234
+
2235
+ // src/utils/ymlMods/makeE2eDependOnApp.ts
2236
+ var makeE2eDependOnApp = (yml) => {
2237
+ if (!yml || !yml.services) {
2238
+ throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2239
+ }
2240
+ if (!yml.services.tester) {
2241
+ throw new ScriptError("Tester service not found");
2242
+ }
2243
+ if (!yml.services.app) {
2244
+ throw new ScriptError("App service not found");
2245
+ }
2246
+ normalizeDependsOn(yml.services.tester);
2247
+ const appHasHealthcheck = Boolean(yml.services.app?.healthcheck);
2248
+ yml.services.tester.depends_on = {
2249
+ ...yml.services.tester.depends_on || {},
2250
+ app: {
2251
+ condition: appHasHealthcheck ? "service_healthy" : "service_started"
2252
+ }
2253
+ };
2254
+ };
2255
+
2256
+ // src/utils/ymlMods/renameServicesWithDependencies.ts
2257
+ var renameServicesWithDependencies = (yml, dependencies) => {
2258
+ if (!yml || !yml.services || typeof yml.services !== "object") {
2259
+ throw new ScriptError("Invalid YAML structure. Missing 'services' field.");
2260
+ }
2261
+ if (!dependencies || dependencies.length === 0) {
2262
+ return;
2263
+ }
2264
+ const renameMap = /* @__PURE__ */ new Map();
2265
+ for (const dep of dependencies) {
2266
+ if (dep.serviceName && dep.name && dep.serviceName !== dep.name) {
2267
+ renameMap.set(dep.serviceName, dep.name);
2268
+ }
2269
+ }
2270
+ if (renameMap.size === 0) {
2271
+ return;
2272
+ }
2273
+ const currentKeys = new Set(Object.keys(yml.services));
2274
+ for (const [oldName, newName] of renameMap.entries()) {
2275
+ if (currentKeys.has(newName) && !renameMap.has(newName)) {
2276
+ throw new ScriptError(
2277
+ `Service collision: cannot rename "${oldName}" to "${newName}" because a service named "${newName}" already exists in the stack.`
2278
+ );
2279
+ }
2280
+ }
2281
+ const newServices = {};
2282
+ for (const [name, service] of Object.entries(yml.services)) {
2283
+ const targetName = renameMap.get(name) || name;
2284
+ newServices[targetName] = service;
2285
+ }
2286
+ yml.services = newServices;
2287
+ for (const service of Object.values(yml.services)) {
2288
+ if (!service || typeof service !== "object") continue;
2289
+ if (service.depends_on) {
2290
+ if (Array.isArray(service.depends_on)) {
2291
+ service.depends_on = service.depends_on.map(
2292
+ (dep) => renameMap.get(dep) || dep
2293
+ );
2294
+ } else if (typeof service.depends_on === "object") {
2295
+ const updatedDependsOn = {};
2296
+ for (const [depName, depConfig] of Object.entries(service.depends_on)) {
2297
+ const targetDepName = renameMap.get(depName) || depName;
2298
+ updatedDependsOn[targetDepName] = depConfig;
2299
+ }
2300
+ service.depends_on = updatedDependsOn;
2301
+ }
2302
+ }
2303
+ if (Array.isArray(service.links)) {
2304
+ service.links = service.links.map((link) => {
2305
+ const [targetSvc, alias] = link.split(":");
2306
+ if (targetSvc && renameMap.has(targetSvc)) {
2307
+ const newTarget = renameMap.get(targetSvc);
2308
+ return alias ? `${newTarget}:${alias}` : newTarget;
2309
+ }
2310
+ return link;
2311
+ });
2312
+ }
2313
+ if (typeof service.network_mode === "string" && service.network_mode.startsWith("service:")) {
2314
+ const targetSvc = service.network_mode.slice("service:".length);
2315
+ if (renameMap.has(targetSvc)) {
2316
+ service.network_mode = `service:${renameMap.get(targetSvc)}`;
2317
+ }
2318
+ }
2319
+ if (Array.isArray(service.volumes_from)) {
2320
+ service.volumes_from = service.volumes_from.map((vf) => {
2321
+ const [vfSvc, mode] = vf.split(":");
2322
+ if (vfSvc && renameMap.has(vfSvc)) {
2323
+ const newTarget = renameMap.get(vfSvc);
2324
+ return mode ? `${newTarget}:${mode}` : newTarget;
2325
+ }
2326
+ return vf;
2327
+ });
2328
+ }
2329
+ if (service.extends && typeof service.extends === "object") {
2330
+ if (service.extends.service && renameMap.has(service.extends.service)) {
2331
+ service.extends.service = renameMap.get(service.extends.service);
2332
+ }
2333
+ }
2334
+ }
2335
+ };
2336
+ function findServiceDefinersInDeclaredFiles(buildJson, projectDir, serviceName) {
2337
+ const declaredFiles = getDeclaredYamlFiles(buildJson, projectDir);
2338
+ const hits = [];
2339
+ for (const file of declaredFiles) {
2340
+ if (!existsSync(file.absolutePath)) continue;
2341
+ try {
2342
+ const content = readFileSync(file.absolutePath, "utf-8");
2343
+ const parsed = parse(content);
2344
+ if (parsed && typeof parsed === "object" && parsed.services && typeof parsed.services === "object") {
2345
+ const svc = parsed.services[serviceName];
2346
+ if (svc) {
2347
+ const hasImageOrBuild = Boolean(svc.image || svc.build);
2348
+ hits.push(
2349
+ ` - ${file.relativePath} (${file.source})${hasImageOrBuild ? " [defines image/build]" : " [no image/build]"}`
2350
+ );
2351
+ }
2352
+ }
2353
+ } catch {
2354
+ }
2355
+ }
2356
+ return hits;
2357
+ }
2358
+ function explainComposeMergeFailure(buildJson, projectDir, envName, filesUsed, rawOutput) {
2359
+ const lines = [];
2360
+ const serviceMatch = rawOutput.match(
2361
+ /service "([^"]+)" has neither an image nor a build context specified/
2362
+ );
2363
+ const envMissingMatch = /env file .* not found|no such file or directory.*\.env/i.test(rawOutput);
2364
+ const actualComposeFiles = filesUsed.filter(
2365
+ (f) => !f.startsWith("-") && (f.endsWith(".yml") || f.endsWith(".yaml"))
2366
+ );
2367
+ lines.push(`Environment : ${envName}`);
2368
+ lines.push(`Compose files merged :`);
2369
+ if (actualComposeFiles.length > 0) {
2370
+ actualComposeFiles.forEach((f) => lines.push(` - ${f}`));
2371
+ } else {
2372
+ filesUsed.filter((f) => f !== "-f").forEach((f) => lines.push(` - ${f}`));
2373
+ }
2374
+ lines.push("");
2375
+ if (serviceMatch && serviceMatch[1]) {
2376
+ const serviceName = serviceMatch[1];
2377
+ lines.push(
2378
+ `ROOT CAUSE: Service "${serviceName}" is referenced in the merged stack, but none of the files provide an "image:" or "build:".`
2379
+ );
2380
+ lines.push("");
2381
+ lines.push(
2382
+ `Files declared in build.json that define a "${serviceName}:" service block:`
2383
+ );
2384
+ const definers = findServiceDefinersInDeclaredFiles(
2385
+ buildJson,
2386
+ projectDir,
2387
+ serviceName
2388
+ );
2389
+ if (definers.length > 0) {
2390
+ definers.forEach((d) => lines.push(d));
2391
+ } else {
2392
+ lines.push(
2393
+ ` (none found \u2014 check spelling/indentation of "${serviceName}:" in files declared in build.json)`
2394
+ );
2395
+ }
2396
+ lines.push("");
2397
+ lines.push("HOW TO FIX:");
2398
+ lines.push(
2399
+ ` - Ensure the file declaring service "${serviceName}" with an "image:" or "build:" is referenced in build.json under dependencies or overrides.`
2400
+ );
2401
+ } else if (/env_file.*must be a string/i.test(rawOutput)) {
2402
+ lines.push(
2403
+ `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 }.`
2404
+ );
2405
+ lines.push("");
2406
+ lines.push("HOW TO FIX:");
2407
+ lines.push(
2408
+ ` - Upgrade Docker Compose to version 2.24.0 or newer to support modern compose templates.`
2409
+ );
2410
+ } else if (/required variable "?([^"\s]+)"? is missing a value/i.test(rawOutput)) {
2411
+ const varMatch = rawOutput.match(/required variable "?([^"\s]+)"? is missing a value/i);
2412
+ const varName = varMatch ? varMatch[1] : "VARIABLE";
2413
+ lines.push(
2414
+ `ROOT CAUSE: Required environment variable "${varName}" is missing a value.`
2415
+ );
2416
+ lines.push("");
2417
+ lines.push("HOW TO FIX:");
2418
+ lines.push(
2419
+ ` - Define "${varName}" in your shell environment or inside your .env file.`
2420
+ );
2421
+ } else if (/port is already allocated|address already in use/i.test(rawOutput)) {
2422
+ lines.push(
2423
+ `ROOT CAUSE: Host port collision. A requested host port is already allocated or in use by another running process or container.`
2424
+ );
2425
+ lines.push("");
2426
+ lines.push("HOW TO FIX:");
2427
+ lines.push(
2428
+ ` - Stop the conflicting process or container, or change the exposed host port in build.json / compose overrides.`
2429
+ );
2430
+ } else if (envMissingMatch) {
2431
+ lines.push(`ROOT CAUSE: A referenced .env file could not be found.`);
2432
+ lines.push("");
2433
+ lines.push("HOW TO FIX:");
2434
+ lines.push(
2435
+ ` - Create the missing env file at the project root (e.g. .env.dev, .env.prod, .env.test)`
2436
+ );
2437
+ } else {
2438
+ lines.push(
2439
+ "Docker Compose failed to resolve this merged stack. Common causes:"
2440
+ );
2441
+ lines.push(
2442
+ ` - A "\${VAR}" substitution with no default and no value set in the shell or an env_file.`
2443
+ );
2444
+ lines.push(` - A YAML syntax error in one of the files listed in build.json.`);
2445
+ lines.push(` - A duplicate or conflicting key across merged compose files.`);
2446
+ }
2447
+ lines.push("");
2448
+ lines.push("Raw Docker Compose output:");
2449
+ lines.push("-".repeat(60));
2450
+ lines.push(rawOutput.trim());
2451
+ lines.push("-".repeat(60));
2452
+ return lines.join("\n");
2453
+ }
2454
+ var cachedTemplatesDir = null;
2455
+ var lastEnvTemplatesDir = void 0;
2456
+ function getTemplatesDir() {
2457
+ const envVal = process.env.BUILDER_TEMPLATES_DIR;
2458
+ if (envVal !== lastEnvTemplatesDir) {
2459
+ cachedTemplatesDir = null;
2460
+ lastEnvTemplatesDir = envVal;
2461
+ }
2462
+ if (envVal) {
2463
+ const envDir = path13.resolve(envVal);
2464
+ if (!fs.existsSync(envDir) || !fs.existsSync(path13.join(envDir, "docker"))) {
2465
+ throw new ScriptError(
2466
+ `BUILDER_TEMPLATES_DIR is set to "${envVal}" but directory does not exist or lacks a "docker/" subdirectory (resolved: "${envDir}").`
2467
+ );
2468
+ }
2469
+ return envDir;
2470
+ }
2471
+ if (cachedTemplatesDir && fs.existsSync(cachedTemplatesDir)) {
2472
+ return cachedTemplatesDir;
2473
+ }
2474
+ const currentDir = typeof __dirname !== "undefined" ? __dirname : path13.dirname(fileURLToPath(import.meta.url));
2475
+ const candidates = [
2476
+ // When executing compiled output in dist/ (e.g. dist/templates)
2477
+ path13.resolve(currentDir, "templates"),
2478
+ path13.resolve(currentDir, "../templates"),
2479
+ // When executing from src/ (e.g. src/core/templates.ts -> ../../templates)
2480
+ path13.resolve(currentDir, "../../templates"),
2481
+ // Fallback relative to cwd
2482
+ path13.resolve(process.cwd(), "templates")
2483
+ ];
2484
+ for (const cand of candidates) {
2485
+ if (fs.existsSync(cand) && fs.existsSync(path13.join(cand, "docker"))) {
2486
+ cachedTemplatesDir = cand;
2487
+ return cand;
2488
+ }
2489
+ }
2490
+ throw new ScriptError(
2491
+ `Templates directory not found. Searched candidates:
2492
+ ${candidates.join("\n")}`
2493
+ );
2494
+ }
2495
+ function getDockerComposeTemplate(filename) {
2496
+ const templatesDir = getTemplatesDir();
2497
+ const filePath = path13.join(templatesDir, "docker", filename);
2498
+ if (!fs.existsSync(filePath)) {
2499
+ throw new ScriptError(`Docker compose template not found: ${filePath}`);
2500
+ }
2501
+ return filePath;
2502
+ }
2503
+
2504
+ // src/core/compileEnvironment.ts
2505
+ var compileEnvironment = (environment, projectDir = process.cwd()) => {
2506
+ const absProjectDir = resolveProjectDir(projectDir);
2507
+ const buildJson = getBuildJson(absProjectDir);
2508
+ const overrides = extractOverrides(buildJson, absProjectDir);
2509
+ const dependencies = extractBuildDeps(buildJson, absProjectDir);
2510
+ const rawProjectName = buildJson.name || path13.basename(absProjectDir);
2511
+ const projectName = deriveProjectName(rawProjectName, environment);
2512
+ const baseComposePath = getDockerComposeTemplate("docker-compose.base.yml");
2513
+ const composeFlags = [
2514
+ "compose",
2515
+ "-p",
2516
+ projectName,
2517
+ "--project-directory",
2518
+ absProjectDir,
2519
+ "-f",
2520
+ baseComposePath
2521
+ ];
2522
+ const filesUsed = [baseComposePath];
2523
+ const defaultEnv = path13.resolve(absProjectDir, ".env");
2524
+ if (existsSync(defaultEnv)) {
2525
+ composeFlags.push("--env-file", defaultEnv);
2526
+ }
2527
+ if (environment === "e2e") {
2528
+ const prodEnv = path13.resolve(absProjectDir, ".env.prod");
2529
+ if (existsSync(prodEnv)) {
2530
+ composeFlags.push("--env-file", prodEnv);
2531
+ }
2532
+ const e2eEnv = path13.resolve(absProjectDir, ".env.e2e");
2533
+ if (existsSync(e2eEnv)) {
2534
+ composeFlags.push("--env-file", e2eEnv);
2535
+ }
2536
+ } else {
2537
+ const stageEnv = path13.resolve(absProjectDir, `.env.${environment}`);
2538
+ if (existsSync(stageEnv)) {
2539
+ composeFlags.push("--env-file", stageEnv);
2540
+ }
2541
+ }
2542
+ switch (environment) {
2543
+ case "dev": {
2544
+ const devPath = getDockerComposeTemplate("docker-compose.dev.yml");
2545
+ const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2546
+ composeFlags.push("-f", devPath);
2547
+ filesUsed.push(devPath);
2548
+ if (overrides.dev) {
2549
+ composeFlags.push("-f", overrides.dev.path);
2550
+ filesUsed.push(overrides.dev.path);
2551
+ }
2552
+ composeFlags.push("-f", standalonePath);
2553
+ filesUsed.push(standalonePath);
2554
+ break;
2555
+ }
2556
+ case "test": {
2557
+ const testPath = getDockerComposeTemplate("docker-compose.test.yml");
2558
+ composeFlags.push("-f", testPath);
2559
+ filesUsed.push(testPath);
2560
+ if (overrides.test) {
2561
+ composeFlags.push("-f", overrides.test.path);
2562
+ filesUsed.push(overrides.test.path);
2563
+ }
2564
+ break;
2565
+ }
2566
+ case "prod": {
2567
+ const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2568
+ const standalonePath = getDockerComposeTemplate("docker-compose.standalone.yml");
2569
+ composeFlags.push("-f", prodPath);
2570
+ filesUsed.push(prodPath);
2571
+ if (overrides.prod) {
2572
+ composeFlags.push("-f", overrides.prod.path);
2573
+ filesUsed.push(overrides.prod.path);
2574
+ }
2575
+ if (dependencies.length > 0) {
2576
+ for (const dep of dependencies) {
2577
+ composeFlags.push("-f", dep.path);
2578
+ filesUsed.push(dep.path);
2579
+ }
2580
+ }
2581
+ composeFlags.push("-f", standalonePath);
2582
+ filesUsed.push(standalonePath);
2583
+ break;
2584
+ }
2585
+ case "e2e": {
2586
+ const prodPath = getDockerComposeTemplate("docker-compose.prod.yml");
2587
+ const e2ePath = getDockerComposeTemplate("docker-compose.e2e.yml");
2588
+ composeFlags.push("-f", prodPath);
2589
+ filesUsed.push(prodPath);
2590
+ if (overrides.prod) {
2591
+ composeFlags.push("-f", overrides.prod.path);
2592
+ filesUsed.push(overrides.prod.path);
2593
+ }
2594
+ if (dependencies.length > 0) {
2595
+ for (const dep of dependencies) {
2596
+ composeFlags.push("-f", dep.path);
2597
+ filesUsed.push(dep.path);
2598
+ }
2599
+ }
2600
+ composeFlags.push("-f", e2ePath);
2601
+ filesUsed.push(e2ePath);
2602
+ if (overrides.e2e) {
2603
+ composeFlags.push("-f", overrides.e2e.path);
2604
+ filesUsed.push(overrides.e2e.path);
2605
+ }
2606
+ break;
2607
+ }
2608
+ }
2609
+ composeFlags.push("config");
2610
+ const result = spawnSync("docker", composeFlags, {
2611
+ cwd: absProjectDir,
2612
+ encoding: "utf-8"
2613
+ });
2614
+ if (result.error) {
2615
+ throw new ScriptError(
2616
+ `Failed to run docker compose: ${result.error.message}`,
2617
+ { cause: result.error }
2618
+ );
2619
+ }
2620
+ if (result.status !== 0) {
2621
+ const rawOutput = result.stderr || result.stdout;
2622
+ const explanation = explainComposeMergeFailure(
2623
+ buildJson,
2624
+ absProjectDir,
2625
+ environment,
2626
+ filesUsed,
2627
+ rawOutput
2628
+ );
2629
+ throw new ScriptError(`\u274C Failed to merge compose files:
2630
+ ${explanation}`);
2631
+ }
2632
+ const mergedYamlConfig = result.stdout;
2633
+ const yml = parse(mergedYamlConfig);
2634
+ if (environment === "prod" || environment === "e2e") {
2635
+ renameServicesWithDependencies(yml, dependencies);
2636
+ addDependenciesToAppService(yml, dependencies);
2637
+ }
2638
+ if (environment === "e2e") {
2639
+ makeE2eDependOnApp(yml);
2640
+ }
2641
+ attachName(yml, projectName);
2642
+ const finalYamlConfig = stringify(yml);
2643
+ return finalYamlConfig;
2644
+ };
2645
+
2646
+ // src/core/runners/runTestUnit.ts
2647
+ var runTestUnit = async (options) => {
2648
+ if (!options.skipBanner) {
2649
+ console.log(pc20.bold(pc20.blue(`
2650
+ ========================================`)));
2651
+ console.log(pc20.bold(pc20.blue(`\u{1F9EA} STAGE: UNIT & ISOLATED TESTS`)));
2652
+ console.log(pc20.bold(pc20.blue(`========================================
2653
+ `)));
2654
+ }
2655
+ const finalYamlConfig = compileEnvironment("test", options.projectDir);
2656
+ const parsed = parse(finalYamlConfig);
2657
+ const projectName = parsed?.name || "test";
2658
+ if (options.debug) {
2659
+ console.log(
2660
+ pc20.yellow("Final merged YAML configuration:\n"),
2661
+ redactYamlSecrets(finalYamlConfig)
2662
+ );
2663
+ }
2664
+ if (options.dryRun) {
2665
+ console.log(pc20.green("[DRY-RUN] Unit tests simulated. Compose was not started."));
2666
+ return 0;
2667
+ }
2668
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2669
+ removeVolumes: true,
2670
+ silent: true
2671
+ });
2672
+ writeRunState(options.projectDir, {
2673
+ projectName,
2674
+ stage: "test-unit",
2675
+ projectDir: options.projectDir
2676
+ });
2677
+ let status = 0;
2678
+ try {
2679
+ status = await runCompose(
2680
+ ["up", "--build", "--abort-on-container-exit", "--exit-code-from", "app"],
2681
+ finalYamlConfig,
2682
+ options.projectDir,
2683
+ { removeVolumes: true }
2684
+ );
2685
+ } finally {
2686
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2687
+ clearRunState(options.projectDir);
2688
+ }
2689
+ if (status === 0) {
2690
+ console.log(pc20.bold(pc20.green(`
2691
+ \u2705 Unit tests passed successfully.
2692
+ `)));
2693
+ } else {
2694
+ console.error(pc20.red(`
2695
+ \u274C Unit tests failed with exit code ${status}.
2696
+ `));
2697
+ }
2698
+ return status;
2699
+ };
2700
+ var runTestE2e = async (options) => {
2701
+ if (!options.skipBanner) {
2702
+ console.log(pc20.bold(pc20.blue(`
2703
+ ========================================`)));
2704
+ console.log(pc20.bold(pc20.blue(`\u{1F6A6} STAGE: INTEGRATED E2E TESTS`)));
2705
+ console.log(pc20.bold(pc20.blue(`========================================
2706
+ `)));
2707
+ }
2708
+ const finalYamlConfig = compileEnvironment("e2e", options.projectDir);
2709
+ const parsed = parse(finalYamlConfig);
2710
+ const projectName = parsed?.name || "e2e";
2711
+ if (options.debug) {
2712
+ console.log(
2713
+ pc20.yellow("Final merged YAML configuration:\n"),
2714
+ redactYamlSecrets(finalYamlConfig)
2715
+ );
2716
+ }
2717
+ if (options.dryRun) {
2718
+ console.log(pc20.green("[DRY-RUN] E2E tests simulated. Compose was not started."));
2719
+ return 0;
2720
+ }
2721
+ await teardownCompose(finalYamlConfig, options.projectDir, {
2722
+ removeVolumes: true,
2723
+ silent: true
2724
+ });
2725
+ writeRunState(options.projectDir, {
2726
+ projectName,
2727
+ stage: "test-e2e",
2728
+ projectDir: options.projectDir
2729
+ });
2730
+ let status = 0;
2731
+ try {
2732
+ status = await runCompose(
2733
+ [
2734
+ "up",
2735
+ "--build",
2736
+ "--abort-on-container-exit",
2737
+ "--exit-code-from",
2738
+ "tester"
2739
+ ],
2740
+ finalYamlConfig,
2741
+ options.projectDir,
2742
+ { removeVolumes: true }
2743
+ );
2744
+ } finally {
2745
+ await teardownCompose(finalYamlConfig, options.projectDir, { removeVolumes: true });
2746
+ clearRunState(options.projectDir);
2747
+ }
2748
+ if (status === 0) {
2749
+ console.log(pc20.bold(pc20.green(`
2750
+ \u2705 E2E tests passed successfully.
2751
+ `)));
2752
+ } else {
2753
+ console.error(pc20.red(`
2754
+ \u274C E2E tests failed with exit code ${status}.
2755
+ `));
2756
+ }
2757
+ return status;
2758
+ };
2759
+
2760
+ // src/core/runners/runTest.ts
2761
+ var runTest = async (options) => {
2762
+ console.log(pc20.bold(pc20.blue(`
2763
+ ========================================`)));
2764
+ console.log(pc20.bold(pc20.blue(`\u{1F9EA} [1/2] STAGE: UNIT & ISOLATED TESTS`)));
2765
+ console.log(pc20.bold(pc20.blue(`========================================
2766
+ `)));
2767
+ const unitStatus = await runTestUnit({ ...options, skipBanner: true });
2768
+ if (unitStatus !== 0) {
2769
+ console.error(
2770
+ pc20.red(
2771
+ `
2772
+ \u274C [1/2] Unit tests failed with exit code ${unitStatus}. Aborting E2E tests.
2773
+ `
2774
+ )
2775
+ );
2776
+ return unitStatus;
2777
+ }
2778
+ console.log(
2779
+ pc20.bold(pc20.green(`
2780
+ \u2705 [1/2] Unit tests passed successfully.
2781
+ `))
2782
+ );
2783
+ console.log(pc20.bold(pc20.blue(`========================================`)));
2784
+ console.log(pc20.bold(pc20.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED E2E TESTS`)));
2785
+ console.log(pc20.bold(pc20.blue(`========================================
2786
+ `)));
2787
+ const e2eStatus = await runTestE2e({ ...options, skipBanner: true });
2788
+ if (e2eStatus !== 0) {
2789
+ console.error(
2790
+ pc20.red(`
2791
+ \u274C [2/2] E2E tests failed with exit code ${e2eStatus}.
2792
+ `)
2793
+ );
2794
+ return e2eStatus;
2795
+ }
2796
+ console.log(pc20.bold(pc20.green(`
2797
+ \u2705 [2/2] E2E tests passed successfully.
2798
+ `)));
2799
+ console.log(
2800
+ pc20.bold(
2801
+ pc20.green(`\u{1F389} All test stages (unit + e2e) completed successfully!
2802
+ `)
2803
+ )
2804
+ );
2805
+ return 0;
2806
+ };
2807
+ async function runMeshTestE2e(options = {}) {
2808
+ const meshDir = resolveProjectDir(options.projectDir);
2809
+ console.log(pc20.bold(pc20.blue(`
2810
+ ========================================`)));
2811
+ console.log(pc20.bold(pc20.blue(`\u{1F6A6} [MESH] STAGE: GLOBAL INTEGRATED E2E TESTS`)));
2812
+ console.log(pc20.bold(pc20.blue(`========================================
2813
+ `)));
2814
+ if (!options.skipChecks) {
2815
+ checkMesh(meshDir, { requireTester: true });
2816
+ }
2817
+ const { yaml, testerServiceName } = compileMeshEnvironment("prod", meshDir, {
2818
+ includeTester: true
2819
+ });
2820
+ if (!testerServiceName) {
2821
+ throw new ScriptError(
2822
+ "No tester service could be identified in the tester docker compose configuration."
2823
+ );
2824
+ }
2825
+ if (options.debug) {
2826
+ console.log(
2827
+ pc20.yellow("\nFinal merged Mesh E2E YAML configuration:\n"),
2828
+ redactYamlSecrets(yaml)
2829
+ );
2830
+ }
2831
+ if (options.dryRun) {
2832
+ console.log(pc20.green("[DRY-RUN] Global E2E test simulated. Compose was not started."));
2833
+ return 0;
2834
+ }
2835
+ const parsed = parse(yaml);
2836
+ const projectName = parsed?.name || "mesh-e2e";
2837
+ await teardownCompose(yaml, meshDir, { removeVolumes: true, silent: true });
2838
+ writeRunState(meshDir, {
2839
+ projectName,
2840
+ stage: "test-e2e",
2841
+ projectDir: meshDir
2842
+ });
2843
+ let status = 0;
2844
+ try {
2845
+ status = await runCompose(
2846
+ [
2847
+ "up",
2848
+ "--build",
2849
+ "--abort-on-container-exit",
2850
+ "--exit-code-from",
2851
+ testerServiceName
2852
+ ],
2853
+ yaml,
2854
+ meshDir,
2855
+ { removeVolumes: true }
2856
+ );
2857
+ } finally {
2858
+ console.log(pc20.cyan("\n\u{1F9F9} Cleaning up global mesh containers and volumes..."));
2859
+ await teardownCompose(yaml, meshDir, { removeVolumes: true });
2860
+ clearRunState(meshDir);
2861
+ }
2862
+ if (status === 0) {
2863
+ console.log(pc20.bold(pc20.green(`
2864
+ \u2705 Global E2E tests passed successfully.
2865
+ `)));
2866
+ } else {
2867
+ console.error(pc20.red(`
2868
+ \u274C Global E2E tests failed with exit code ${status}.
2869
+ `));
2870
+ }
2871
+ return status;
2872
+ }
2873
+
2874
+ // src/core/mesh/runners/runMeshTest.ts
2875
+ async function runMeshTest(options = {}) {
2876
+ const meshDir = resolveProjectDir(options.projectDir);
2877
+ console.log(pc20.bold(pc20.blue(`
2878
+ ========================================`)));
2879
+ console.log(pc20.bold(pc20.blue(`\u{1F9EA} GLOBAL MESH TEST PIPELINE`)));
2880
+ console.log(pc20.bold(pc20.blue(`========================================
2881
+ `)));
2882
+ if (!options.skipChecks) {
2883
+ checkMesh(meshDir, { requireTester: true });
2884
+ }
2885
+ const mesh = getMeshJson(meshDir);
2886
+ console.log(pc20.bold(pc20.blue(`
2887
+ ========================================`)));
2888
+ console.log(
2889
+ pc20.bold(
2890
+ pc20.blue(`\u{1F9EA} [1/2] STAGE: LOCAL SUBMODULE TEST SUITES (Unit & Isolated E2E)`)
2891
+ )
2892
+ );
2893
+ console.log(pc20.bold(pc20.blue(`========================================
2894
+ `)));
2895
+ for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
2896
+ const serviceDir = path13.resolve(meshDir, serviceConfig.path);
2897
+ console.log(
2898
+ pc20.bold(pc20.cyan(`
2899
+ -> Running full test suite for [${serviceName}] in isolation...`))
2900
+ );
2901
+ if (options.dryRun) {
2902
+ console.log(
2903
+ pc20.green(`[DRY-RUN] Full isolated tests for ${serviceName} simulated.`)
2904
+ );
2905
+ continue;
2906
+ }
2907
+ const serviceStatus = await runTest({
2908
+ projectDir: serviceDir,
2909
+ debug: Boolean(options.debug),
2910
+ detach: Boolean(options.detach)
2911
+ });
2912
+ if (serviceStatus !== 0) {
2913
+ console.error(
2914
+ pc20.red(
2915
+ `
2916
+ \u274C Isolated tests failed for service [${serviceName}] with exit code ${serviceStatus}. Aborting global E2E tests.
2917
+ `
2918
+ )
2919
+ );
2920
+ return serviceStatus;
2921
+ }
2922
+ console.log(
2923
+ pc20.bold(pc20.green(`
2924
+ \u2705 Isolated tests passed for service: [${serviceName}]
2925
+ `))
2926
+ );
2927
+ }
2928
+ console.log(pc20.bold(pc20.blue(`
2929
+ ========================================`)));
2930
+ console.log(
2931
+ pc20.bold(
2932
+ pc20.blue(`\u{1F6A6} [2/2] STAGE: INTEGRATED PRODUCTION MESH & GLOBAL E2E ASSERTIONS`)
2933
+ )
2934
+ );
2935
+ console.log(pc20.bold(pc20.blue(`========================================
2936
+ `)));
2937
+ const e2eStatus = await runMeshTestE2e({ ...options, skipChecks: true });
2938
+ if (e2eStatus !== 0) {
2939
+ return e2eStatus;
2940
+ }
2941
+ console.log(
2942
+ pc20.bold(
2943
+ pc20.green(`\u{1F389} Entire global mesh test pipeline (unit, local e2e, and global e2e) completed successfully!
2944
+ `)
2945
+ )
2946
+ );
2947
+ return 0;
2948
+ }
2949
+ async function runMeshTestUnit(options = {}) {
2950
+ const meshDir = resolveProjectDir(options.projectDir);
2951
+ console.log(pc20.bold(pc20.blue(`
2952
+ ========================================`)));
2953
+ console.log(pc20.bold(pc20.blue(`\u{1F9EA} [MESH] STAGE: ISOLATED UNIT TESTS`)));
2954
+ console.log(pc20.bold(pc20.blue(`========================================
2955
+ `)));
2956
+ if (!options.skipChecks) {
2957
+ checkMesh(meshDir, { requireTester: false });
2958
+ }
2959
+ const mesh = getMeshJson(meshDir);
2960
+ for (const [serviceName, serviceConfig] of Object.entries(mesh.services)) {
2961
+ const serviceDir = path13.resolve(meshDir, serviceConfig.path);
2962
+ console.log(
2963
+ pc20.cyan(`
2964
+ -> Running isolated unit tests for service: [${serviceName}]...`)
2965
+ );
2966
+ if (options.dryRun) {
2967
+ console.log(pc20.green(`[DRY-RUN] Unit tests for ${serviceName} simulated.`));
2968
+ continue;
2969
+ }
2970
+ const unitStatus = await runTestUnit({
2971
+ projectDir: serviceDir,
2972
+ debug: Boolean(options.debug),
2973
+ detach: Boolean(options.detach),
2974
+ skipBanner: true
2975
+ });
2976
+ if (unitStatus !== 0) {
2977
+ console.error(
2978
+ pc20.red(`
2979
+ \u274C Unit tests failed for service [${serviceName}] with exit code ${unitStatus}.
2980
+ `)
2981
+ );
2982
+ return unitStatus;
2983
+ }
2984
+ console.log(
2985
+ pc20.bold(pc20.green(`
2986
+ \u2705 Isolated unit tests passed for service: [${serviceName}]
2987
+ `))
2988
+ );
2989
+ }
2990
+ console.log(
2991
+ pc20.bold(pc20.green(`\u{1F389} All mesh service unit tests completed successfully!
2992
+ `))
2993
+ );
2994
+ return 0;
2995
+ }
2996
+
2997
+ // src/commands/mesh/commands/up/handler.ts
2998
+ async function handleMeshUp(rawStage = "dev", options = {}) {
2999
+ const stage = (rawStage || "dev").toLowerCase();
3000
+ const projectDir = resolveProjectDir(options.projectDir);
3001
+ const runOptions = {
3002
+ ...options,
3003
+ projectDir
3004
+ };
3005
+ switch (stage) {
3006
+ case "dev":
3007
+ return await runMeshDev(runOptions);
3008
+ case "prod":
3009
+ return await runMeshProd(runOptions);
3010
+ case "test-unit":
3011
+ return await runMeshTestUnit(runOptions);
3012
+ case "test-e2e":
3013
+ return await runMeshTestE2e(runOptions);
3014
+ case "test":
3015
+ return await runMeshTest(runOptions);
3016
+ default:
3017
+ throw new ScriptError(
3018
+ `Unknown mesh stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
3019
+ );
3020
+ }
3021
+ }
3022
+
3023
+ // src/commands/mesh/commands/up/command.ts
3024
+ var registerMeshUpCommand = (cmd) => {
3025
+ cmd.command("up [stage]").description(
3026
+ "Start, build, or test the mesh environment (dev, prod, test, test-unit, test-e2e)"
3027
+ ).option("--debug", "Output the merged Docker Compose YAML configuration").option("-d, --detach", "Run containers in the background").option(
3028
+ "--dry-run",
3029
+ "Compile configuration and validate checks without starting containers"
3030
+ ).option(
3031
+ "--skip-checks",
3032
+ "Skip hadolint and conftest pre-flight checks"
3033
+ ).option(
3034
+ "-C, --project-dir <dir>",
3035
+ "Mesh project directory containing mesh.json (defaults to cwd)"
3036
+ ).addHelpText(
3037
+ "after",
3038
+ `
3039
+ Examples:
3040
+ $ builder mesh up dev
3041
+ $ builder mesh up prod
3042
+ $ builder mesh up test
3043
+ $ builder mesh up test-unit
3044
+ $ builder mesh up test-e2e`
3045
+ ).action(
3046
+ async (stage = "dev", options = {}) => {
3047
+ const exitCode = await handleMeshUp(stage, {
3048
+ projectDir: options.projectDir,
3049
+ debug: options.debug,
3050
+ detach: options.detach,
3051
+ dryRun: options.dryRun,
3052
+ skipChecks: options.skipChecks
3053
+ });
3054
+ if (exitCode !== 0) {
3055
+ process.exit(exitCode);
3056
+ }
3057
+ }
3058
+ );
3059
+ };
3060
+
3061
+ // src/commands/mesh/command.ts
3062
+ var registerMeshCommand = (program) => {
3063
+ const meshCmd = program.command("mesh").description("Manage and orchestrate multi-service mesh environments");
3064
+ meshCmd.hook("preAction", () => {
3065
+ checkDependencies();
3066
+ });
3067
+ registerMeshUpCommand(meshCmd);
3068
+ registerMeshDownCommand(meshCmd);
3069
+ registerMeshCheckCommand(meshCmd);
3070
+ };
3071
+ async function handlePrune(options = {}) {
3072
+ console.log(pc20.cyan("\n\u{1F9F9} Pruning stopped Compose containers and unused networks..."));
3073
+ const rmContainers = spawnSync("docker", ["container", "prune", "-f"], {
3074
+ stdio: "inherit",
3075
+ encoding: "utf-8"
3076
+ });
3077
+ if (rmContainers.error) {
3078
+ throw new ScriptError(`Failed to prune containers: ${rmContainers.error.message}`, {
3079
+ cause: rmContainers.error
3080
+ });
3081
+ }
3082
+ const rmNetworks = spawnSync("docker", ["network", "prune", "-f"], {
3083
+ stdio: "inherit",
3084
+ encoding: "utf-8"
3085
+ });
3086
+ if (rmNetworks.error) {
3087
+ throw new ScriptError(`Failed to prune networks: ${rmNetworks.error.message}`, {
3088
+ cause: rmNetworks.error
3089
+ });
3090
+ }
3091
+ if (options.volumes) {
3092
+ console.log(pc20.cyan("\u{1F9F9} Pruning dangling volumes..."));
3093
+ spawnSync("docker", ["volume", "prune", "-f"], {
3094
+ stdio: "inherit",
3095
+ encoding: "utf-8"
3096
+ });
3097
+ }
3098
+ console.log(pc20.green("\u2705 Docker environment pruned successfully.\n"));
3099
+ return 0;
3100
+ }
3101
+
3102
+ // src/commands/prune/command.ts
3103
+ var registerPruneCommand = (cmd) => {
3104
+ cmd.command("prune").description("Remove stopped containers, unused networks, and dangling resources").option("-v, --volumes", "Also prune dangling anonymous volumes").action(async (options = {}) => {
3105
+ const exitCode = await handlePrune({
3106
+ volumes: Boolean(options.volumes)
3107
+ });
3108
+ if (exitCode !== 0) {
3109
+ process.exit(exitCode);
3110
+ }
3111
+ });
3112
+ };
3113
+ async function handleServiceDown(rawStage = "dev", options = {}) {
3114
+ const projectDir = resolveProjectDir(options.projectDir);
3115
+ const stage = (rawStage || "dev").toLowerCase();
3116
+ const validStages = ["dev", "prod", "test", "test-unit", "test-e2e"];
3117
+ if (!validStages.includes(stage)) {
3118
+ throw new ScriptError(
3119
+ `Unknown environment stage: "${rawStage}". Supported stages: dev, prod, test, test-unit, test-e2e`
3120
+ );
3121
+ }
3122
+ console.log(
3123
+ pc20.cyan(`
3124
+ \u{1F9F9} Stopping and tearing down service environment [${stage}]...`)
3125
+ );
3126
+ if (options.debug) {
3127
+ try {
3128
+ let env = "dev";
3129
+ if (stage === "prod") env = "prod";
3130
+ else if (stage === "test" || stage === "test-unit") env = "test";
3131
+ else if (stage === "test-e2e") env = "e2e";
3132
+ const finalYamlConfig = compileEnvironment(env, projectDir);
3133
+ console.log(
3134
+ pc20.yellow("Final merged YAML configuration:\n"),
3135
+ redactYamlSecrets(finalYamlConfig)
3136
+ );
3137
+ } catch {
3138
+ }
3139
+ }
3140
+ const runState = readRunState(projectDir);
3141
+ const candidateProjects = projectNamesForServiceStage(projectDir, stage);
3142
+ if (runState?.projectName) {
3143
+ candidateProjects.unshift(runState.projectName);
3144
+ }
3145
+ const uniqueProjects = Array.from(new Set(candidateProjects));
3146
+ for (const proj of uniqueProjects) {
3147
+ await teardownCompose("", projectDir, {
3148
+ projectName: proj,
3149
+ removeVolumes: Boolean(options.volumes)
3150
+ });
3151
+ }
3152
+ clearRunState(projectDir);
3153
+ console.log(
3154
+ pc20.green(`\u2705 Service environment [${stage}] stopped and removed.
3155
+ `)
3156
+ );
3157
+ return 0;
3158
+ }
3159
+
3160
+ // src/commands/service/commands/down/command.ts
3161
+ var registerDownCommand = (cmd) => {
3162
+ cmd.command("down [stage]").description(
3163
+ "Stop and remove containers and networks for a service environment (dev, prod, test, test-unit, test-e2e)"
3164
+ ).option(
3165
+ "-v, --volumes",
3166
+ "Remove named volumes declared in the volumes section"
3167
+ ).option(
3168
+ "-C, --project-dir <dir>",
3169
+ "Service project directory (defaults to cwd)"
3170
+ ).option("--debug", "Output the merged Docker Compose YAML configuration").addHelpText(
3171
+ "after",
3172
+ `
3173
+ Examples:
3174
+ $ builder service down
3175
+ $ builder service down dev
3176
+ $ builder service down prod
3177
+ $ builder service down -v`
3178
+ ).action(
3179
+ async (stage = "dev", options = {}) => {
3180
+ const exitCode = await handleServiceDown(stage, {
3181
+ projectDir: options.projectDir,
3182
+ volumes: options.volumes,
3183
+ debug: options.debug
3184
+ });
3185
+ if (exitCode !== 0) {
3186
+ process.exit(exitCode);
3187
+ }
3188
+ }
3189
+ );
3190
+ };
3191
+ var runDev = async (options) => {
3192
+ console.log(pc20.cyan(`\u{1F680} Starting DEV environment...`));
3193
+ const finalYamlConfig = compileEnvironment("dev", options.projectDir);
3194
+ const parsed = parse(finalYamlConfig);
3195
+ const projectName = parsed?.name || "dev";
3196
+ if (options.debug) {
3197
+ console.log(
3198
+ pc20.yellow("Final merged YAML configuration:\n"),
3199
+ redactYamlSecrets(finalYamlConfig)
3200
+ );
3201
+ }
3202
+ if (options.dryRun) {
3203
+ console.log(pc20.green("Dry run complete. Compose was not started."));
3204
+ return 0;
3205
+ }
3206
+ const hostPorts = extractHostPorts(finalYamlConfig);
3207
+ await checkHostPortCollisions(hostPorts);
3208
+ writeRunState(options.projectDir, {
3209
+ projectName,
3210
+ stage: "dev",
3211
+ projectDir: options.projectDir
3212
+ });
3213
+ const upArgs = ["up", "--build"];
3214
+ if (options.detach) {
3215
+ upArgs.push("-d");
3216
+ }
3217
+ let status = 0;
3218
+ try {
3219
+ status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3220
+ removeVolumes: false
3221
+ });
3222
+ } finally {
3223
+ if (!options.detach) {
3224
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3225
+ removeVolumes: false
3226
+ });
3227
+ clearRunState(options.projectDir);
3228
+ }
3229
+ }
3230
+ return status;
3231
+ };
3232
+ var runProd = async (options) => {
3233
+ console.log(pc20.cyan(`\u{1F3ED} Starting PROD environment...`));
3234
+ const finalYamlConfig = compileEnvironment("prod", options.projectDir);
3235
+ const parsed = parse(finalYamlConfig);
3236
+ const projectName = parsed?.name || "prod";
3237
+ if (options.debug) {
3238
+ console.log(
3239
+ pc20.yellow("Final merged YAML configuration:\n"),
3240
+ redactYamlSecrets(finalYamlConfig)
3241
+ );
3242
+ }
3243
+ if (options.dryRun) {
3244
+ console.log(pc20.green("Dry run complete. Compose was not started."));
3245
+ return 0;
3246
+ }
3247
+ const hostPorts = extractHostPorts(finalYamlConfig);
3248
+ await checkHostPortCollisions(hostPorts);
3249
+ writeRunState(options.projectDir, {
3250
+ projectName,
3251
+ stage: "prod",
3252
+ projectDir: options.projectDir
3253
+ });
3254
+ const upArgs = ["up", "--build"];
3255
+ if (options.detach) {
3256
+ upArgs.push("-d");
3257
+ }
3258
+ let status = 0;
3259
+ try {
3260
+ status = await runCompose(upArgs, finalYamlConfig, options.projectDir, {
3261
+ removeVolumes: false
3262
+ });
3263
+ } finally {
3264
+ if (!options.detach) {
3265
+ await teardownCompose(finalYamlConfig, options.projectDir, {
3266
+ removeVolumes: false
3267
+ });
3268
+ clearRunState(options.projectDir);
3269
+ }
3270
+ }
3271
+ return status;
3272
+ };
3273
+
3274
+ // src/commands/service/commands/up/handler.ts
3275
+ async function handleServiceUp(rawStage, options = {}) {
3276
+ const projectDir = resolveProjectDir(options.projectDir);
3277
+ const stage = (rawStage || "dev").toLowerCase();
3278
+ const runOptions = {
3279
+ projectDir,
3280
+ debug: Boolean(options.debug),
3281
+ detach: Boolean(options.detach),
3282
+ dryRun: Boolean(options.dryRun)
3283
+ };
3284
+ if (stage === "dev") {
3285
+ return await runDev(runOptions);
3286
+ }
3287
+ if (stage === "prod") {
3288
+ return await runProd(runOptions);
3289
+ }
3290
+ if (stage === "test-unit") {
3291
+ return await runTestUnit(runOptions);
3292
+ }
3293
+ if (stage === "test-e2e") {
3294
+ return await runTestE2e(runOptions);
3295
+ }
3296
+ if (stage === "test") {
3297
+ return await runTest(runOptions);
3298
+ }
3299
+ throw new ScriptError(
3300
+ `Unknown environment stage: "${rawStage}". Supported stages: ${SERVICE_STAGES.join(", ")}`
3301
+ );
3302
+ }
3303
+
3304
+ // src/commands/service/commands/up/command.ts
3305
+ var registerUpCommand = (cmd) => {
3306
+ cmd.command("up [stage]").description(
3307
+ "Start or test a service environment (dev, prod, test, test-unit, test-e2e)"
3308
+ ).option("--debug", "Output the merged Docker Compose YAML configuration").option("-d, --detach", "Run containers in the background").option(
3309
+ "--dry-run",
3310
+ "Compile configuration and validate checks without starting containers"
3311
+ ).option(
3312
+ "--skip-checks",
3313
+ "Skip hadolint and conftest pre-flight checks"
3314
+ ).option(
3315
+ "-C, --project-dir <dir>",
3316
+ "Service project directory (defaults to cwd)"
3317
+ ).addHelpText(
3318
+ "after",
3319
+ `
3320
+ Examples:
3321
+ $ builder service up dev
3322
+ $ builder service up prod
3323
+ $ builder service up test
3324
+ $ builder service up test-unit
3325
+ $ builder service up test-e2e`
3326
+ ).action(
3327
+ async (stage = "dev", options = {}) => {
3328
+ const exitCode = await handleServiceUp(stage, {
3329
+ projectDir: options.projectDir,
3330
+ debug: options.debug,
3331
+ detach: options.detach,
3332
+ dryRun: options.dryRun,
3333
+ skipChecks: options.skipChecks
3334
+ });
3335
+ if (exitCode !== 0) {
3336
+ process.exit(exitCode);
3337
+ }
3338
+ }
3339
+ );
3340
+ };
3341
+
3342
+ // src/commands/service/command.ts
3343
+ var registerServiceCommand = (cmd) => {
3344
+ const service = cmd.command("service").description("Manage and run services");
3345
+ service.hook("preAction", async (_thisCommand, actionCommand) => {
3346
+ checkDependencies();
3347
+ if (actionCommand.name() === "up") {
3348
+ const options = actionCommand.opts();
3349
+ const stageArg = actionCommand.args[0]?.toLowerCase();
3350
+ if (stageArg && !SERVICE_STAGES.includes(stageArg)) {
3351
+ return;
3352
+ }
3353
+ const projectDir = resolveProjectDir(options.projectDir);
3354
+ if (!options.skipChecks) {
3355
+ checkInfra(projectDir);
3356
+ }
3357
+ }
3358
+ });
3359
+ registerUpCommand(service);
3360
+ registerDownCommand(service);
3361
+ };
3362
+ var require2 = createRequire(import.meta.url);
3363
+ var pkg = require2("../package.json");
3364
+ var packageSchema = z.object({
3365
+ version: z.string().min(1, "Version string cannot be empty")
3366
+ });
3367
+ var parsedPkg = packageSchema.parse(pkg);
3368
+ var version = parsedPkg.version;
3369
+
3370
+ // src/cli.ts
3371
+ function createCli() {
3372
+ const program = new Command();
3373
+ program.name("builder").description("CLI build tool and orchestrator for Solid Stack services").version(version, "-V, --version", "Output the current version").option("--verbose", "Output verbose error messages with stack traces").exitOverride();
3374
+ registerServiceCommand(program);
3375
+ registerMeshCommand(program);
3376
+ registerCheckCommand(program);
3377
+ registerPruneCommand(program);
3378
+ return program;
3379
+ }
3380
+ async function runCli(argv = process.argv) {
3381
+ const cli = createCli();
3382
+ if (argv.length <= 2) {
3383
+ cli.outputHelp();
3384
+ return;
3385
+ }
3386
+ try {
3387
+ await cli.parseAsync(argv);
3388
+ } catch (err) {
3389
+ const errorObj = err;
3390
+ if (errorObj?.code === "commander.helpDisplayed" || errorObj?.code === "commander.help" || errorObj?.code === "commander.version") {
3391
+ return;
3392
+ }
3393
+ const isVerbose = argv.includes("--verbose") || Boolean(process.env.DEBUG) || Boolean(process.env.VERBOSE);
3394
+ let exitCode = errorObj?.exitCode ?? 1;
3395
+ if (typeof errorObj?.code === "string" && errorObj.code.startsWith("commander.")) {
3396
+ if (process.env.VITEST) {
3397
+ throw err;
3398
+ }
3399
+ process.exit(exitCode);
3400
+ }
3401
+ if (err instanceof ScriptError) {
3402
+ exitCode = err.exitCode;
3403
+ const formatted = err.message.startsWith("\u274C") ? err.message : `\u274C ${err.message}`;
3404
+ console.error(pc20.red(`
3405
+ ${formatted}
3406
+ `));
3407
+ if (isVerbose && err.stack) {
3408
+ console.error(pc20.dim(err.stack));
3409
+ }
3410
+ } else {
3411
+ const message = errorMessage(err);
3412
+ const formatted = message.startsWith("\u274C") ? message : `\u274C Error: ${message}`;
3413
+ console.error(pc20.red(`
3414
+ ${formatted}
3415
+ `));
3416
+ if (isVerbose && err instanceof Error && err.stack) {
3417
+ console.error(pc20.dim(err.stack));
3418
+ }
3419
+ }
3420
+ if (process.env.VITEST) {
3421
+ throw err;
3422
+ }
3423
+ process.exit(exitCode);
3424
+ }
3425
+ }
3426
+
3427
+ export { NotFoundError, SERVICE_STAGES, ScriptError, compileEnvironment, compileMeshEnvironment, createCli, runCli, runCompose, teardownCompose, version };
3428
+ //# sourceMappingURL=index.js.map
3429
+ //# sourceMappingURL=index.js.map