@bleedingdev/modern-js-app-tools-extensions 3.9.0-ultramodern.1 → 3.9.0-ultramodern.10

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 (118) hide show
  1. package/dist/cjs/backend-federation-build/codegen.js +256 -0
  2. package/dist/cjs/backend-federation-build/config.js +189 -0
  3. package/dist/cjs/backend-federation-build/emit.js +150 -0
  4. package/dist/cjs/backend-federation-build/index.js +53 -0
  5. package/dist/cjs/build-config/build-environment.js +268 -0
  6. package/dist/cjs/build-config/precompress/plugin.js +124 -0
  7. package/dist/cjs/build-config/precompress/types.js +18 -0
  8. package/dist/cjs/build-config/public.js +46 -0
  9. package/dist/cjs/cloudflare/constants.js +1 -1
  10. package/dist/cjs/cloudflare/delivery-unit.js +7 -16
  11. package/dist/cjs/cloudflare-output-contract.js +37 -1
  12. package/dist/cjs/cloudflare-output-verifier/identity.js +6 -6
  13. package/dist/cjs/cloudflare-output-verifier/worker-bundles.js +4 -1
  14. package/dist/cjs/config.js +29 -1
  15. package/dist/cjs/deploy-output/npmAliases.js +226 -0
  16. package/dist/cjs/deploy-output/plugin.js +76 -0
  17. package/dist/cjs/deploy-output/target.js +48 -0
  18. package/dist/cjs/native-type-checker.js +193 -0
  19. package/dist/cjs/policy-defaults.js +101 -0
  20. package/dist/cjs/release-envelope/framework-output.js +77 -32
  21. package/dist/cjs/release-envelope/plugin.js +5 -3
  22. package/dist/cjs/release-identity.js +3 -6
  23. package/dist/cjs/runtime-package-resolution.js +118 -0
  24. package/dist/esm/backend-federation-build/codegen.mjs +205 -0
  25. package/dist/esm/backend-federation-build/config.mjs +116 -0
  26. package/dist/esm/backend-federation-build/emit.mjs +99 -0
  27. package/dist/esm/backend-federation-build/index.mjs +1 -0
  28. package/dist/esm/build-config/build-environment.mjs +224 -0
  29. package/dist/esm/build-config/precompress/plugin.mjs +76 -0
  30. package/dist/esm/build-config/precompress/types.mjs +0 -0
  31. package/dist/esm/build-config/public.mjs +1 -0
  32. package/dist/esm/cloudflare/constants.mjs +1 -1
  33. package/dist/esm/cloudflare/delivery-unit.mjs +1 -10
  34. package/dist/esm/cloudflare-output-contract.mjs +35 -2
  35. package/dist/esm/cloudflare-output-verifier/identity.mjs +1 -1
  36. package/dist/esm/cloudflare-output-verifier/worker-bundles.mjs +5 -2
  37. package/dist/esm/config.mjs +1 -0
  38. package/dist/esm/deploy-output/npmAliases.mjs +174 -0
  39. package/dist/esm/deploy-output/plugin.mjs +28 -0
  40. package/dist/esm/deploy-output/target.mjs +10 -0
  41. package/dist/esm/native-type-checker.mjs +142 -0
  42. package/dist/esm/policy-defaults.mjs +45 -0
  43. package/dist/esm/release-envelope/framework-output.mjs +51 -6
  44. package/dist/esm/release-envelope/plugin.mjs +5 -3
  45. package/dist/esm/release-identity.mjs +3 -6
  46. package/dist/esm/runtime-package-resolution.mjs +60 -0
  47. package/dist/esm-node/backend-federation-build/codegen.mjs +206 -0
  48. package/dist/esm-node/backend-federation-build/config.mjs +117 -0
  49. package/dist/esm-node/backend-federation-build/emit.mjs +100 -0
  50. package/dist/esm-node/backend-federation-build/index.mjs +2 -0
  51. package/dist/esm-node/build-config/build-environment.mjs +225 -0
  52. package/dist/esm-node/build-config/precompress/plugin.mjs +77 -0
  53. package/dist/esm-node/build-config/precompress/types.mjs +1 -0
  54. package/dist/esm-node/build-config/public.mjs +2 -0
  55. package/dist/esm-node/cloudflare/constants.mjs +1 -1
  56. package/dist/esm-node/cloudflare/delivery-unit.mjs +1 -10
  57. package/dist/esm-node/cloudflare-output-contract.mjs +35 -2
  58. package/dist/esm-node/cloudflare-output-verifier/identity.mjs +1 -1
  59. package/dist/esm-node/cloudflare-output-verifier/worker-bundles.mjs +5 -2
  60. package/dist/esm-node/config.mjs +1 -0
  61. package/dist/esm-node/deploy-output/npmAliases.mjs +175 -0
  62. package/dist/esm-node/deploy-output/plugin.mjs +31 -0
  63. package/dist/esm-node/deploy-output/target.mjs +11 -0
  64. package/dist/esm-node/native-type-checker.mjs +143 -0
  65. package/dist/esm-node/policy-defaults.mjs +46 -0
  66. package/dist/esm-node/release-envelope/framework-output.mjs +51 -6
  67. package/dist/esm-node/release-envelope/plugin.mjs +5 -3
  68. package/dist/esm-node/release-identity.mjs +3 -6
  69. package/dist/esm-node/runtime-package-resolution.mjs +61 -0
  70. package/dist/types/backend-federation-build/codegen.d.ts +86 -0
  71. package/dist/types/backend-federation-build/config.d.ts +102 -0
  72. package/dist/types/backend-federation-build/emit.d.ts +21 -0
  73. package/dist/types/backend-federation-build/index.d.ts +2 -0
  74. package/dist/types/build-config/build-environment.d.ts +22 -0
  75. package/dist/types/build-config/precompress/plugin.d.ts +4 -0
  76. package/dist/types/build-config/precompress/types.d.ts +19 -0
  77. package/dist/types/build-config/public.d.ts +2 -0
  78. package/dist/types/cloudflare/constants.d.ts +1 -1
  79. package/dist/types/cloudflare/delivery-unit.d.ts +2 -2
  80. package/dist/types/cloudflare/worker-manifest.d.ts +2 -2
  81. package/dist/types/cloudflare-output-contract.d.ts +2 -1
  82. package/dist/types/cloudflare-output-verifier/identity.d.ts +1 -1
  83. package/dist/types/config.d.ts +2 -0
  84. package/dist/types/deploy-output/npmAliases.d.ts +14 -0
  85. package/dist/types/deploy-output/plugin.d.ts +15 -0
  86. package/dist/types/deploy-output/target.d.ts +6 -0
  87. package/dist/types/native-type-checker.d.ts +15 -0
  88. package/dist/types/policy-defaults.d.ts +46 -0
  89. package/dist/types/precompress/LICENSE +20 -0
  90. package/dist/types/precompress/index.d.ts +76 -0
  91. package/dist/types/release-envelope/framework-output.d.ts +2 -1
  92. package/dist/types/runtime-package-resolution.d.ts +28 -0
  93. package/package.json +71 -13
  94. package/src/backend-federation-build/codegen.ts +245 -0
  95. package/src/backend-federation-build/config.ts +356 -0
  96. package/src/backend-federation-build/emit.ts +202 -0
  97. package/src/backend-federation-build/index.ts +2 -0
  98. package/src/build-config/build-environment.ts +404 -0
  99. package/src/build-config/precompress/plugin.ts +140 -0
  100. package/src/build-config/precompress/types.ts +26 -0
  101. package/src/build-config/public.ts +6 -0
  102. package/src/cloudflare/constants.ts +1 -1
  103. package/src/cloudflare/delivery-unit.ts +3 -20
  104. package/src/cloudflare/worker-manifest.ts +1 -0
  105. package/src/cloudflare-builder.ts +1 -0
  106. package/src/cloudflare-output-contract.ts +37 -0
  107. package/src/cloudflare-output-verifier/identity.ts +1 -1
  108. package/src/cloudflare-output-verifier/worker-bundles.ts +5 -3
  109. package/src/config.ts +7 -0
  110. package/src/deploy-output/npmAliases.ts +333 -0
  111. package/src/deploy-output/plugin.ts +49 -0
  112. package/src/deploy-output/target.ts +23 -0
  113. package/src/native-type-checker.ts +183 -0
  114. package/src/policy-defaults.ts +127 -0
  115. package/src/release-envelope/framework-output.ts +135 -4
  116. package/src/release-envelope/plugin.ts +15 -3
  117. package/src/release-identity.ts +3 -2
  118. package/src/runtime-package-resolution.ts +115 -0
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import promises from "node:fs/promises";
3
3
  import node_path from "node:path";
4
- import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, ULTRAMODERN_BUILD_ARTIFACT_FILE, isUltramodernBuildArtifact } from "@modern-js/utils/universal";
4
+ import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, ULTRAMODERN_BUILD_ARTIFACT_FILE, isUltramodernBuildArtifact } from "@modern-js/backend-federation-contracts";
5
5
  import { canonicalSerializeMicroVerticalReleaseEnvelope, createMicroVerticalReleaseEnvelope, verifyMicroVerticalReleaseEnvelope } from "./index.mjs";
6
6
  const MICROVERTICAL_RELEASE_ENVELOPE_PATH = 'release/microvertical-release-envelope.json';
7
7
  const MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_PATH = 'release/microvertical-release-identity-carriers.json';
@@ -21,6 +21,46 @@ const collectNestedStrings = (value, key)=>{
21
21
  ...collectNestedStrings(entryValue, key)
22
22
  ]);
23
23
  };
24
+ const emptyProducerRouteModules = async (distDirectory, files, manifest, manifestLogicalPath)=>{
25
+ if (!isRecord(manifest) || !Array.isArray(manifest.exposes) || 0 !== manifest.exposes.length || !Array.isArray(manifest.remotes) || 0 !== manifest.remotes.length || !isRecord(manifest.metaData) || !isRecord(manifest.metaData.remoteEntry) || '' !== manifest.metaData.remoteEntry.name || '' !== manifest.metaData.remoteEntry.path || 'global' !== manifest.metaData.remoteEntry.type) return [];
26
+ const publicPath = manifest.metaData.publicPath;
27
+ const safeReference = (value)=>'string' == typeof value && value.length > 0 && !/[\\\\%?#\s]/u.test(value) && !value.split('/').some((segment)=>'.' === segment || '..' === segment);
28
+ if (!safeReference(publicPath)) return [];
29
+ const absoluteBase = /^https?:\/\//u.test(publicPath);
30
+ if ('auto' !== publicPath && (!publicPath.endsWith('/') || !absoluteBase && (!publicPath.startsWith('/') || publicPath.startsWith('//')))) return [];
31
+ if (absoluteBase) {
32
+ const base = new URL(publicPath);
33
+ if (base.username || base.password || base.href !== publicPath) return [];
34
+ }
35
+ const directory = node_path.posix.dirname(manifestLogicalPath);
36
+ const routesManifest = await readJson(node_path.join(distDirectory, directory, 'routes-manifest.json'));
37
+ if (!isRecord(routesManifest) || !isRecord(routesManifest.routeAssets)) return [];
38
+ const modules = new Set();
39
+ for (const route of Object.values(routesManifest.routeAssets)){
40
+ if (!isRecord(route) || !Array.isArray(route.assets)) return [];
41
+ for (const reference of route.assets){
42
+ if (!safeReference(reference) || reference.startsWith('//')) return [];
43
+ let relative = reference;
44
+ if (/^https?:\/\//u.test(reference)) {
45
+ if (!absoluteBase || !reference.startsWith(publicPath)) return [];
46
+ relative = reference.slice(publicPath.length);
47
+ } else if (reference.startsWith('/')) {
48
+ const prefix = 'auto' === publicPath ? '/' : absoluteBase ? new URL(publicPath).pathname : publicPath;
49
+ if (!reference.startsWith(prefix)) return [];
50
+ relative = reference.slice(prefix.length);
51
+ }
52
+ if (!/^(?:static|html|public)\/[^:]+$/u.test(relative) || relative.includes('//')) return [];
53
+ const logicalPath = node_path.posix.join(directory, relative);
54
+ if (!files.includes(logicalPath)) return [];
55
+ const assetStat = await promises.lstat(node_path.join(distDirectory, logicalPath));
56
+ if (!assetStat.isFile()) return [];
57
+ if (COMPILED_MODULE_PATTERN.test(logicalPath)) modules.add(logicalPath);
58
+ }
59
+ }
60
+ return [
61
+ ...modules
62
+ ];
63
+ };
24
64
  const manifestReferencedClientModules = async (distDirectory, files, manifestLogicalPath = 'mf-manifest.json')=>{
25
65
  const manifest = await readJson(node_path.join(distDirectory, manifestLogicalPath));
26
66
  const references = [
@@ -30,9 +70,10 @@ const manifestReferencedClientModules = async (distDirectory, files, manifestLog
30
70
  ...collectNestedStrings(manifest, 'async')
31
71
  ];
32
72
  const normalizedReferences = new Set(references.filter((value)=>'string' == typeof value).map((value)=>value.replace(/^https?:\/\/[^/]+/u, '')).map((value)=>value.replace(/^\/+/u, '')));
33
- return files.filter((logicalPath)=>COMPILED_MODULE_PATTERN.test(logicalPath) && [
73
+ const modules = files.filter((logicalPath)=>COMPILED_MODULE_PATTERN.test(logicalPath) && [
34
74
  ...normalizedReferences
35
75
  ].some((reference)=>reference === logicalPath || reference.endsWith(`/${logicalPath}`) || logicalPath.endsWith(`/${reference}`)));
76
+ return modules.length > 0 ? modules : emptyProducerRouteModules(distDirectory, files, manifest, manifestLogicalPath);
36
77
  };
37
78
  const routeReferencedSsrModules = async (distDirectory, files, target, routeSpecLogicalPath = 'route.json')=>{
38
79
  const routeSpec = await readJson(node_path.join(distDirectory, routeSpecLogicalPath));
@@ -82,11 +123,14 @@ const writeReleaseEnvelope = async (artifactRoot, envelope)=>{
82
123
  if (!envelopePath) throw new Error('[ultramodern-release-envelope] could not resolve release envelope path.');
83
124
  await promises.writeFile(envelopePath, `${canonicalSerializeMicroVerticalReleaseEnvelope(envelope)}\n`);
84
125
  };
85
- const readBuildArtifact = async (distDirectory)=>{
126
+ const readBuildArtifact = async (distDirectory, requirePromotable = true)=>{
86
127
  const artifactPath = node_path.join(distDirectory, ULTRAMODERN_BUILD_ARTIFACT_FILE);
87
128
  const artifact = await readJson(artifactPath);
88
129
  if (!isUltramodernBuildArtifact(artifact)) throw new Error(`[ultramodern-release-envelope] ${ULTRAMODERN_BUILD_ARTIFACT_FILE} is missing or invalid.`);
89
- if ('workspace' === artifact.deliveryUnit.sourceRevision) throw new Error('[ultramodern-release-envelope] sourceRevision "workspace" cannot produce a promotable full-stack envelope.');
130
+ if ('workspace' === artifact.deliveryUnit.sourceRevision) {
131
+ if (!requirePromotable) return;
132
+ throw new Error('[ultramodern-release-envelope] sourceRevision "workspace" cannot produce a promotable full-stack envelope.');
133
+ }
90
134
  return artifact;
91
135
  };
92
136
  const assertIdentityBlock = (value, identity, location, includeReleaseVersion)=>{
@@ -284,7 +328,7 @@ const pathExists = async (filePath)=>{
284
328
  return false;
285
329
  }
286
330
  };
287
- const emitFrameworkMicroVerticalReleaseEnvelope = async ({ apiOnly, distDirectory, target })=>{
331
+ const emitFrameworkMicroVerticalReleaseEnvelope = async ({ apiOnly, distDirectory, requirePromotable = true, target })=>{
288
332
  if (apiOnly) return;
289
333
  const backendManifestPath = node_path.join(distDirectory, BACKEND_FEDERATION_MANIFEST_FILE);
290
334
  const backendContainerPath = node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE);
@@ -294,7 +338,8 @@ const emitFrameworkMicroVerticalReleaseEnvelope = async ({ apiOnly, distDirector
294
338
  ]);
295
339
  if (!hasBackendManifest && !hasBackendContainer) return;
296
340
  if (!hasBackendManifest || !hasBackendContainer) throw new Error('[ultramodern-release-envelope] full-stack MicroVertical backend federation manifest and container must be emitted together.');
297
- const buildArtifact = await readBuildArtifact(distDirectory);
341
+ const buildArtifact = await readBuildArtifact(distDirectory, requirePromotable);
342
+ if (!buildArtifact) return;
298
343
  const identity = {
299
344
  unitId: buildArtifact.deliveryUnit.unitId,
300
345
  buildMarker: buildArtifact.deliveryUnit.buildMarker,
@@ -10,24 +10,26 @@ const createUltramodernReleaseEnvelopePlugin = ({ resolveDeployTarget })=>({
10
10
  name: '@modern-js/ultramodern-release-envelope',
11
11
  pre: [
12
12
  '@modern-js/backend-federation-build',
13
- '@modern-js/plugin-bff'
13
+ '@modern-js/plugin-bff',
14
+ '@modern-js/deploy-output-aliases'
14
15
  ],
15
16
  post: [
16
17
  '@modern-js/plugin-deploy'
17
18
  ],
18
19
  setup (api) {
19
- const emitBuildEnvelope = async (target)=>{
20
+ const emitBuildEnvelope = async (target, requirePromotable = true)=>{
20
21
  const { apiOnly, distDirectory } = api.getAppContext();
21
22
  await emitFrameworkMicroVerticalReleaseEnvelope({
22
23
  apiOnly,
23
24
  distDirectory,
25
+ requirePromotable,
24
26
  target
25
27
  });
26
28
  };
27
29
  api.onAfterBuild(async ()=>{
28
30
  const configuredTarget = resolveDeployTarget(api.getNormalizedConfig());
29
31
  if ('node' !== configuredTarget && 'cloudflare' !== configuredTarget) return;
30
- await emitBuildEnvelope(configuredTarget);
32
+ await emitBuildEnvelope(configuredTarget, false);
31
33
  });
32
34
  api.onBeforeDeploy(async ()=>{
33
35
  const configuredTarget = resolveActiveDeployTarget(api, resolveDeployTarget);
@@ -4,11 +4,8 @@ const BUILD_MARKER_NAMESPACE = 'ultramodern-delivery-unit-release-build-marker:v
4
4
  const PROMOTABLE_SOURCE_REVISION_PATTERN = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;
5
5
  const gitOutput = (workspaceRoot, args)=>{
6
6
  try {
7
- return execFileSync('git', [
8
- '-C',
9
- workspaceRoot,
10
- ...args
11
- ], {
7
+ return execFileSync('git', args, {
8
+ cwd: workspaceRoot,
12
9
  encoding: 'utf8',
13
10
  stdio: [
14
11
  'ignore',
@@ -43,7 +40,7 @@ const resolveUltramodernSourceRevision = (workspaceRoot = process.cwd(), configu
43
40
  ]);
44
41
  const status = gitOutput(gitRoot, [
45
42
  'status',
46
- '--porcelain=v1',
43
+ '--porcelain',
47
44
  '--untracked-files=all'
48
45
  ]);
49
46
  if (!revision || void 0 === status || status.length > 0) return 'workspace';
@@ -0,0 +1,60 @@
1
+ import node_fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import node_path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const findHostingModuleDirectory = (packageName, fromDirectory)=>{
6
+ let directory = node_path.resolve(fromDirectory);
7
+ for(;;){
8
+ const candidate = node_path.join(directory, 'node_modules');
9
+ if (node_fs.existsSync(node_path.join(candidate, packageName))) return candidate;
10
+ const parent = node_path.dirname(directory);
11
+ if (parent === directory) return;
12
+ directory = parent;
13
+ }
14
+ };
15
+ const collectRuntimePackageModuleDirectories = (packageNames, registrarUrl)=>{
16
+ const registrarDirectory = node_path.dirname(fileURLToPath(registrarUrl));
17
+ const directories = [];
18
+ for (const packageName of packageNames){
19
+ const directory = findHostingModuleDirectory(packageName, registrarDirectory);
20
+ if (directory && !directories.includes(directory)) directories.push(directory);
21
+ }
22
+ return directories;
23
+ };
24
+ const appendModuleDirectories = (config, directories)=>{
25
+ if (0 === directories.length) return;
26
+ config.resolve ??= {};
27
+ const existing = config.resolve.modules ?? [
28
+ 'node_modules'
29
+ ];
30
+ config.resolve.modules = [
31
+ ...existing,
32
+ ...directories.filter((directory)=>!existing.includes(directory))
33
+ ];
34
+ };
35
+ const createRuntimePackageResolutionPlugin = (directories)=>({
36
+ name: 'ultramodern:runtime-package-resolution',
37
+ setup (api) {
38
+ api.modifyRspackConfig({
39
+ order: 'post',
40
+ handler (config) {
41
+ appendModuleDirectories(config, directories);
42
+ }
43
+ });
44
+ api.onBeforeCreateCompiler({
45
+ order: 'post',
46
+ handler ({ bundlerConfigs }) {
47
+ for (const config of bundlerConfigs)appendModuleDirectories(config, directories);
48
+ }
49
+ });
50
+ }
51
+ });
52
+ const canResolveRuntimePackage = (packageName, registrarUrl)=>{
53
+ try {
54
+ createRequire(registrarUrl).resolve(packageName);
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ };
60
+ export { canResolveRuntimePackage, collectRuntimePackageModuleDirectories, createRuntimePackageResolutionPlugin, findHostingModuleDirectory };
@@ -0,0 +1,206 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, formatBackendFederationValidationErrors, validateBackendFederationManifest } from "@modern-js/backend-federation-contracts";
4
+ import { build } from "esbuild";
5
+ import { normalizeRelativePath } from "./config.mjs";
6
+ const createRelativeImportSpecifier = (fromDirectory, toFile)=>{
7
+ const relativePath = normalizeRelativePath(node_path.relative(fromDirectory, toFile));
8
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
9
+ };
10
+ const createPublicPath = (containerEntry, fallbackPort)=>{
11
+ try {
12
+ return new URL('.', containerEntry).href;
13
+ } catch {
14
+ const slashIndex = containerEntry.lastIndexOf('/');
15
+ if (slashIndex >= 0) return containerEntry.slice(0, slashIndex + 1);
16
+ return `http://localhost:${fallbackPort}/`;
17
+ }
18
+ };
19
+ const createBackendRemoteEntrySource = async (workspaceRoot, app, effectApiPath, entryPath)=>{
20
+ const effectApiSpecifier = createRelativeImportSpecifier(node_path.dirname(effectApiPath), effectApiPath);
21
+ const containerMetadata = {
22
+ buildVersion: app.buildVersion,
23
+ expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
24
+ name: app.backendName,
25
+ packageName: app.packageName,
26
+ remoteType: app.remoteType,
27
+ source: normalizeRelativePath(node_path.relative(workspaceRoot, effectApiPath)),
28
+ version: app.version,
29
+ ...app.unitId ? {
30
+ unitId: app.unitId
31
+ } : {},
32
+ ...app.sourceRevision ? {
33
+ sourceRevision: app.sourceRevision
34
+ } : {}
35
+ };
36
+ const compatibility = {
37
+ build: app.buildVersion,
38
+ contractVersion: BACKEND_FEDERATION_CONTRACT_VERSION,
39
+ nodeAdapterVersion: BACKEND_FEDERATION_NODE_ADAPTER_VERSION,
40
+ packageName: app.packageName,
41
+ ...app.unitId ? {
42
+ unitId: app.unitId
43
+ } : {},
44
+ ...app.sourceRevision ? {
45
+ sourceRevision: app.sourceRevision
46
+ } : {}
47
+ };
48
+ const source = `// Generated by Modern.js backend federation build.
49
+ import * as exposedNamespace from ${JSON.stringify(effectApiSpecifier)};
50
+
51
+ const exposedModule = {
52
+ ...exposedNamespace,
53
+ backendFederationContract: {
54
+ ...(exposedNamespace.backendFederationContract ?? {}),
55
+ compatibility: {
56
+ ...(exposedNamespace.backendFederationContract?.compatibility ?? {}),
57
+ ...${JSON.stringify(compatibility)},
58
+ },
59
+ name: ${JSON.stringify(app.backendName)},
60
+ role: 'microvertical-server',
61
+ runtimeFramework: 'effect',
62
+ strictEffectApproach: true,
63
+ },
64
+ };
65
+ const exposedModules = {
66
+ ${JSON.stringify(BACKEND_FEDERATION_EFFECT_EXPOSE)}: () => Promise.resolve(exposedModule),
67
+ };
68
+ const __modernjsBackendFederation = ${JSON.stringify(containerMetadata)};
69
+
70
+ function init() {}
71
+
72
+ function get(id) {
73
+ const load = exposedModules[id];
74
+ if (!load) {
75
+ throw new Error(\`Unexpected backend federation expose: \${id}\`);
76
+ }
77
+
78
+ return async () => load();
79
+ }
80
+
81
+ module.exports = { __modernjsBackendFederation, get, init };
82
+ `;
83
+ const result = await build({
84
+ absWorkingDir: node_path.dirname(effectApiPath),
85
+ bundle: true,
86
+ format: 'cjs',
87
+ logLevel: 'silent',
88
+ platform: 'node',
89
+ stdin: {
90
+ contents: source,
91
+ loader: 'ts',
92
+ resolveDir: node_path.dirname(effectApiPath),
93
+ sourcefile: node_path.basename(entryPath)
94
+ },
95
+ target: 'node20',
96
+ write: false
97
+ });
98
+ const output = result.outputFiles[0];
99
+ if (!output) throw new Error('[backend-federation-build] CommonJS backend federation container emitted no output.');
100
+ return output.text;
101
+ };
102
+ const createBackendManifest = (workspaceRoot, distDirectory, app, entryIntegrity)=>{
103
+ const sourceModule = `${app.directory}/api/effect-api.ts`;
104
+ const publicPath = createPublicPath(app.containerEntry, app.port);
105
+ const manifest = {
106
+ schemaVersion: 1,
107
+ id: app.backendName,
108
+ name: app.backendName,
109
+ version: app.version,
110
+ buildVersion: app.buildVersion,
111
+ metaData: {
112
+ name: app.backendName,
113
+ type: 'backend',
114
+ buildInfo: {
115
+ buildVersion: app.buildVersion,
116
+ buildName: app.packageName
117
+ },
118
+ remoteEntry: {
119
+ name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
120
+ path: '',
121
+ type: app.remoteType
122
+ },
123
+ globalName: app.backendName,
124
+ publicPath,
125
+ ssrRemoteEntry: {
126
+ name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
127
+ path: '',
128
+ type: app.remoteType
129
+ },
130
+ ssrPublicPath: publicPath
131
+ },
132
+ entry: {
133
+ ...entryIntegrity,
134
+ file: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
135
+ path: normalizeRelativePath(node_path.relative(workspaceRoot, node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE))),
136
+ type: app.remoteType,
137
+ url: app.containerEntry
138
+ },
139
+ exposes: [
140
+ {
141
+ id: `${app.backendName}:${BACKEND_FEDERATION_EFFECT_EXPOSE}`,
142
+ name: BACKEND_FEDERATION_EFFECT_EXPOSE,
143
+ path: '',
144
+ assets: {
145
+ js: {
146
+ async: [],
147
+ sync: [
148
+ BACKEND_FEDERATION_REMOTE_ENTRY_FILE
149
+ ]
150
+ },
151
+ css: {
152
+ async: [],
153
+ sync: []
154
+ }
155
+ }
156
+ }
157
+ ],
158
+ shared: [],
159
+ backendFederation: {
160
+ role: 'microvertical-server',
161
+ appId: app.id,
162
+ name: app.backendName,
163
+ runtimeFramework: 'effect',
164
+ strictEffectApproach: true,
165
+ contractVersion: BACKEND_FEDERATION_CONTRACT_VERSION,
166
+ nodeAdapterVersion: BACKEND_FEDERATION_NODE_ADAPTER_VERSION,
167
+ remoteType: app.remoteType,
168
+ expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
169
+ manifestUrl: app.manifestUrl,
170
+ containerEntry: app.containerEntry,
171
+ source: {
172
+ module: sourceModule
173
+ },
174
+ readinessPath: `${app.apiPrefix}/${app.apiStem}/readiness`,
175
+ openapiPath: `${app.apiPrefix}/openapi.json`,
176
+ ...app.deliveryUnit ? {
177
+ deliveryUnit: app.deliveryUnit
178
+ } : {},
179
+ versionBoundary: {
180
+ invariant: 'web-and-api-same-build',
181
+ packageName: app.packageName,
182
+ version: app.version,
183
+ buildVersion: app.buildVersion,
184
+ ...app.uiManifestUrl ? {
185
+ uiManifestUrl: app.uiManifestUrl
186
+ } : {},
187
+ ...app.deliveryUnit ? {
188
+ deliveryUnit: {
189
+ unitId: app.deliveryUnit.unitId,
190
+ buildMarker: app.deliveryUnit.buildMarker,
191
+ sourceRevision: app.deliveryUnit.sourceRevision
192
+ }
193
+ } : {}
194
+ }
195
+ }
196
+ };
197
+ const validation = validateBackendFederationManifest(manifest, {
198
+ path: 'backendFederationManifest',
199
+ requireEffectExpose: true,
200
+ requireEffectRuntime: true,
201
+ requireVersionFields: true
202
+ });
203
+ if (!validation.ok) throw new Error(`[backend-federation-build] Invalid backend federation manifest: ${formatBackendFederationValidationErrors(validation.errors)}.`);
204
+ return manifest;
205
+ };
206
+ export { createBackendManifest, createBackendRemoteEntrySource };
@@ -0,0 +1,117 @@
1
+ import "node:module";
2
+ import { existsSync } from "node:fs";
3
+ import promises from "node:fs/promises";
4
+ import node_path from "node:path";
5
+ import { resolveUltramodernSourceRevision } from "@modern-js/app-tools-extensions/release-identity";
6
+ import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, DELIVERY_UNIT_DEPLOY_PROFILE, DELIVERY_UNIT_KIND, DELIVERY_UNIT_SCHEMA_VERSION, ULTRAMODERN_BUILD_ARTIFACT_PATH, deliveryUnitContractBlock, isUltramodernBuildArtifact, validateDeliveryUnitRecord, validateUltramodernBuildArtifact } from "@modern-js/backend-federation-contracts";
7
+ const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
8
+ const normalizeRelativePath = (value)=>value.replace(/\\/gu, '/').replace(/^\.\/+/u, '');
9
+ const isRecord = (value)=>'object' == typeof value && null !== value;
10
+ const readJsonFile = async (filePath)=>JSON.parse(await promises.readFile(filePath, 'utf8'));
11
+ const buildArtifactPathFor = (appDirectory)=>node_path.join(appDirectory, ULTRAMODERN_BUILD_ARTIFACT_PATH);
12
+ const readBuildIdentity = async (appDirectory)=>{
13
+ const buildArtifactPath = buildArtifactPathFor(appDirectory);
14
+ if (existsSync(buildArtifactPath)) {
15
+ const artifact = await readJsonFile(buildArtifactPath);
16
+ const artifactValidation = validateUltramodernBuildArtifact(artifact, buildArtifactPath);
17
+ if (!artifactValidation.ok) throw new Error(`[backend-federation-build] Invalid delivery-unit build artifact at ${buildArtifactPath}.`);
18
+ if (!isUltramodernBuildArtifact(artifact)) throw new Error(`[backend-federation-build] Invalid delivery-unit build artifact at ${buildArtifactPath}.`);
19
+ const deliveryUnit = artifact.deliveryUnit;
20
+ return {
21
+ artifact,
22
+ appId: deliveryUnit.appId,
23
+ buildVersion: deliveryUnit.buildMarker,
24
+ packageName: deliveryUnit.packageName,
25
+ version: deliveryUnit.version,
26
+ unitId: deliveryUnit.unitId,
27
+ sourceRevision: deliveryUnit.sourceRevision
28
+ };
29
+ }
30
+ throw new Error(`[backend-federation-build] Missing delivery-unit build artifact at ${buildArtifactPath}.`);
31
+ };
32
+ const toPascalCase = (value)=>value.split(/[^a-zA-Z0-9]+/u).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
33
+ const stringValue = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
34
+ const createBackendName = (app, id)=>{
35
+ const configuredName = stringValue(app.backendFederation?.name) ?? stringValue(app.backendFederation?.executionSurfaces?.node?.remoteName) ?? stringValue(app.serverExecution?.node?.remoteName);
36
+ if (configuredName) return configuredName;
37
+ const mfName = stringValue(app.moduleFederation?.name);
38
+ return mfName ? `${mfName}Backend` : `vertical${toPascalCase(id)}Backend`;
39
+ };
40
+ const findWorkspaceRoot = (appDirectory)=>{
41
+ let current = appDirectory;
42
+ while(true){
43
+ if (existsSync(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
44
+ const parent = node_path.dirname(current);
45
+ if (parent === current) return;
46
+ current = parent;
47
+ }
48
+ };
49
+ const resolveWorkspaceSourceRevision = async (workspaceRoot)=>resolveUltramodernSourceRevision(workspaceRoot);
50
+ const createStampedDeliveryUnit = (input)=>{
51
+ if (!input.unitId || !input.buildMarker || !input.packageName || !input.version) return;
52
+ const record = {
53
+ schemaVersion: DELIVERY_UNIT_SCHEMA_VERSION,
54
+ kind: DELIVERY_UNIT_KIND,
55
+ appId: input.appId,
56
+ unitId: input.unitId,
57
+ packageName: input.packageName,
58
+ version: input.version,
59
+ buildMarker: input.buildMarker,
60
+ sourceRevision: input.sourceRevision,
61
+ deployProfile: DELIVERY_UNIT_DEPLOY_PROFILE
62
+ };
63
+ const validation = validateDeliveryUnitRecord(record);
64
+ if (!validation.ok) return;
65
+ return deliveryUnitContractBlock(record);
66
+ };
67
+ const createAppFromCompactMetadata = (workspaceRoot, appDirectory, compactApp)=>{
68
+ const id = stringValue(compactApp.id);
69
+ const appPath = stringValue(compactApp.path);
70
+ if (!id || 'vertical' !== compactApp.kind || !isRecord(compactApp.api)) return;
71
+ const directory = appPath ? normalizeRelativePath(appPath) : `verticals/${id}`;
72
+ if (node_path.resolve(workspaceRoot, directory) !== node_path.resolve(appDirectory)) return;
73
+ const port = 'number' == typeof compactApp.port ? compactApp.port : void 0;
74
+ if (void 0 === port) return;
75
+ const apiPrefix = stringValue(compactApp.api.prefix) ?? `/${id}-api`;
76
+ const apiStem = stringValue(compactApp.api.stem) ?? id;
77
+ const backendName = createBackendName(compactApp, id);
78
+ const manifestUrl = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.manifestUrl) ?? stringValue(compactApp.serverExecution?.node?.manifestUrl) ?? `http://localhost:${port}/${BACKEND_FEDERATION_MANIFEST_FILE}`;
79
+ const containerEntry = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.containerEntry) ?? stringValue(compactApp.serverExecution?.node?.containerEntry) ?? `http://localhost:${port}/${BACKEND_FEDERATION_REMOTE_ENTRY_FILE}`;
80
+ const configuredRemoteType = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.remoteType) ?? stringValue(compactApp.serverExecution?.node?.remoteType);
81
+ if (void 0 !== configuredRemoteType && 'commonjs-module' !== configuredRemoteType) throw new Error(`[backend-federation-build] Node backend federation remoteType must be "commonjs-module"; received "${configuredRemoteType}" for ${id}.`);
82
+ if (!new URL(containerEntry).pathname.endsWith(`/${BACKEND_FEDERATION_REMOTE_ENTRY_FILE}`)) throw new Error(`[backend-federation-build] Node backend federation containerEntry must end with "/${BACKEND_FEDERATION_REMOTE_ENTRY_FILE}"; received "${containerEntry}" for ${id}.`);
83
+ const remoteType = 'commonjs-module';
84
+ const packageName = stringValue(compactApp.package);
85
+ const uiManifestUrl = stringValue(compactApp.backendFederation?.versionBoundary?.ui?.manifestUrl) ?? stringValue(compactApp.moduleFederation?.manifestUrl);
86
+ const compactDeliveryUnit = isRecord(compactApp.deliveryUnit) ? {
87
+ unitId: stringValue(compactApp.deliveryUnit.unitId),
88
+ buildMarker: stringValue(compactApp.deliveryUnit.buildMarker),
89
+ sourceRevision: stringValue(compactApp.deliveryUnit.sourceRevision),
90
+ packageName: stringValue(compactApp.deliveryUnit.packageName),
91
+ version: stringValue(compactApp.deliveryUnit.version)
92
+ } : void 0;
93
+ return {
94
+ id,
95
+ directory,
96
+ packageName,
97
+ port,
98
+ apiPrefix,
99
+ apiStem,
100
+ backendName,
101
+ manifestUrl,
102
+ containerEntry,
103
+ remoteType,
104
+ uiManifestUrl,
105
+ compactDeliveryUnit
106
+ };
107
+ };
108
+ const findBackendFederationApp = async (workspaceRoot, appDirectory)=>{
109
+ const compactConfigPath = node_path.join(workspaceRoot, COMPACT_CONFIG_PATH);
110
+ const compactConfig = await readJsonFile(compactConfigPath);
111
+ const apps = Array.isArray(compactConfig.topology?.apps) ? compactConfig.topology.apps : [];
112
+ for (const app of apps){
113
+ const resolved = createAppFromCompactMetadata(workspaceRoot, appDirectory, app);
114
+ if (resolved) return resolved;
115
+ }
116
+ };
117
+ export { COMPACT_CONFIG_PATH, buildArtifactPathFor, createAppFromCompactMetadata, createStampedDeliveryUnit, findBackendFederationApp, findWorkspaceRoot, normalizeRelativePath, readBuildIdentity, resolveWorkspaceSourceRevision };
@@ -0,0 +1,100 @@
1
+ import "node:module";
2
+ import { existsSync } from "node:fs";
3
+ import promises from "node:fs/promises";
4
+ import node_path from "node:path";
5
+ import { resolveUltramodernReleaseIdentity } from "@modern-js/app-tools-extensions/release-identity";
6
+ import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, ULTRAMODERN_BUILD_ARTIFACT_FILE, stampUltramodernBuildArtifactIdentity } from "@modern-js/backend-federation-contracts";
7
+ import { createBackendFederationEntryIntegrity } from "@modern-js/server-runtime-extensions/backend-federation-security/node";
8
+ import { createBackendManifest, createBackendRemoteEntrySource } from "./codegen.mjs";
9
+ import { COMPACT_CONFIG_PATH, buildArtifactPathFor, createStampedDeliveryUnit, findBackendFederationApp, findWorkspaceRoot, readBuildIdentity, resolveWorkspaceSourceRevision } from "./config.mjs";
10
+ const emitBackendFederationArtifacts = async (appDirectory, distDirectory)=>{
11
+ const workspaceRoot = findWorkspaceRoot(appDirectory);
12
+ if (!workspaceRoot) return;
13
+ const effectApiPath = node_path.join(appDirectory, 'api/effect-api.ts');
14
+ const backendFederationConfigPath = node_path.join(appDirectory, 'backend-federation.config.ts');
15
+ if (!existsSync(effectApiPath) || !existsSync(backendFederationConfigPath)) return;
16
+ const app = await findBackendFederationApp(workspaceRoot, appDirectory);
17
+ if (!app) return;
18
+ const buildIdentity = await readBuildIdentity(appDirectory);
19
+ const compactDeliveryUnit = app.compactDeliveryUnit;
20
+ const hasCompactDeliveryUnit = void 0 !== compactDeliveryUnit && (void 0 !== compactDeliveryUnit.unitId || void 0 !== compactDeliveryUnit.buildMarker || void 0 !== compactDeliveryUnit.packageName || void 0 !== compactDeliveryUnit.version);
21
+ const hasBuildIdentity = void 0 !== buildIdentity.unitId || void 0 !== buildIdentity.buildVersion || void 0 !== buildIdentity.packageName || void 0 !== buildIdentity.version;
22
+ if (hasBuildIdentity) {
23
+ const compactConfigPath = node_path.join(workspaceRoot, COMPACT_CONFIG_PATH);
24
+ const buildIdentityPath = buildArtifactPathFor(appDirectory);
25
+ const mismatches = [];
26
+ const compare = (label, a, b, leftLabel = 'deliveryUnit')=>{
27
+ if (void 0 !== a && void 0 !== b && a !== b) mismatches.push(`${label}: ${leftLabel}=${a} vs ultramodern-build=${b}`);
28
+ };
29
+ compare('appId', app.id, buildIdentity.appId, 'topology');
30
+ if (hasCompactDeliveryUnit) {
31
+ compare('unitId', compactDeliveryUnit?.unitId, buildIdentity.unitId);
32
+ compare('buildMarker/build', compactDeliveryUnit?.buildMarker, buildIdentity.buildVersion);
33
+ compare('packageName', compactDeliveryUnit?.packageName, buildIdentity.packageName);
34
+ compare('version', compactDeliveryUnit?.version, buildIdentity.version);
35
+ }
36
+ if (mismatches.length > 0) throw new Error(`[backend-federation-build] Delivery-unit identity drift between ${compactConfigPath} (topology) and ${buildIdentityPath}: ${mismatches.join('; ')}`);
37
+ }
38
+ const unitId = compactDeliveryUnit?.unitId ?? buildIdentity.unitId;
39
+ const generationBuildMarker = compactDeliveryUnit?.buildMarker ?? buildIdentity.buildVersion;
40
+ const sourceRevision = await resolveWorkspaceSourceRevision(workspaceRoot);
41
+ const buildVersion = generationBuildMarker && unitId ? resolveUltramodernReleaseIdentity({
42
+ generationBuildMarker,
43
+ unitId,
44
+ workspaceRoot
45
+ }).buildMarker : void 0;
46
+ const packageName = compactDeliveryUnit?.packageName ?? buildIdentity.packageName ?? app.packageName;
47
+ const version = compactDeliveryUnit?.version ?? buildIdentity.version;
48
+ const deliveryUnit = createStampedDeliveryUnit({
49
+ appId: app.id,
50
+ unitId,
51
+ buildMarker: buildVersion,
52
+ packageName,
53
+ version,
54
+ sourceRevision
55
+ });
56
+ const stampedBuildArtifact = buildIdentity.artifact ? stampUltramodernBuildArtifactIdentity(buildIdentity.artifact, {
57
+ buildMarker: buildVersion ?? buildIdentity.artifact.deliveryUnit.buildMarker,
58
+ sourceRevision
59
+ }) : void 0;
60
+ const resolvedApp = {
61
+ ...app,
62
+ packageName,
63
+ version,
64
+ buildVersion,
65
+ unitId,
66
+ sourceRevision,
67
+ deliveryUnit
68
+ };
69
+ const manifestPath = node_path.join(distDirectory, BACKEND_FEDERATION_MANIFEST_FILE);
70
+ const entryPath = node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE);
71
+ const deliveryUnitArtifactPath = stampedBuildArtifact ? node_path.join(distDirectory, ULTRAMODERN_BUILD_ARTIFACT_FILE) : void 0;
72
+ const entrySource = await createBackendRemoteEntrySource(workspaceRoot, resolvedApp, effectApiPath, entryPath);
73
+ await promises.mkdir(distDirectory, {
74
+ recursive: true
75
+ });
76
+ await promises.writeFile(entryPath, entrySource);
77
+ await promises.writeFile(manifestPath, `${JSON.stringify(createBackendManifest(workspaceRoot, distDirectory, resolvedApp, createBackendFederationEntryIntegrity(entrySource)), null, 2)}\n`);
78
+ if (stampedBuildArtifact && deliveryUnitArtifactPath) await promises.writeFile(deliveryUnitArtifactPath, `${JSON.stringify(stampedBuildArtifact, null, 2)}\n`);
79
+ return {
80
+ appId: resolvedApp.id,
81
+ manifestPath,
82
+ containerPath: entryPath,
83
+ ...deliveryUnitArtifactPath ? {
84
+ deliveryUnitArtifactPath
85
+ } : {},
86
+ remoteName: resolvedApp.backendName,
87
+ remoteType: resolvedApp.remoteType
88
+ };
89
+ };
90
+ const emit = ()=>({
91
+ name: '@modern-js/backend-federation-build',
92
+ setup (api) {
93
+ api.onAfterBuild(async ()=>{
94
+ const { appDirectory, distDirectory } = api.getAppContext();
95
+ await emitBackendFederationArtifacts(appDirectory, distDirectory);
96
+ });
97
+ }
98
+ });
99
+ export default emit;
100
+ export { emitBackendFederationArtifacts };
@@ -0,0 +1,2 @@
1
+ import "node:module";
2
+ export { default, emitBackendFederationArtifacts } from "./emit.mjs";