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