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