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