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