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