@solid-stack/builder 2.0.2 → 2.0.3

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.
Files changed (42) hide show
  1. package/dist/bin.js +381 -93
  2. package/dist/bin.js.map +1 -1
  3. package/dist/core/composition/compileServiceComposition.d.ts +2 -0
  4. package/dist/core/composition/compileServiceComposition.d.ts.map +1 -1
  5. package/dist/core/composition/composeBuildResources.d.ts +6 -0
  6. package/dist/core/composition/composeBuildResources.d.ts.map +1 -0
  7. package/dist/core/composition/composeDependsOn.d.ts +3 -0
  8. package/dist/core/composition/composeDependsOn.d.ts.map +1 -0
  9. package/dist/core/composition/composeEnvironment.d.ts +2 -2
  10. package/dist/core/composition/composeEnvironment.d.ts.map +1 -1
  11. package/dist/core/composition/composeHealthcheck.d.ts +3 -0
  12. package/dist/core/composition/composeHealthcheck.d.ts.map +1 -0
  13. package/dist/core/composition/composePaths.d.ts.map +1 -1
  14. package/dist/core/composition/generatedNames.d.ts +9 -0
  15. package/dist/core/composition/generatedNames.d.ts.map +1 -0
  16. package/dist/core/composition/namespaceDependencyCompose.d.ts +3 -0
  17. package/dist/core/composition/namespaceDependencyCompose.d.ts.map +1 -1
  18. package/dist/core/composition/types.d.ts +8 -3
  19. package/dist/core/composition/types.d.ts.map +1 -1
  20. package/dist/core/composition/validateComposeResourceReferences.d.ts +7 -0
  21. package/dist/core/composition/validateComposeResourceReferences.d.ts.map +1 -0
  22. package/dist/core/composition/validateDependencyCompose.d.ts.map +1 -1
  23. package/dist/core/composition/validateOverrideCompose.d.ts +3 -0
  24. package/dist/core/composition/validateOverrideCompose.d.ts.map +1 -1
  25. package/dist/core/config/pathSafety.d.ts.map +1 -1
  26. package/dist/core/mesh/checkers/checkMeshServices.d.ts.map +1 -1
  27. package/dist/core/mesh/runners/runMeshTestUnit.d.ts.map +1 -1
  28. package/dist/core/mesh/v2/compileMeshComposition.d.ts.map +1 -1
  29. package/dist/core/mesh/v2/compileMeshTester.d.ts +2 -1
  30. package/dist/core/mesh/v2/compileMeshTester.d.ts.map +1 -1
  31. package/dist/core/mesh/v2/validateMeshTestStage.d.ts +22 -0
  32. package/dist/core/mesh/v2/validateMeshTestStage.d.ts.map +1 -0
  33. package/dist/index.js +381 -93
  34. package/dist/index.js.map +1 -1
  35. package/dist/templates/policy/dockerfile/dockerfile.rego +6 -9
  36. package/dist/utils/assertUniqueHostPortMappings.d.ts.map +1 -1
  37. package/dist/utils/checkPortCollision.d.ts.map +1 -1
  38. package/dist/utils/composePublishedPort.d.ts +3 -0
  39. package/dist/utils/composePublishedPort.d.ts.map +1 -0
  40. package/package.json +1 -1
  41. package/schemas/mesh-schema.json +310 -20
  42. package/templates/policy/dockerfile/dockerfile.rego +6 -9
package/dist/bin.js CHANGED
@@ -7,9 +7,9 @@ import { z } from 'zod';
7
7
  import { spawnSync, spawn } from 'child_process';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { parseAllDocuments, parse, stringify } from 'yaml';
10
- import crypto from 'crypto';
10
+ import crypto, { createHash } from 'crypto';
11
+ import net, { isIP } from 'net';
11
12
  import os from 'os';
12
- import net from 'net';
13
13
  import { createInterface } from 'readline/promises';
14
14
  import { createRequire } from 'module';
15
15
 
@@ -137,8 +137,12 @@ var getBuildJson = (projectDir = process.cwd()) => {
137
137
  }
138
138
  return result.data;
139
139
  };
140
+ function isAbsoluteManagedPath(value) {
141
+ return path.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value) || /^\/\//.test(value);
142
+ }
140
143
  function resolveInsideProject(projectDir, relativePath, context) {
141
144
  if (!relativePath.trim()) throw new ConfigError({ ...context, value: relativePath, reason: "Path must not be empty" });
145
+ if (isAbsoluteManagedPath(relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Builder-managed path must be relative to its project root" });
142
146
  const resolved = path.resolve(projectDir, relativePath);
143
147
  if (!isPathInside(projectDir, relativePath)) throw new ConfigError({ ...context, value: relativePath, reason: "Path escapes the project directory" });
144
148
  return resolved;
@@ -327,6 +331,34 @@ function checkYamlFiles(build, projectDir) {
327
331
  loadComposeDocument(absolutePath, { sourceFile: `${root}/build.json`, configPath: file.source, stage: file.stage ?? "base", composition: "service" });
328
332
  }
329
333
  }
334
+ var GeneratedComposeNameAllocator = class {
335
+ occupied;
336
+ allocated = /* @__PURE__ */ new Map();
337
+ constructor(initialNames = []) {
338
+ this.occupied = new Set(initialNames);
339
+ }
340
+ allocate(identity, hint) {
341
+ const existing = this.allocated.get(identity);
342
+ if (existing) return existing;
343
+ const hash = createHash("sha256").update(identity).digest("hex");
344
+ const safeHint = hint.replace(/[^a-zA-Z0-9_-]/g, "-") || "item";
345
+ for (const candidate of [
346
+ safeHint,
347
+ ...[12, 16, 24, 32, 64].map((length) => `${safeHint}-${hash.slice(0, length)}`)
348
+ ]) {
349
+ if (this.occupied.has(candidate)) continue;
350
+ this.occupied.add(candidate);
351
+ this.allocated.set(identity, candidate);
352
+ return candidate;
353
+ }
354
+ throw new Error(`Unable to allocate unique Compose name for ${identity}`);
355
+ }
356
+ assertUnique() {
357
+ if (new Set(this.allocated.values()).size !== this.allocated.size) {
358
+ throw new Error("Internal generated Compose name collision");
359
+ }
360
+ }
361
+ };
330
362
 
331
363
  // src/core/composition/composeNetworks.ts
332
364
  function normalizeNetworks(value) {
@@ -640,14 +672,33 @@ function volumeShort(v, base, out) {
640
672
  if (mount?.type !== "bind" || !mount.source || /^(?:[\\/]|~|[a-z]:)/i.test(mount.source)) return v;
641
673
  return rewriteVolumeSource(v, rebase(mount.source, base, out));
642
674
  }
675
+ function isRemoteBuildContext(value) {
676
+ return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value) || /^[^/@\s]+@[^:\s]+:.+/.test(value);
677
+ }
678
+ function rebaseAdditionalContext(value, base, out) {
679
+ if (value.startsWith("service:") || isRemoteBuildContext(value)) return value;
680
+ return rebase(value, base, out);
681
+ }
682
+ function rebaseAdditionalContexts(value, base, out) {
683
+ if (Array.isArray(value)) return value.map((entry) => {
684
+ if (typeof entry !== "string") return entry;
685
+ const separator = entry.indexOf("=");
686
+ if (separator < 0) return entry;
687
+ return `${entry.slice(0, separator)}=${rebaseAdditionalContext(entry.slice(separator + 1), base, out)}`;
688
+ });
689
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, context]) => [name, typeof context === "string" ? rebaseAdditionalContext(context, base, out) : context]));
690
+ return value;
691
+ }
643
692
  function rebaseComposePaths(document, composeFilePath, outputProjectDir) {
644
693
  const doc = structuredClone(document), base = path.dirname(composeFilePath), out = path.resolve(outputProjectDir);
645
694
  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") {
695
+ if (typeof svc.build === "string") {
696
+ if (!isRemoteBuildContext(svc.build)) svc.build = rebase(svc.build, base, out);
697
+ } else if (svc.build && typeof svc.build === "object") {
648
698
  const b = svc.build;
649
699
  const context = typeof b.context === "string" ? b.context : ".";
650
- b.context = rebase(context, base, out);
700
+ if (!isRemoteBuildContext(context)) b.context = rebase(context, base, out);
701
+ if (b.additional_contexts !== void 0) b.additional_contexts = rebaseAdditionalContexts(b.additional_contexts, base, out);
651
702
  }
652
703
  if (typeof svc.env_file === "string") svc.env_file = rebase(svc.env_file, base, out);
653
704
  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);
@@ -712,7 +763,7 @@ function normalizeComposeEnvironment(value, context) {
712
763
  if (typeof item !== "string") throw new ConfigError({ configPath: context, value: item, reason: "Compose environment entries must be strings" });
713
764
  const at = item.indexOf("=");
714
765
  if (at < 0) {
715
- result[item] = process.env[item] ?? "";
766
+ result[item] = null;
716
767
  continue;
717
768
  }
718
769
  result[item.slice(0, at)] = item.slice(at + 1);
@@ -721,7 +772,10 @@ function normalizeComposeEnvironment(value, context) {
721
772
  }
722
773
  if (typeof value !== "object") throw new ConfigError({ configPath: context, value, reason: "Compose environment must be a map or list" });
723
774
  for (const [key, val] of Object.entries(value)) {
724
- if (val === null || val === void 0) continue;
775
+ if (val === null || val === void 0) {
776
+ result[key] = null;
777
+ continue;
778
+ }
725
779
  if (typeof val === "object") throw new ConfigError({ configPath: `${context}.${key}`, value: val, reason: "Compose environment value must be scalar" });
726
780
  result[key] = String(val);
727
781
  }
@@ -731,16 +785,66 @@ function mergeComposeEnvironment(service, overlay) {
731
785
  service.environment = { ...normalizeComposeEnvironment(service.environment, "service.environment"), ...overlay };
732
786
  }
733
787
 
788
+ // src/core/composition/composeBuildResources.ts
789
+ function buildObject(service) {
790
+ return service.build && typeof service.build === "object" && !Array.isArray(service.build) ? service.build : void 0;
791
+ }
792
+ function rewriteBuildSecretReferences(service, names) {
793
+ const build = buildObject(service);
794
+ if (!build || !Array.isArray(build.secrets)) return;
795
+ build.secrets = build.secrets.map((entry) => {
796
+ if (typeof entry === "string") return names.get(entry) ?? entry;
797
+ if (entry && typeof entry === "object" && typeof entry.source === "string") {
798
+ return { ...entry, source: names.get(entry.source) ?? entry.source };
799
+ }
800
+ return entry;
801
+ });
802
+ }
803
+ function collectBuildSecretReferences(service) {
804
+ const build = buildObject(service);
805
+ if (!build || !Array.isArray(build.secrets)) return [];
806
+ return build.secrets.flatMap((entry) => {
807
+ if (typeof entry === "string") return [entry];
808
+ return entry && typeof entry === "object" && typeof entry.source === "string" ? [entry.source] : [];
809
+ });
810
+ }
811
+ function assertNoServiceBuildContexts(service, configPath, sourceFile) {
812
+ const contexts = buildObject(service)?.additional_contexts;
813
+ const values = Array.isArray(contexts) ? contexts.map((entry) => typeof entry === "string" ? entry.slice(entry.indexOf("=") + 1) : entry) : contexts && typeof contexts === "object" ? Object.values(contexts) : [];
814
+ if (values.some((value) => typeof value === "string" && value.startsWith("service:"))) {
815
+ throw new ConfigError({
816
+ sourceFile,
817
+ configPath: `${configPath}.build.additional_contexts`,
818
+ reason: "Compose service-reference additional_contexts are unsupported"
819
+ });
820
+ }
821
+ }
822
+
734
823
  // src/core/composition/namespaceDependencyCompose.ts
735
824
  var entries = (obj) => obj && typeof obj === "object" && !Array.isArray(obj) ? Object.entries(obj) : [];
736
825
  function namespaceDependencyCompose(options) {
737
826
  const { document, namespacePrefix: prefix } = options, doc = structuredClone(document);
738
- const make = (kind, keys) => new Map(keys.map((k) => [k, `${prefix}--${kind}--${k}`]));
739
- const serviceNameMap = make("", Object.keys(doc.services ?? {}));
740
- for (const [k, v] of serviceNameMap) serviceNameMap.set(k, `${prefix}--${k}`);
827
+ const originalServices = doc.services ?? {};
828
+ const usesImplicitDefault = Object.values(originalServices).some((service) => service.network_mode === void 0 && service.networks === void 0);
829
+ if (usesImplicitDefault && !Object.hasOwn(doc.networks ?? {}, "default")) doc.networks = { ...doc.networks ?? {}, default: {} };
830
+ const allocator = options.allocator ?? new GeneratedComposeNameAllocator();
831
+ const identityPrefix = options.identityPrefix ?? JSON.stringify(["dependency", options.dependencyKey, prefix]);
832
+ const make = (kind, keys) => new Map(keys.sort().map((k) => [k, allocator.allocate(JSON.stringify([identityPrefix, kind, k]), kind === "service" ? `${prefix}--${k}` : `${prefix}--${kind}--${k}`)]));
833
+ const serviceNameMap = make("service", Object.keys(doc.services ?? {}));
741
834
  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 ?? {}));
742
835
  const rewriteKeys = (obj, map) => Object.fromEntries(entries(obj).map(([k, v]) => [map.get(k) ?? k, v]));
743
- const rewriteResourceRefs = (svc) => {
836
+ const addOriginalNetworkAliases = (name, svc) => {
837
+ if (svc.network_mode !== void 0 || svc.networks === void 0) return;
838
+ const attached = Array.isArray(svc.networks) ? Object.fromEntries(svc.networks.filter((network) => typeof network === "string").map((network) => [network, null])) : svc.networks && typeof svc.networks === "object" ? { ...svc.networks } : {};
839
+ for (const [network, rawOptions] of Object.entries(attached)) {
840
+ const options2 = rawOptions && typeof rawOptions === "object" && !Array.isArray(rawOptions) ? rawOptions : {};
841
+ const aliases = Array.isArray(options2.aliases) ? options2.aliases.filter((alias) => typeof alias === "string") : [];
842
+ attached[network] = { ...options2, aliases: [.../* @__PURE__ */ new Set([...aliases, name])] };
843
+ }
844
+ svc.networks = attached;
845
+ };
846
+ const rewriteResourceRefs = (svc, originalName) => {
847
+ rewriteBuildSecretReferences(svc, secretNameMap);
744
848
  if (Array.isArray(svc.depends_on)) {
745
849
  svc.depends_on = svc.depends_on.map((v) => typeof v === "string" ? serviceNameMap.get(v) ?? v : v);
746
850
  } else if (svc.depends_on && typeof svc.depends_on === "object") svc.depends_on = rewriteKeys(svc.depends_on, serviceNameMap);
@@ -755,17 +859,14 @@ function namespaceDependencyCompose(options) {
755
859
  }
756
860
  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);
757
861
  if (Array.isArray(svc.volumes)) svc.volumes = svc.volumes.map((v) => namespaceVolume(v, volumeNameMap));
758
- if (svc.networks === void 0 && svc.network_mode === void 0 && svc.extends === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
862
+ if (svc.networks === void 0 && svc.network_mode === void 0 && networkNameMap.has("default")) svc.networks = { default: null };
759
863
  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)}`;
760
- if (svc.extends && typeof svc.extends === "object" && !svc.extends.file) {
761
- const ref = svc.extends;
762
- if (typeof ref.service === "string") ref.service = serviceNameMap.get(ref.service) ?? ref.service;
763
- }
764
864
  if (Array.isArray(svc.networks)) svc.networks = svc.networks.map((v) => typeof v === "string" ? networkNameMap.get(v) ?? v : v);
765
865
  else if (svc.networks && typeof svc.networks === "object") svc.networks = rewriteKeys(svc.networks, networkNameMap);
766
866
  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);
867
+ addOriginalNetworkAliases(originalName, svc);
767
868
  };
768
- for (const svc of Object.values(doc.services ?? {})) rewriteResourceRefs(svc);
869
+ for (const [name, svc] of Object.entries(originalServices)) rewriteResourceRefs(svc, name);
769
870
  doc.services = rewriteKeys(doc.services, serviceNameMap);
770
871
  if (doc.volumes) doc.volumes = rewriteKeys(doc.volumes, volumeNameMap);
771
872
  if (doc.networks) doc.networks = rewriteKeys(doc.networks, networkNameMap);
@@ -774,14 +875,81 @@ function namespaceDependencyCompose(options) {
774
875
  return { document: doc, serviceNameMap, volumeNameMap, networkNameMap, configNameMap, secretNameMap };
775
876
  }
776
877
 
878
+ // src/core/composition/validateComposeResourceReferences.ts
879
+ function validateComposeResourceReferences(document, context, onlyServices) {
880
+ const selected = onlyServices ? new Set(onlyServices) : void 0;
881
+ const fail = (configPath, kind, name) => {
882
+ throw new ConfigError({
883
+ sourceFile: context.sourceFile,
884
+ configPath,
885
+ ...context.stage ? { stage: context.stage } : {},
886
+ composition: context.composition,
887
+ referencedObject: name,
888
+ reason: `Compose ${kind} reference "${name}" has no top-level definition`
889
+ });
890
+ };
891
+ const exists = (kind, name) => {
892
+ const definitions = document[kind === "volume" ? "volumes" : kind === "network" ? "networks" : kind === "config" ? "configs" : "secrets"];
893
+ return Boolean(definitions && Object.hasOwn(definitions, name));
894
+ };
895
+ const check = (path20, kind, name) => {
896
+ if (kind === "network" && name === "default") return;
897
+ if (!exists(kind, name)) fail(path20, kind, name);
898
+ };
899
+ for (const [serviceName, service] of Object.entries(document.services ?? {})) {
900
+ if (selected && !selected.has(serviceName)) continue;
901
+ validateServiceResources(serviceName, service, check);
902
+ }
903
+ }
904
+ function validateServiceResources(serviceName, service, check) {
905
+ for (const mount of Array.isArray(service.volumes) ? service.volumes : []) {
906
+ const parsed = parseVolume(mount);
907
+ if (parsed?.type === "volume" && parsed.source) {
908
+ check(`services.${serviceName}.volumes`, "volume", parsed.source);
909
+ }
910
+ }
911
+ const networks = service.networks;
912
+ const networkNames = Array.isArray(networks) ? networks.filter((name) => typeof name === "string") : networks && typeof networks === "object" ? Object.keys(networks) : [];
913
+ for (const name of networkNames) {
914
+ check(`services.${serviceName}.networks`, "network", name);
915
+ }
916
+ for (const kind of ["configs", "secrets"]) {
917
+ const entries2 = service[kind];
918
+ if (!Array.isArray(entries2)) continue;
919
+ for (const entry of entries2) {
920
+ const name = typeof entry === "string" ? entry : entry && typeof entry === "object" && typeof entry.source === "string" ? entry.source : void 0;
921
+ if (name) check(`services.${serviceName}.${kind}`, kind === "configs" ? "config" : "secret", name);
922
+ }
923
+ }
924
+ for (const name of collectBuildSecretReferences(service)) {
925
+ check(`services.${serviceName}.build.secrets`, "secret", name);
926
+ }
927
+ }
928
+
929
+ // src/core/composition/composeHealthcheck.ts
930
+ function isEnabledValidComposeHealthcheck(value) {
931
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
932
+ const health = value;
933
+ if (health.disable === true) return false;
934
+ const test = health.test;
935
+ if (typeof test === "string") return test.trim().length > 0;
936
+ if (!Array.isArray(test) || !test.every((item) => typeof item === "string")) return false;
937
+ if (test[0] !== "CMD" && test[0] !== "CMD-SHELL") return false;
938
+ return test.length >= 2 && test.slice(1).some((item) => item.trim().length > 0);
939
+ }
940
+
777
941
  // src/core/composition/validateDependencyCompose.ts
778
942
  function validateDependencyCompose(dependencyKey, dependency, document, context) {
779
943
  const fail = (configPath, reason, value) => {
780
944
  throw new ConfigError({ sourceFile: context.composePath, configPath, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason: `Dependency "${dependencyKey}": ${reason}` });
781
945
  };
782
946
  if (document.include !== void 0) fail("include", "Compose include is unsupported for atomic dependency implementations");
947
+ validateComposeResourceReferences(document, { sourceFile: context.composePath, stage: context.stage, composition: "service" });
783
948
  const services = document.services ?? {};
784
949
  for (const [name, svc] of Object.entries(services)) {
950
+ assertNoServiceBuildContexts(svc, `services.${name}`, context.composePath);
951
+ if (svc.profiles !== void 0) fail(`services.${name}.profiles`, "dependency Compose profiles are unsupported because a materialized dependency is atomic");
952
+ if (svc.extends !== void 0) fail(`services.${name}.extends`, "dependency Compose extends is unsupported until effective endpoint-owner networking and health can be validated");
785
953
  if (svc.ports !== void 0) fail(`services.${name}.ports`, "raw dependency ports are forbidden");
786
954
  if (svc.network_mode === "host") fail(`services.${name}.network_mode`, "host network mode is forbidden");
787
955
  if (svc.privileged === true) fail(`services.${name}.privileged`, `privileged services are forbidden`);
@@ -804,11 +972,6 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
804
972
  for (const ref of svc.volumes_from) if (typeof ref === "string") internalRefs.push(["volumes_from", ref.split(":")[0]]);
805
973
  }
806
974
  for (const key of ["ipc", "pid"]) if (typeof svc[key] === "string" && svc[key].startsWith("service:")) internalRefs.push([key, svc[key].slice(8)]);
807
- if (svc.extends && typeof svc.extends === "object") {
808
- const ref = svc.extends;
809
- if (ref.file !== void 0) fail(`services.${name}.extends.file`, "external extends is unsupported for atomic dependency implementations");
810
- if (typeof ref.service === "string") internalRefs.push(["extends.service", ref.service]);
811
- }
812
975
  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);
813
976
  }
814
977
  if (!Object.keys(dependency.endpoints).length) return;
@@ -821,8 +984,7 @@ function validateDependencyCompose(dependencyKey, dependency, document, context)
821
984
  }
822
985
  for (const owner of owners) {
823
986
  if (services[owner].network_mode !== void 0) fail(`services.${owner}.network_mode`, `endpoint owner cannot use network_mode`);
824
- const health = services[owner].healthcheck;
825
- 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`);
987
+ if (!isEnabledValidComposeHealthcheck(services[owner].healthcheck)) fail(`services.${owner}.healthcheck`, "endpoint owner requires a valid enabled Compose healthcheck");
826
988
  }
827
989
  }
828
990
  function canonicalBuildContext(value, baseDir) {
@@ -835,10 +997,12 @@ function validateAndPrepareAppOverride(document, context) {
835
997
  const fail = (path20, reason, value) => {
836
998
  throw new ConfigError({ sourceFile: context.file, configPath: path20, stage: context.stage, composition: "service", ...value === void 0 ? {} : { value }, reason });
837
999
  };
1000
+ const allowedRootKeys = /* @__PURE__ */ new Set(["services", "volumes", "networks", "configs", "secrets"]);
1001
+ for (const key of Object.keys(document)) if (!key.startsWith("x-") && !allowedRootKeys.has(key)) fail(key, "unsupported override Compose top-level field");
838
1002
  const keys = Object.keys(document.services ?? {});
839
1003
  if (keys.length !== 1 || keys[0] !== "app") fail("services", "override must define exactly one service named app");
840
1004
  const app = structuredClone(document.services.app);
841
- 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");
1005
+ for (const k of ["ports", "depends_on", "network_mode", "container_name", "privileged", "profiles", "extends", "env_file"]) if (app[k] !== void 0) fail(`services.app.${k}`, "override cannot own endpoint or lifecycle behavior");
842
1006
  if (app.healthcheck && typeof app.healthcheck === "object") {
843
1007
  const health = app.healthcheck;
844
1008
  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");
@@ -848,8 +1012,8 @@ function validateAndPrepareAppOverride(document, context) {
848
1012
  }
849
1013
  if (app.build && typeof app.build === "object") {
850
1014
  const build = app.build;
851
- for (const key of ["target", "dockerfile"]) {
852
- if (build[key] !== void 0) {
1015
+ for (const key of Object.keys(build)) {
1016
+ if (!["args", "context"].includes(key)) {
853
1017
  fail(`services.app.build.${key}`, "override cannot change Builder-owned build configuration");
854
1018
  }
855
1019
  }
@@ -865,6 +1029,7 @@ function validateAndPrepareAppOverride(document, context) {
865
1029
  const env = normalizeComposeEnvironment(app.environment, "services.app.environment");
866
1030
  for (const k of ["EXEC_MODE", "INFRA_MODE"]) if (k in env) fail(`services.app.environment.${k}`, "override cannot set Builder-owned environment");
867
1031
  app.environment = env;
1032
+ const allocator = context.allocator ?? new GeneratedComposeNameAllocator();
868
1033
  const resourceKeys = ["volumes", "networks", "configs", "secrets"];
869
1034
  const resources = {};
870
1035
  for (const kind of resourceKeys) {
@@ -880,7 +1045,8 @@ function validateAndPrepareAppOverride(document, context) {
880
1045
  const names = /* @__PURE__ */ new Map(), mapped = {};
881
1046
  for (const [name, definition] of Object.entries(defs)) {
882
1047
  if (!refs2.has(name)) fail(`${kind}.${name}`, "override resource must be consumed by app");
883
- const target = `app-override--${context.stage}--${kind.slice(0, -1)}--${name}`;
1048
+ const prefix = context.resourceNamespace && context.resourceNamespace !== "app" ? `svc--${context.resourceNamespace}--app-override` : "app-override";
1049
+ const target = allocator.allocate(JSON.stringify(["service", context.resourceNamespace ?? "app", "override", context.stage, kind, name]), `${prefix}--${context.stage}--${kind.slice(0, -1)}--${name}`);
884
1050
  names.set(name, target);
885
1051
  mapped[target] = definition;
886
1052
  }
@@ -1002,13 +1168,14 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1002
1168
  const seed = getTemplateSeed(stage, Boolean(options.meshMode));
1003
1169
  const rawName = options.projectNameOverride ?? raw.name ?? path.basename(root);
1004
1170
  const projectName = deriveProjectName(rawName, stage);
1171
+ const nameAllocator = options.nameAllocator ?? new GeneratedComposeNameAllocator(["app", "tester", "default", options.appServiceName ?? "app"]);
1005
1172
  const namespaced = {};
1006
1173
  for (const [key, dep] of Object.entries(effective.dependencies).sort(([a], [b]) => a.localeCompare(b))) {
1007
1174
  const sourcePath = resolveInsideProject(root, dep.compose, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage });
1008
1175
  const document = rebaseComposePaths(loadComposeDocument(sourcePath, { sourceFile: buildPath, configPath: `dependencies.${key}.compose`, stage, composition: "service" }), sourcePath, options.composeOutputDir ?? root);
1009
1176
  validateDependencyCompose(key, dep, document, { composePath: sourcePath, stage });
1010
1177
  if (Object.keys(dep.endpoints).length) {
1011
- const ns = namespaceDependencyCompose({ namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document });
1178
+ const ns = namespaceDependencyCompose({ dependencyKey: key, namespacePrefix: options.namespacePrefix ? `${options.namespacePrefix}${key}` : `dep--${key}`, document, allocator: nameAllocator, identityPrefix: JSON.stringify(["service", options.appServiceName ?? "app", "dependency", key]) });
1012
1179
  namespaced[key] = { doc: ns.document, map: ns.serviceNameMap, source: sourcePath };
1013
1180
  }
1014
1181
  }
@@ -1023,7 +1190,7 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1023
1190
  const endpointOwnerMap = /* @__PURE__ */ new Map();
1024
1191
  for (const [epName, ep] of Object.entries(dep.endpoints)) endpointOwnerMap.set(epName, entry.map.get(ep.service));
1025
1192
  const endpointOwners = new Set(endpointOwnerMap.values());
1026
- materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners };
1193
+ materialized[key] = { key, composePath: entry.source, compose: item, serviceNameMap: entry.map, endpointOwnerMap, endpoints: {}, endpointOwners, serviceNames: new Set(Object.keys(item.services)) };
1027
1194
  }
1028
1195
  const appEndpoints = buildStandaloneAppEndpoints(effective, stage, options.appServiceName ?? "app");
1029
1196
  const depEndpoints = {};
@@ -1072,8 +1239,9 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1072
1239
  const depEnv = options.deferReferenceResolution ? dep.env : resolveEnv(dep.env, registry, `dependencies.${key}.env`);
1073
1240
  for (const svc of Object.values(materialized[key]?.compose.services ?? {})) mergeComposeEnvironment(svc, depEnv);
1074
1241
  }
1075
- const appEnv = options.deferReferenceResolution ? ownEnv(effective, stage) : resolveEnv(ownEnv(effective, stage), registry, "app.env");
1076
- let buildAppEnvironment = { ...appEnv };
1242
+ const buildJsonAppEnvironment = ownEnv(effective, stage);
1243
+ const appEnv = options.deferReferenceResolution ? buildJsonAppEnvironment : resolveEnv(buildJsonAppEnvironment, registry, "app.env");
1244
+ let overrideComposeAppEnvironment = {};
1077
1245
  const runtimeDotenv = path.join(root, `.env.${profile.runtimeStage}`);
1078
1246
  if (fs.existsSync(runtimeDotenv)) {
1079
1247
  const text = fs.readFileSync(runtimeDotenv, "utf8");
@@ -1128,13 +1296,15 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1128
1296
  file: overridePath,
1129
1297
  stage,
1130
1298
  expectedBuildContext: String(appBuild.context),
1131
- buildContextBaseDir: outputDir
1299
+ buildContextBaseDir: outputDir,
1300
+ allocator: nameAllocator,
1301
+ resourceNamespace: options.meshMode ? options.appServiceName ?? "app" : "app"
1132
1302
  });
1133
1303
  for (const section of ["volumes", "networks", "configs", "secrets"]) if (prepared.resources[section]) mergeDocument(compose, { services: {}, [section]: prepared.resources[section] }, "app override");
1134
1304
  const rawOverrideEnv = normalizeComposeEnvironment(prepared.app.environment, "override-compose.services.app.environment");
1135
- const overrideEnv = options.deferReferenceResolution ? rawOverrideEnv : resolveEnv(rawOverrideEnv, registry, "override-compose.services.app.environment");
1305
+ const overrideEnv = rawOverrideEnv;
1136
1306
  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" });
1137
- buildAppEnvironment = { ...appEnv, ...overrideEnv };
1307
+ overrideComposeAppEnvironment = { ...overrideEnv };
1138
1308
  const merged = { ...app, ...prepared.app };
1139
1309
  merged.environment = { ...appEnv, ...overrideEnv, ...options.externalAppEnv ? Object.fromEntries(Object.entries(options.externalAppEnv).map(([k, v]) => [k, v.replace(/\$/g, "$$$$")])) : {}, ...internal };
1140
1310
  const overrideBuild = prepared.app.build && typeof prepared.app.build === "object" ? prepared.app.build : {};
@@ -1157,8 +1327,8 @@ function compileServiceComposition(stage, projectDir, options = {}) {
1157
1327
  const testerEnv = options.deferReferenceResolution ? testerEnvRaw : resolveEnv(testerEnvRaw, registry, "tester.env");
1158
1328
  compose.services.tester = { build: { context: ".", ...raw.dockerfile ? { dockerfile: raw.dockerfile } : {}, target: "test-e2e" }, network_mode: "host", environment: testerEnv, depends_on: { app: { condition: "service_healthy" } } };
1159
1329
  }
1160
- const builderAppEnvironment = { ...buildAppEnvironment, ...options.externalAppEnv ?? {} };
1161
- 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])) };
1330
+ nameAllocator.assertUnique();
1331
+ return { compose, effectiveBuild: effective, endpoints: { app: appEndpoints, dependencies: depEndpoints }, projectName, ...profile.attachTester && !options.meshMode ? { testerServiceName: "tester" } : {}, buildJsonAppEnvironment, overrideComposeAppEnvironment, builderInternalEnvironment: { ...internal }, externalAppEnvironment: { ...options.externalAppEnv ?? {} }, dependencyServiceNames: Object.fromEntries(Object.entries(materialized).map(([key, dep]) => [key, [...dep.serviceNames]])), dependencyEnvironments: Object.fromEntries(Object.entries(effective.dependencies).map(([key, dep]) => [key, dep.env])) };
1162
1332
  }
1163
1333
 
1164
1334
  // src/core/checkers/checkEffectiveServiceStages.ts
@@ -1444,18 +1614,29 @@ function applyMeshLifecycleEdges(services, edges) {
1444
1614
  }
1445
1615
  }
1446
1616
 
1617
+ // src/core/composition/composeDependsOn.ts
1618
+ function normalizeComposeDependsOn(value) {
1619
+ if (Array.isArray(value)) {
1620
+ return Object.fromEntries(value.filter((item) => typeof item === "string").map((name) => [name, {}]));
1621
+ }
1622
+ return value && typeof value === "object" ? { ...value } : {};
1623
+ }
1624
+
1447
1625
  // src/core/mesh/v2/compileMeshTester.ts
1448
1626
  function refs(svc) {
1449
- const out = [];
1627
+ const out = /* @__PURE__ */ new Set();
1450
1628
  const add = (v) => {
1451
- if (typeof v === "string") out.push(v);
1629
+ if (typeof v === "string" && v) out.add(v);
1452
1630
  };
1453
1631
  if (Array.isArray(svc.depends_on)) svc.depends_on.forEach(add);
1454
1632
  else if (svc.depends_on && typeof svc.depends_on === "object") Object.keys(svc.depends_on).forEach(add);
1455
1633
  if (Array.isArray(svc.links)) svc.links.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1456
1634
  if (Array.isArray(svc.volumes_from)) svc.volumes_from.forEach((v) => add(typeof v === "string" ? v.split(":")[0] : v));
1457
- if (typeof svc.network_mode === "string" && svc.network_mode.startsWith("service:")) out.push(svc.network_mode.slice(8));
1458
- return out;
1635
+ for (const property of ["network_mode", "ipc", "pid"]) {
1636
+ const value = svc[property];
1637
+ if (typeof value === "string" && value.startsWith("service:")) add(value.slice("service:".length));
1638
+ }
1639
+ return [...out];
1459
1640
  }
1460
1641
  function referencedResources(svc, doc) {
1461
1642
  const sets = { volumes: /* @__PURE__ */ new Set(), networks: /* @__PURE__ */ new Set(), configs: /* @__PURE__ */ new Set(), secrets: /* @__PURE__ */ new Set() };
@@ -1479,20 +1660,25 @@ function referencedResources(svc, doc) {
1479
1660
  if (typeof n === "string" && doc[kind]?.[n]) sets[kind].add(n);
1480
1661
  }
1481
1662
  }
1663
+ for (const name of collectBuildSecretReferences(svc)) if (doc.secrets && name in doc.secrets) sets.secrets.add(name);
1482
1664
  return sets;
1483
1665
  }
1484
- function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext) {
1666
+ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelApps, stage, referenceContext, nameAllocator = new GeneratedComposeNameAllocator(effectiveTopLevelApps)) {
1485
1667
  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);
1486
1668
  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" });
1487
1669
  const included = /* @__PURE__ */ new Set(), visit = (name) => {
1488
1670
  if (included.has(name)) return;
1489
- if (!raw.services[name]) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1671
+ const service = raw.services[name];
1672
+ if (!service) throw new ConfigError({ sourceFile: file, configPath: `services.${name}`, stage, composition: "mesh", reason: "Tester service dependency does not exist" });
1673
+ if (service.extends !== void 0) throw new ConfigError({ sourceFile: file, configPath: `services.${name}.extends`, stage, composition: "mesh", reason: "Tester Compose extends is unsupported until effective Compose inheritance can be validated before host-network rewriting" });
1490
1674
  included.add(name);
1491
- for (const ref of refs(raw.services[name])) visit(ref);
1675
+ for (const ref of refs(service)) visit(ref);
1492
1676
  };
1493
1677
  visit(tester.service);
1678
+ validateComposeResourceReferences(raw, { sourceFile: file, stage, composition: "mesh" }, included);
1494
1679
  for (const name of included) {
1495
1680
  const svc = raw.services[name];
1681
+ assertNoServiceBuildContexts(svc, `services.${name}`, file);
1496
1682
  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" });
1497
1683
  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" });
1498
1684
  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" });
@@ -1504,7 +1690,7 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1504
1690
  }
1505
1691
  const selected = { services: Object.fromEntries([...included].map((k) => [k, raw.services[k]])) };
1506
1692
  for (const k of Object.keys(res)) if (res[k].size) selected[k] = Object.fromEntries([...res[k]].map((n) => [n, raw[k]?.[n]]));
1507
- const ns = namespaceDependencyCompose({ namespacePrefix: "mesh-tester", document: selected });
1693
+ const ns = namespaceDependencyCompose({ dependencyKey: "mesh-tester", namespacePrefix: "mesh-tester", document: selected, allocator: nameAllocator, identityPrefix: JSON.stringify(["mesh-tester"]) });
1508
1694
  const runner = ns.serviceNameMap.get(tester.service);
1509
1695
  const runnerSvc = ns.document.services[runner];
1510
1696
  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" });
@@ -1514,25 +1700,52 @@ function compileMeshTester(meshDir, tester, endpointRegistry, effectiveTopLevelA
1514
1700
  const env = tester.env ?? {};
1515
1701
  assertMeshTesterEnvPublic(env, "tester.env");
1516
1702
  runnerSvc.environment = { ...normalizeComposeEnvironment(runnerSvc.environment, "tester runner environment"), ...resolveMeshEnvMap(env, meshCtx, "tester.env") };
1517
- const depends = runnerSvc.depends_on && typeof runnerSvc.depends_on === "object" && !Array.isArray(runnerSvc.depends_on) ? runnerSvc.depends_on : {};
1703
+ const depends = normalizeComposeDependsOn(runnerSvc.depends_on);
1518
1704
  for (const app of effectiveTopLevelApps) depends[app] = { condition: "service_healthy" };
1519
1705
  runnerSvc.depends_on = depends;
1520
1706
  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 };
1521
1707
  }
1708
+ function validPort(value) {
1709
+ if (!/^\d+$/.test(value)) return void 0;
1710
+ const port = Number(value);
1711
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : void 0;
1712
+ }
1713
+ function parsePublishedHostPort(value) {
1714
+ if (value && typeof value === "object") {
1715
+ const published = value.published;
1716
+ if (typeof published === "number" && Number.isInteger(published)) {
1717
+ return published >= 1 && published <= 65535 ? published : void 0;
1718
+ }
1719
+ if (typeof published === "string") return validPort(published);
1720
+ return void 0;
1721
+ }
1722
+ if (typeof value !== "string") return void 0;
1723
+ const mapping = value.replace(/\/(?:tcp|udp|sctp)$/i, "");
1724
+ if (/^\d+(?:-\d+)?$/.test(mapping)) return void 0;
1725
+ if (mapping.startsWith("[")) {
1726
+ const close = mapping.indexOf("]");
1727
+ if (close < 0 || isIP(mapping.slice(1, close)) !== 6) return void 0;
1728
+ const suffix = mapping.slice(close + 1);
1729
+ const match = suffix.match(/^:(\d+)(?:-\d+)?:\d+(?:-\d+)?$/);
1730
+ return match ? validPort(match[1]) : void 0;
1731
+ }
1732
+ const parts = mapping.split(":");
1733
+ if (parts.length === 2) return validPort(parts[0]);
1734
+ if (parts.length >= 3) {
1735
+ const hostIp = parts.slice(0, -2).join(":");
1736
+ if (isIP(hostIp) === 4) return validPort(parts[parts.length - 2]);
1737
+ }
1738
+ return void 0;
1739
+ }
1740
+
1741
+ // src/utils/assertUniqueHostPortMappings.ts
1522
1742
  function assertUniqueHostPortMappings(yamlConfig) {
1523
1743
  const parsed = parse(yamlConfig);
1524
1744
  const owners = /* @__PURE__ */ new Map();
1525
1745
  for (const [serviceName, service] of Object.entries(parsed?.services ?? {})) {
1526
1746
  for (const port of service?.ports ?? []) {
1527
- let hostPort = null;
1528
- if (typeof port === "string") {
1529
- const parts = port.split(":");
1530
- if (parts.length === 2) hostPort = Number(parts[0]);
1531
- if (parts.length === 3) hostPort = Number(parts[1]);
1532
- } else if (port && typeof port === "object" && "published" in port) {
1533
- hostPort = Number(port.published);
1534
- }
1535
- if (!hostPort || !Number.isInteger(hostPort)) continue;
1747
+ const hostPort = parsePublishedHostPort(port);
1748
+ if (hostPort === void 0) continue;
1536
1749
  const existing = owners.get(hostPort);
1537
1750
  if (existing) {
1538
1751
  throw new ScriptError(
@@ -1561,6 +1774,26 @@ function appendPort(service, target, published) {
1561
1774
  ports.push({ target, published, host_ip: PUBLIC_HOST, protocol: "tcp" });
1562
1775
  service.ports = ports;
1563
1776
  }
1777
+ function buildMeshPortIntents(services, publication) {
1778
+ const intents = [];
1779
+ for (const name of Object.keys(services).sort((a, b) => a.localeCompare(b))) {
1780
+ const service = services[name];
1781
+ const appPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "app").sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1782
+ for (const pub of appPublications) {
1783
+ const endpoint = service.effectiveBuild.app.endpoints[pub.endpoint];
1784
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1785
+ }
1786
+ const dependencyNames = [...new Set(publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency").map((pub) => pub.dependency))].sort((a, b) => a.localeCompare(b));
1787
+ for (const dependency of dependencyNames) {
1788
+ const dependencyPublications = publication.filter((pub) => pub.ownerMeshService === name && pub.target === "dependency" && pub.dependency === dependency).sort((a, b) => a.endpoint.localeCompare(b.endpoint));
1789
+ for (const pub of dependencyPublications) {
1790
+ const endpoint = service.effectiveBuild.dependencies[dependency].endpoints[pub.endpoint];
1791
+ intents.push({ logicalPath: pub.logicalPath, requested: endpoint.publicPort });
1792
+ }
1793
+ }
1794
+ }
1795
+ return intents;
1796
+ }
1564
1797
  function ownerFor(pub, fragment) {
1565
1798
  return pub.target === "app" ? pub.ownerMeshService : fragment.endpoints.dependencies[pub.dependency]?.[pub.endpoint]?.networkHost ?? "";
1566
1799
  }
@@ -1568,15 +1801,20 @@ function setEnv(service, env) {
1568
1801
  const current = service.environment && typeof service.environment === "object" && !Array.isArray(service.environment) ? service.environment : {};
1569
1802
  service.environment = { ...current, ...env };
1570
1803
  }
1804
+ function attachNetworkIfCompatible(service, networkName) {
1805
+ if (service.network_mode !== void 0) return;
1806
+ service.networks = { ...normalizeNetworks(service.networks), [networkName]: null };
1807
+ }
1571
1808
  function compileMeshComposition(stage, meshDir, options = {}) {
1572
1809
  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);
1573
1810
  const rawName = raw.name ?? path.basename(meshDir), projectName = deriveProjectName(rawName, stage, meshDir);
1811
+ const nameAllocator = new GeneratedComposeNameAllocator(["mesh", "default", ...Object.keys(services), ...Object.keys(services).map((name) => `mesh--${name}`)]);
1574
1812
  const fragments = {};
1575
1813
  const compose = { name: projectName, services: {}, networks: { mesh: { driver: "bridge" } } };
1576
1814
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
1577
1815
  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" });
1578
1816
  const suppress = new Set(Object.keys(svc.dependencyBindings));
1579
- 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 });
1817
+ const fragment = compileServiceComposition(stage, svc.absolutePath, { nameAllocator, full: true, meshMode: true, projectNameOverride: projectName, namespacePrefix: `svc--${name}--dep--`, suppressDependencies: suppress, externalAppEnv: svc.meshEnv, deferReferenceResolution: true, appServiceName: name, composeOutputDir: meshDir, validationMode: options.validationMode });
1580
1818
  fragments[name] = fragment;
1581
1819
  mergeFragment(compose, fragment.compose, name);
1582
1820
  const app = compose.services[name];
@@ -1590,32 +1828,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1590
1828
  for (const ep of Object.values(fragment.endpoints.dependencies[dep] ?? {})) {
1591
1829
  const owner = ep.networkHost;
1592
1830
  const ownerService = compose.services[owner];
1593
- if (ownerService) {
1594
- const old = normalizeNetworks(ownerService.networks);
1595
- old[privateName] = null;
1596
- ownerService.networks = old;
1597
- }
1831
+ if (ownerService) attachNetworkIfCompatible(ownerService, privateName);
1598
1832
  }
1599
- for (const generated of Object.keys(fragment.compose.services).filter((k) => k.startsWith(`svc--${name}--dep--${dep}--`))) {
1833
+ for (const generated of fragment.dependencyServiceNames?.[dep] ?? []) {
1600
1834
  const ownerService = compose.services[generated];
1601
- const old = normalizeNetworks(ownerService.networks);
1602
- old[privateName] = null;
1603
- ownerService.networks = old;
1835
+ attachNetworkIfCompatible(ownerService, privateName);
1604
1836
  }
1605
1837
  }
1606
1838
  }
1607
1839
  app.networks = { ...normalizeNetworks(app.networks), ...networks };
1608
1840
  }
1609
- const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = [];
1610
- 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))) {
1611
- const ep = services[name].effectiveBuild.app.endpoints[pub.endpoint];
1612
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1613
- }
1614
- 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}`))) {
1615
- const ep = services[name].effectiveBuild.dependencies[pub.dependency].endpoints[pub.endpoint];
1616
- intents.push({ logicalPath: pub.logicalPath, requested: ep.publicPort });
1617
- }
1618
- const ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
1841
+ const publication = resolveMeshPublication(services, bindingMap, stage, meshPath), intents = buildMeshPortIntents(services, publication), ports = allocateHostPorts(meshDir, stage, intents, Boolean(options.validationMode));
1619
1842
  const endpoints = { app: {}, dependencies: {} };
1620
1843
  for (const [name, svc] of Object.entries(services)) {
1621
1844
  endpoints.app[name] = {};
@@ -1652,15 +1875,17 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1652
1875
  const refContext = { services, bindings: bindingMap, endpoints, stage, meshJsonPath: meshPath };
1653
1876
  for (const [name, fragment] of Object.entries(fragments)) {
1654
1877
  const app = compose.services[name];
1655
- const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildAppEnvironment ?? fragment.builderAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1878
+ const buildEnv = resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, refContext, `services.${name}.app.env`);
1656
1879
  const meshEnv = resolveMeshEnvMap(fragment.externalAppEnvironment ?? {}, refContext, `services.${name}.env`);
1657
- setEnv(app, { ...buildEnv, ...meshEnv });
1880
+ app.environment = { ...buildEnv, ...fragment.overrideComposeAppEnvironment ?? {}, ...meshEnv, ...fragment.builderInternalEnvironment ?? {} };
1658
1881
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) {
1659
1882
  const logicalBinding = bindingMap.get(bindingKey(name, depName));
1660
1883
  if (logicalBinding) continue;
1661
1884
  const resolvedDep = resolveServiceBuildEnvThroughMesh(name, depEnv, refContext, `services.${name}.dependencies.${depName}.env`);
1662
- const prefix = `svc--${name}--dep--${depName}--`;
1663
- for (const [serviceName, service] of Object.entries(compose.services)) if (serviceName.startsWith(prefix)) setEnv(service, resolvedDep);
1885
+ for (const serviceName of fragment.dependencyServiceNames?.[depName] ?? []) {
1886
+ const service = compose.services[serviceName];
1887
+ if (service) setEnv(service, resolvedDep);
1888
+ }
1664
1889
  }
1665
1890
  }
1666
1891
  const edges = buildMeshLifecycleEdges(services, bindingMap, stage, meshPath);
@@ -1695,18 +1920,85 @@ function compileMeshComposition(stage, meshDir, options = {}) {
1695
1920
  let testerServiceName;
1696
1921
  if (stage === "e2e") {
1697
1922
  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? }" });
1698
- const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext) : void 0;
1923
+ const built = raw.tester ? compileMeshTester(meshDir, raw.tester, endpoints, Object.keys(services).sort(), "e2e", refContext, nameAllocator) : void 0;
1699
1924
  if (built) {
1700
1925
  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 } : {} };
1701
1926
  mergeFragment(compose, fragment, "mesh tester");
1702
1927
  testerServiceName = built.runnerServiceName;
1703
1928
  }
1704
1929
  }
1930
+ nameAllocator.assertUnique();
1705
1931
  const yaml = stringify(compose);
1706
1932
  assertUniqueHostPortMappings(yaml);
1707
1933
  return { compose, effectiveMesh: effective, loadedServices: services, endpoints, projectName, ...testerServiceName ? { testerServiceName } : {} };
1708
1934
  }
1709
1935
 
1936
+ // src/core/mesh/v2/validateMeshTestStage.ts
1937
+ function validateMeshTestStage(services, meshDir, meshPath, validationMode = false) {
1938
+ const bindings = bindingsMap(buildDependencyBindings(services, "test", meshPath));
1939
+ const publication = resolveMeshPublication(
1940
+ services,
1941
+ bindings,
1942
+ "test",
1943
+ meshPath
1944
+ );
1945
+ for (const pub of publication) {
1946
+ if (pub.target === "dependency") {
1947
+ throw new ConfigError({
1948
+ sourceFile: meshPath,
1949
+ configPath: `services.${pub.ownerMeshService}.publish`,
1950
+ stage: "test",
1951
+ composition: "mesh",
1952
+ value: pub.logicalPath,
1953
+ reason: "mesh.test is isolated; dependency endpoints are not materialized and cannot be published"
1954
+ });
1955
+ }
1956
+ }
1957
+ const appPublications = publication.filter((pub) => pub.target === "app").sort(
1958
+ (a, b) => a.ownerMeshService.localeCompare(b.ownerMeshService) || a.endpoint.localeCompare(b.endpoint)
1959
+ ).map((pub) => {
1960
+ const endpoint = services[pub.ownerMeshService].effectiveBuild.app.endpoints[pub.endpoint];
1961
+ return {
1962
+ meshService: pub.ownerMeshService,
1963
+ endpoint: pub.endpoint,
1964
+ logicalPath: pub.logicalPath,
1965
+ containerPort: endpoint.port,
1966
+ requested: endpoint.publicPort
1967
+ };
1968
+ });
1969
+ const intents = appPublications.map((pub) => ({
1970
+ logicalPath: pub.logicalPath,
1971
+ requested: pub.requested
1972
+ }));
1973
+ const allocatedPorts = allocateHostPorts(
1974
+ meshDir,
1975
+ "test",
1976
+ intents,
1977
+ validationMode
1978
+ );
1979
+ return { bindings, appPublications, allocatedPorts };
1980
+ }
1981
+ function applyTestAppPublications(validated, meshService, app, endpointRegistry) {
1982
+ for (const publication of validated.appPublications) {
1983
+ if (publication.meshService !== meshService) continue;
1984
+ const published = validated.allocatedPorts.get(publication.logicalPath);
1985
+ const ports = Array.isArray(app.ports) ? app.ports : [];
1986
+ ports.push({
1987
+ target: publication.containerPort,
1988
+ published,
1989
+ host_ip: PUBLIC_HOST,
1990
+ protocol: "tcp"
1991
+ });
1992
+ app.ports = ports;
1993
+ const endpoint = endpointRegistry[publication.endpoint];
1994
+ if (endpoint) {
1995
+ endpoint.publicHost = PUBLIC_HOST;
1996
+ endpoint.publicPort = published;
1997
+ endpoint.effectivelyPublished = true;
1998
+ }
1999
+ }
2000
+ }
2001
+
1710
2002
  // src/core/mesh/checkers/checkMeshServices.ts
1711
2003
  function checkMeshServices(mesh, meshDir) {
1712
2004
  const root = resolveProjectDir(meshDir), meshPath = path.join(root, "mesh.json");
@@ -1714,6 +2006,7 @@ function checkMeshServices(mesh, meshDir) {
1714
2006
  for (const stage of ["dev", "prod", "test", "e2e"]) {
1715
2007
  const effective = resolveMeshStage(mesh, stage, meshPath);
1716
2008
  const services = loadEffectiveMeshServices(root, effective, stage);
2009
+ if (stage === "test") validateMeshTestStage(services, root, meshPath, true);
1717
2010
  for (const [name, svc] of Object.entries(services)) {
1718
2011
  if (!checked.has(svc.absolutePath)) {
1719
2012
  console.log(pc22.cyan(`
@@ -1728,7 +2021,7 @@ function checkMeshServices(mesh, meshDir) {
1728
2021
  for (const key of ["EXEC_MODE", "INFRA_MODE", ...Object.values(svc.effectiveBuild.app.endpoints).some((ep) => ep.primary) ? ["PORT"] : []]) {
1729
2022
  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" });
1730
2023
  }
1731
- resolveServiceBuildEnvThroughMesh(name, fragment.builderAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
2024
+ resolveServiceBuildEnvThroughMesh(name, fragment.buildJsonAppEnvironment ?? {}, ctx, `services.${name}.app.env`);
1732
2025
  for (const [depName, depEnv] of Object.entries(fragment.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, ctx, `services.${name}.dependencies.${depName}.env`);
1733
2026
  resolveMeshEnvMap(svc.meshEnv, ctx, `services.${name}.env`);
1734
2027
  }
@@ -2197,15 +2490,9 @@ function extractHostPorts(yamlConfig) {
2197
2490
  if (parsed?.services && typeof parsed.services === "object") {
2198
2491
  for (const svc of Object.values(parsed.services)) {
2199
2492
  if (Array.isArray(svc?.ports)) {
2200
- for (const p of svc.ports) {
2201
- if (typeof p === "string") {
2202
- const parts = p.split(":");
2203
- const hostPort = parts.length > 1 ? parseInt(parts[0], 10) : parseInt(p, 10);
2204
- if (!isNaN(hostPort)) ports.push(hostPort);
2205
- } else if (typeof p === "object" && p.published) {
2206
- const hostPort = parseInt(p.published, 10);
2207
- if (!isNaN(hostPort)) ports.push(hostPort);
2208
- }
2493
+ for (const mapping of svc.ports) {
2494
+ const hostPort = parsePublishedHostPort(mapping);
2495
+ if (hostPort !== void 0) ports.push(hostPort);
2209
2496
  }
2210
2497
  }
2211
2498
  }
@@ -2379,7 +2666,7 @@ async function runMeshProd(options = {}) {
2379
2666
  return status;
2380
2667
  }
2381
2668
  async function runMeshTestUnit(options = {}) {
2382
- const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test");
2669
+ const meshDir = resolveProjectDir(options.projectDir), meshPath = path.join(meshDir, "mesh.json"), raw = getMeshJson(meshDir), effective = resolveMeshStage(raw, "test", meshPath), services = loadEffectiveMeshServices(meshDir, effective, "test"), validated = validateMeshTestStage(services, meshDir, meshPath, Boolean(options.dryRun));
2383
2670
  console.log(pc22.bold(pc22.blue("\n[1/2] MESH SERVICE UNIT/ISOLATED TESTS\n")));
2384
2671
  for (const [name, svc] of Object.entries(services).sort(([a], [b]) => a.localeCompare(b))) {
2385
2672
  console.log(pc22.cyan(`-> Running isolated unit tests for [${name}]`));
@@ -2388,11 +2675,12 @@ async function runMeshTestUnit(options = {}) {
2388
2675
  const refCtx = { services: { [name]: svc }, bindings: /* @__PURE__ */ new Map(), endpoints, stage: "test", meshJsonPath: meshPath };
2389
2676
  const env = svc.meshEnv;
2390
2677
  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" });
2391
- const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.builderAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2678
+ const resolvedBuild = resolveServiceBuildEnvThroughMesh(name, compiled.buildJsonAppEnvironment ?? {}, refCtx, `services.${name}.app.env`);
2392
2679
  for (const [depName, depEnv] of Object.entries(compiled.dependencyEnvironments ?? {})) resolveServiceBuildEnvThroughMesh(name, depEnv, refCtx, `services.${name}.dependencies.${depName}.env`);
2393
2680
  const resolved = resolveMeshEnvMap(env, refCtx, `services.${name}.env`);
2394
2681
  const app = compiled.compose.services.app;
2395
- app.environment = { ...app.environment, ...resolvedBuild, ...resolved };
2682
+ app.environment = { ...resolvedBuild, ...compiled.overrideComposeAppEnvironment ?? {}, ...resolved, ...compiled.builderInternalEnvironment ?? {} };
2683
+ applyTestAppPublications(validated, name, app, compiled.endpoints.app);
2396
2684
  const projectName = `${deriveProjectName(raw.name ?? path.basename(meshDir), "dev")}-${name}-test`;
2397
2685
  compiled.compose.name = projectName;
2398
2686
  const yaml = stringify(compiled.compose);