@bleedingdev/modern-js-app-tools 3.5.0-ultramodern.101 → 3.5.0-ultramodern.103

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 (31) hide show
  1. package/dist/cjs/builder/generator/getBuilderEnvironments.js +73 -11
  2. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/index.js +1 -1
  3. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.js +94 -18
  4. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +1 -0
  5. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-mf-ssr-runtime-plugin.mjs +14 -0
  6. package/dist/cjs/ultramodern-release-envelope/framework-output.js +109 -57
  7. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +63 -10
  8. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +1 -1
  9. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +93 -18
  10. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +1 -0
  11. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-mf-ssr-runtime-plugin.mjs +14 -0
  12. package/dist/esm/ultramodern-release-envelope/framework-output.mjs +107 -58
  13. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +63 -10
  14. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +1 -1
  15. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +93 -18
  16. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +1 -0
  17. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-mf-ssr-runtime-plugin.mjs +14 -0
  18. package/dist/esm-node/ultramodern-release-envelope/framework-output.mjs +107 -58
  19. package/dist/types/builder/generator/getBuilderEnvironments.d.ts +29 -0
  20. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.d.ts +1 -1
  21. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.d.mts +1 -1
  22. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-mf-ssr-runtime-plugin.d.mts +13 -0
  23. package/dist/types/ultramodern-release-envelope/framework-output.d.ts +1 -0
  24. package/docs/configure/app/bff/effect.md +13 -15
  25. package/docs/configure/app/server/rsc.md +8 -12
  26. package/docs/guides/basic-features/render/rsc.md +5 -14
  27. package/docs/guides/get-started/quick-start.md +1 -1
  28. package/docs/guides/get-started/ultramodern.md +19 -7
  29. package/docs/guides/get-started/upgrade.md +5 -10
  30. package/docs/llms.txt +1 -1
  31. package/package.json +12 -12
@@ -5,6 +5,8 @@ import { isProd, isSSR, isServiceWorker, isUseRsc, isUseSSRBundle } from "@moder
5
5
  import { CLOUDFLARE_WORKER_NODE_BUILTINS } from "../../plugins/deploy/platforms/cloudflare-output-contract.mjs";
6
6
  const BFF_EFFECT_WORKER_ENTRY_NAME = '__modern_bff_effect';
7
7
  const BFF_EFFECT_WORKER_RUNTIME_QUERY = 'modern-bff-runtime';
8
+ const MF_SSR_DATA_FETCH_RUNTIME_PLUGIN = '@module-federation/modern-js-v3/ssr-inject-data-fetch-function-plugin';
9
+ const MF_SSR_DEV_RUNTIME_PLUGIN = '@module-federation/modern-js-v3/ssr-dev-plugin';
8
10
  const JS_OR_TS_EXTS = [
9
11
  '.js',
10
12
  '.jsx',
@@ -85,6 +87,64 @@ function getCloudflareWorkerNodeExternals() {
85
87
  ];
86
88
  }));
87
89
  }
90
+ const reserveWorkerChunkName = (baseName, reservedOutputNames)=>{
91
+ let name = baseName;
92
+ while(reservedOutputNames.has(normalizeWorkerOutputName(name)))name = `${name}_`;
93
+ return name;
94
+ };
95
+ const normalizeWorkerOutputName = (name)=>node_path.posix.normalize(name.replace(/\\/gu, '/')).toLowerCase();
96
+ function getCloudflareWorkerRspackConfig(workerEntryNames) {
97
+ const entryNames = [
98
+ ...workerEntryNames
99
+ ];
100
+ for (const entryName of entryNames){
101
+ const slashName = entryName.replace(/\\/gu, '/');
102
+ const normalizedName = node_path.posix.normalize(slashName);
103
+ if (entryName !== slashName || normalizedName !== slashName || '.' === normalizedName || normalizedName.startsWith('../') || node_path.posix.isAbsolute(normalizedName) || node_path.win32.isAbsolute(slashName) || /^[A-Za-z]:/u.test(slashName)) throw new Error(`Cloudflare worker entry name "${entryName}" must be a canonical relative output path without dot segments or backslashes.`);
104
+ }
105
+ const reservedNames = new Set(entryNames.map(normalizeWorkerOutputName));
106
+ const runtimeName = reserveWorkerChunkName('__modern_worker_runtime', reservedNames);
107
+ reservedNames.add(normalizeWorkerOutputName(runtimeName));
108
+ const sharedName = reserveWorkerChunkName('__modern_worker_shared', reservedNames);
109
+ return {
110
+ experiments: {
111
+ outputModule: true
112
+ },
113
+ externals: getCloudflareWorkerNodeExternals(),
114
+ externalsType: 'module-import',
115
+ module: {
116
+ parser: {
117
+ javascript: {
118
+ dynamicImportMode: 'eager'
119
+ }
120
+ }
121
+ },
122
+ optimization: {
123
+ runtimeChunk: {
124
+ name: runtimeName
125
+ },
126
+ splitChunks: {
127
+ chunks: 'all',
128
+ minSize: 0,
129
+ name: sharedName
130
+ }
131
+ }
132
+ };
133
+ }
134
+ function applyCloudflareWorkerRspackConfig(chain, workerEntryNames) {
135
+ const config = getCloudflareWorkerRspackConfig(workerEntryNames);
136
+ chain.experiments(config.experiments);
137
+ chain.externals(config.externals);
138
+ chain.externalsType(config.externalsType);
139
+ chain.module.parser.merge(config.module.parser);
140
+ chain.optimization.runtimeChunk(config.optimization.runtimeChunk);
141
+ chain.optimization.splitChunks(config.optimization.splitChunks);
142
+ }
143
+ function applyCloudflareWorkerMfRuntimeBoundary(chain) {
144
+ chain.plugins.delete('plugin-module-federation');
145
+ chain.resolve.alias.set(`${MF_SSR_DATA_FETCH_RUNTIME_PLUGIN}$`, getCloudflareWorkerCompatFile('cloudflare-worker-mf-ssr-runtime-plugin.mjs'));
146
+ chain.resolve.alias.set(`${MF_SSR_DEV_RUNTIME_PLUGIN}$`, getCloudflareWorkerCompatFile('cloudflare-worker-mf-ssr-runtime-plugin.mjs'));
147
+ }
88
148
  function getEffectBffEntry(normalizedConfig, appContext) {
89
149
  if (!normalizedConfig.bff || 'hono' === normalizedConfig.bff.runtimeFramework) return;
90
150
  const configuredEntry = normalizedConfig.bff.effect?.entry;
@@ -243,17 +303,10 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
243
303
  htmlPlugin: false,
244
304
  ...useCloudflareModuleWorker ? {
245
305
  bundlerChain: (chain)=>{
246
- chain.merge({
247
- experiments: {
248
- outputModule: true
249
- },
250
- externals: getCloudflareWorkerNodeExternals(),
251
- externalsType: 'module-import'
252
- });
306
+ applyCloudflareWorkerRspackConfig(chain, Object.keys(workerEntries));
253
307
  chain.output.module(true).library({
254
308
  type: 'module'
255
309
  }).publicPath('/').chunkFormat('module').chunkLoading('import').workerChunkLoading('import');
256
- chain.optimization.usedExports(false).providedExports(true).innerGraph(false).sideEffects(false);
257
310
  for (const condition of [
258
311
  'workerd',
259
312
  'worker',
@@ -263,7 +316,7 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
263
316
  'require',
264
317
  'module'
265
318
  ])chain.resolve.conditionNames.add(condition);
266
- chain.plugins.delete('plugin-module-federation');
319
+ applyCloudflareWorkerMfRuntimeBoundary(chain);
267
320
  if (tanstackRouterSsrServerFile) {
268
321
  chain.resolve.alias.set('@tanstack/router-core/ssr/server$', tanstackRouterSsrServerFile);
269
322
  chain.resolve.alias.set('@tanstack/router-core/ssr/server', tanstackRouterSsrServerFile);
@@ -304,4 +357,4 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
304
357
  builderConfig: tempBuilderConfig
305
358
  };
306
359
  }
307
- export { getBuilderEnvironments };
360
+ export { applyCloudflareWorkerMfRuntimeBoundary, applyCloudflareWorkerRspackConfig, getBuilderEnvironments, getCloudflareWorkerRspackConfig };
@@ -116,7 +116,7 @@ const verifyCloudflareOutput = async (options)=>{
116
116
  path: publicPath
117
117
  });
118
118
  }
119
- if (false !== options.importWorker && await pathExists(outputPlan.paths.workerEntry)) await verifyWorkerImport(issues, outputPlan.paths.workerEntry);
119
+ if (false !== options.importWorker && await pathExists(outputPlan.paths.workerEntry)) await verifyWorkerImport(issues, outputPlan.paths.workerEntry, manifest);
120
120
  return {
121
121
  ok: 0 === issues.length,
122
122
  issues
@@ -1,7 +1,9 @@
1
1
  import promises from "node:fs/promises";
2
2
  import node_path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
+ import { isDeepStrictEqual } from "node:util";
4
5
  import { parse } from "@babel/parser";
6
+ import traverse from "@babel/traverse";
5
7
  import { CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_NODE_BUILTINS } from "../cloudflare-output-contract.mjs";
6
8
  import { addIssue } from "./issues.mjs";
7
9
  const getReferencedRouteWorkers = (manifest)=>Array.isArray(manifest?.routeSpec?.routes) ? manifest.routeSpec.routes.map((route)=>'string' == typeof route?.worker && route.worker.length > 0 ? route.worker : void 0).filter((worker)=>'string' == typeof worker) : [];
@@ -45,6 +47,7 @@ const getNodeName = (node)=>{
45
47
  if (!isAstNode(node)) return;
46
48
  return 'Identifier' === node.type && 'string' == typeof node.name ? node.name : 'StringLiteral' === node.type && 'string' == typeof node.value ? node.value : void 0;
47
49
  };
50
+ const getStringLiteralValue = (node)=>isAstNode(node) && 'StringLiteral' === node.type && 'string' == typeof node.value ? node.value : void 0;
48
51
  const collectBindingNames = (node, names)=>{
49
52
  if (!isAstNode(node)) return;
50
53
  const name = getNodeName(node);
@@ -54,7 +57,11 @@ const collectBindingNames = (node, names)=>{
54
57
  } else if ('ArrayPattern' === node.type && Array.isArray(node.elements)) for (const element of node.elements)collectBindingNames(element, names);
55
58
  else if ('AssignmentPattern' === node.type || 'RestElement' === node.type) collectBindingNames('AssignmentPattern' === node.type ? node.left : node.argument, names);
56
59
  };
57
- const getMemberPropertyName = (node)=>'MemberExpression' === node.type ? getNodeName(node.property) : void 0;
60
+ const getMemberPropertyName = (node)=>{
61
+ if ('MemberExpression' !== node.type) return;
62
+ return true === node.computed ? getStringLiteralValue(node.property) : getNodeName(node.property);
63
+ };
64
+ const isAmbientModuleRequire = (node, modulePath)=>isAstNode(node) && 'MemberExpression' === node.type && isAstNode(node.object) && 'Identifier' === node.object.type && 'module' === node.object.name && void 0 === modulePath.scope.getBinding('module') && 'require' === getMemberPropertyName(node);
58
65
  const isModuleExports = (node)=>isAstNode(node) && 'MemberExpression' === node.type && isAstNode(node.object) && 'Identifier' === node.object.type && 'module' === node.object.name && 'exports' === getMemberPropertyName(node);
59
66
  const collectCommonJsExports = (statement, exports)=>{
60
67
  if ('ExpressionStatement' !== statement.type || !isAstNode(statement.expression) || 'AssignmentExpression' !== statement.expression.type) return;
@@ -89,19 +96,31 @@ const collectEsmExports = (statement, exports)=>{
89
96
  }
90
97
  }
91
98
  };
92
- const visitAst = (node, visitor)=>{
93
- visitor(node);
94
- for (const [key, value] of Object.entries(node))if ('loc' !== key && 'start' !== key && 'end' !== key && 'leadingComments' !== key && 'trailingComments' !== key && 'innerComments' !== key) {
95
- if (isAstNode(value)) visitAst(value, visitor);
96
- else if (Array.isArray(value)) {
97
- for (const item of value)if (isAstNode(item)) visitAst(item, visitor);
99
+ const getStaticImport = (modulePath)=>{
100
+ const node = modulePath.node;
101
+ if (('ImportDeclaration' === node.type || 'ExportNamedDeclaration' === node.type || 'ExportAllDeclaration' === node.type) && isAstNode(node.source)) return getStringLiteralValue(node.source);
102
+ if ('ImportExpression' === node.type && isAstNode(node.source)) return getStringLiteralValue(node.source);
103
+ if ('CallExpression' === node.type && Array.isArray(node.arguments) && 1 === node.arguments.length && isAstNode(node.callee) && ('Identifier' === node.callee.type && 'require' === node.callee.name && void 0 === modulePath.scope.getBinding('require') || isAmbientModuleRequire(node.callee, modulePath) || 'Import' === node.callee.type)) return getStringLiteralValue(node.arguments[0]);
104
+ };
105
+ const isAmbientLoaderWrite = (modulePath)=>{
106
+ let targetPath = modulePath;
107
+ while(targetPath.parentPath){
108
+ const parentPath = targetPath.parentPath;
109
+ if (parentPath.isAssignmentExpression()) return 'left' === targetPath.key;
110
+ if (parentPath.isUpdateExpression()) return 'argument' === targetPath.key;
111
+ if (parentPath.isForInStatement() || parentPath.isForOfStatement()) return 'left' === targetPath.key;
112
+ if (parentPath.isObjectProperty()) {
113
+ if ('value' !== targetPath.key) return false;
114
+ targetPath = parentPath;
115
+ continue;
116
+ }
117
+ if (parentPath.isObjectPattern() || parentPath.isArrayPattern() || parentPath.isRestElement() || parentPath.isAssignmentPattern()) {
118
+ targetPath = parentPath;
119
+ continue;
98
120
  }
121
+ break;
99
122
  }
100
- };
101
- const getStaticImport = (node)=>{
102
- if (('ImportDeclaration' === node.type || 'ExportNamedDeclaration' === node.type || 'ExportAllDeclaration' === node.type) && isAstNode(node.source)) return getNodeName(node.source);
103
- if ('ImportExpression' === node.type && isAstNode(node.source)) return getNodeName(node.source);
104
- if ('CallExpression' === node.type && Array.isArray(node.arguments) && 1 === node.arguments.length && isAstNode(node.callee) && ('Identifier' === node.callee.type && 'require' === node.callee.name || 'Import' === node.callee.type)) return getNodeName(node.arguments[0]);
123
+ return false;
105
124
  };
106
125
  const analyzeWorkerModule = (source)=>{
107
126
  const ast = parse(source, {
@@ -109,17 +128,49 @@ const analyzeWorkerModule = (source)=>{
109
128
  });
110
129
  const exports = new Set();
111
130
  const imports = new Set();
131
+ let unsafeCommonJsLoaderUsage = false;
132
+ let unsafeDynamicImport = false;
112
133
  for (const statement of ast.program.body){
113
134
  collectEsmExports(statement, exports);
114
135
  collectCommonJsExports(statement, exports);
115
136
  }
116
- visitAst(ast.program, (node)=>{
117
- const specifier = getStaticImport(node);
118
- if (specifier) imports.add(specifier);
137
+ traverse(ast, {
138
+ enter (modulePath) {
139
+ const node = modulePath.node;
140
+ if (('ImportExpression' === node.type || 'CallExpression' === node.type && isAstNode(node.callee) && 'Import' === node.callee.type) && void 0 === getStaticImport(modulePath)) unsafeDynamicImport = true;
141
+ if (modulePath.isReferencedIdentifier({
142
+ name: 'require'
143
+ }) && void 0 === modulePath.scope.getBinding('require')) {
144
+ const parentPath = modulePath.parentPath;
145
+ const isStaticRequireCall = parentPath?.isCallExpression() && 'callee' === modulePath.key && void 0 !== getStaticImport(parentPath);
146
+ const isAvailabilityCheck = parentPath?.isUnaryExpression({
147
+ operator: 'typeof'
148
+ });
149
+ if (!isStaticRequireCall && !isAvailabilityCheck) unsafeCommonJsLoaderUsage = true;
150
+ }
151
+ if ('Identifier' === node.type && isAmbientLoaderWrite(modulePath) && ('require' === node.name || 'module' === node.name) && void 0 === modulePath.scope.getBinding(node.name)) unsafeCommonJsLoaderUsage = true;
152
+ if (modulePath.isReferencedIdentifier({
153
+ name: 'module'
154
+ }) && void 0 === modulePath.scope.getBinding('module')) {
155
+ const parentPath = modulePath.parentPath;
156
+ const isExportsAccess = null !== parentPath && isModuleExports(parentPath.node);
157
+ const isStaticModuleRequireCall = null !== parentPath && isAmbientModuleRequire(parentPath.node, parentPath) && parentPath.parentPath?.isCallExpression() === true && 'callee' === parentPath.key && void 0 !== getStaticImport(parentPath.parentPath);
158
+ if (!isExportsAccess && !isStaticModuleRequireCall) unsafeCommonJsLoaderUsage = true;
159
+ }
160
+ if (isAmbientModuleRequire(node, modulePath)) {
161
+ const parentPath = modulePath.parentPath;
162
+ const isStaticRequireCall = parentPath?.isCallExpression() && 'callee' === modulePath.key && void 0 !== getStaticImport(parentPath);
163
+ if (!isStaticRequireCall) unsafeCommonJsLoaderUsage = true;
164
+ }
165
+ const specifier = getStaticImport(modulePath);
166
+ if (void 0 !== specifier) imports.add(specifier);
167
+ }
119
168
  });
120
169
  return {
121
170
  exports,
122
- imports
171
+ imports,
172
+ unsafeCommonJsLoaderUsage,
173
+ unsafeDynamicImport
123
174
  };
124
175
  };
125
176
  const getPackageName = (specifier)=>specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0];
@@ -170,7 +221,25 @@ const verifyWorkerModuleClosure = async (issues, entryPath, entrySource, contrac
170
221
  return;
171
222
  }
172
223
  if (isEntry) entryAnalysis = analysis;
224
+ if (analysis.unsafeCommonJsLoaderUsage) addIssue(issues, {
225
+ code: 'invalid-worker-bundle',
226
+ message: 'Cloudflare worker bundles must use exactly one string-literal specifier in ambient CommonJS loader calls and must not pass or alias the loader.',
227
+ path: modulePath
228
+ });
229
+ if (analysis.unsafeDynamicImport) addIssue(issues, {
230
+ code: 'invalid-worker-bundle',
231
+ message: 'Cloudflare worker bundles must not contain non-static dynamic module imports.',
232
+ path: modulePath
233
+ });
173
234
  for (const specifier of analysis.imports){
235
+ if (0 === specifier.length) {
236
+ addIssue(issues, {
237
+ code: 'invalid-worker-bundle',
238
+ message: 'Cloudflare worker bundle module specifiers must not be empty.',
239
+ path: modulePath
240
+ });
241
+ continue;
242
+ }
174
243
  if (!specifier.startsWith('.') && !node_path.isAbsolute(specifier)) {
175
244
  if (CLOUDFLARE_WORKER_NODE_BUILTIN_SPECIFIERS.has(specifier)) continue;
176
245
  if (specifier.startsWith('node:')) {
@@ -219,14 +288,20 @@ const verifyWorkerBundleReferences = async (issues, worker, source, contract)=>{
219
288
  path: worker.path
220
289
  });
221
290
  };
222
- const verifyWorkerImport = async (issues, entryPath)=>{
291
+ const verifyWorkerImport = async (issues, entryPath, expectedManifest)=>{
223
292
  try {
224
- const worker = (await import(`${pathToFileURL(entryPath).href}?t=${Date.now()}`)).default;
293
+ const workerModule = await import(`${pathToFileURL(entryPath).href}?t=${Date.now()}`);
294
+ const worker = workerModule.default;
225
295
  if (!worker || 'function' != typeof worker.fetch) addIssue(issues, {
226
296
  code: 'worker-import-failed',
227
297
  message: 'Cloudflare server entry must default-export a Worker with fetch.',
228
298
  path: entryPath
229
299
  });
300
+ if (void 0 !== expectedManifest && !isDeepStrictEqual(workerModule.modernWorkerManifest, expectedManifest)) addIssue(issues, {
301
+ code: 'worker-import-failed',
302
+ message: 'Cloudflare server entry runtime manifest must exactly match modern-worker-manifest.json.',
303
+ path: entryPath
304
+ });
230
305
  } catch (error) {
231
306
  addIssue(issues, {
232
307
  code: 'worker-import-failed',
@@ -1,5 +1,6 @@
1
1
  const ASSETS_BINDING = 'ASSETS';
2
2
  const MODERN_WORKER_MANIFEST = p_workerManifest;
3
+ export const modernWorkerManifest = MODERN_WORKER_MANIFEST;
3
4
  const WORKER_MODULE_LOADERS = p_workerModuleLoaders;
4
5
  const workerModulePromises = new Map();
5
6
  const effectBffDispatcherPromises = new Map();
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Workerd cannot initialize Module Federation's Node-oriented SSR data-fetch
3
+ * runtime. Cloudflare workers do not load native MF remotes, so retain the
4
+ * runtime-plugin contract without installing its server data-fetch hooks.
5
+ */
6
+ export const injectDataFetchFunctionPlugin = () => ({
7
+ name: '@module-federation/inject-data-fetch-function-plugin',
8
+ setup() {},
9
+ });
10
+
11
+ export const mfSSRDevPlugin = () => ({
12
+ name: '@module-federation/modern-js-v3',
13
+ setup() {},
14
+ });
@@ -1,42 +1,15 @@
1
+ import { createHash } from "node:crypto";
1
2
  import promises from "node:fs/promises";
2
3
  import node_path from "node:path";
3
- import { parse } from "@babel/parser";
4
4
  import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, ULTRAMODERN_BUILD_ARTIFACT_FILE, isUltramodernBuildArtifact } from "@modern-js/utils/universal";
5
5
  import { canonicalSerializeMicroVerticalReleaseEnvelope, createMicroVerticalReleaseEnvelope, verifyMicroVerticalReleaseEnvelope } from "./index.mjs";
6
6
  const MICROVERTICAL_RELEASE_ENVELOPE_PATH = 'release/microvertical-release-envelope.json';
7
+ const MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_PATH = 'release/microvertical-release-identity-carriers.json';
8
+ const MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_KIND = 'ultramodern-release-identity-carriers';
9
+ const MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_SCHEMA_VERSION = 1;
7
10
  const COMPILED_MODULE_PATTERN = /\.(?:c|m)?js$/u;
8
11
  const EFFECT_BFF_WORKER_PATTERN = /^worker\/__modern_bff_effect\.(?:c|m)?js$/u;
9
12
  const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
10
- const isAstNode = (value)=>isRecord(value) && 'string' == typeof value.type;
11
- const visitAst = (node, visitor)=>{
12
- visitor(node);
13
- for (const value of Object.values(node))if (isAstNode(value)) visitAst(value, visitor);
14
- else if (Array.isArray(value)) {
15
- for (const item of value)if (isAstNode(item)) visitAst(item, visitor);
16
- }
17
- };
18
- const compiledModuleIdentityValues = (source)=>{
19
- const values = new Set();
20
- const ast = parse(source, {
21
- sourceType: 'unambiguous'
22
- });
23
- visitAst(ast.program, (node)=>{
24
- if ('StringLiteral' === node.type && 'string' == typeof node.value) values.add(node.value);
25
- else if ('TemplateElement' === node.type && isRecord(node.value) && 'string' == typeof node.value.cooked) values.add(node.value.cooked);
26
- });
27
- return values;
28
- };
29
- const assertEveryCompiledIdentityCarrier = async (distDirectory, logicalPaths, identity, surface)=>{
30
- const compiledLogicalPaths = logicalPaths.filter((pathname)=>COMPILED_MODULE_PATTERN.test(pathname));
31
- if (0 === compiledLogicalPaths.length) throw new Error(`[ultramodern-release-envelope] ${surface} has no compiled execution module carrying release identity.`);
32
- for (const logicalPath of compiledLogicalPaths){
33
- const source = await promises.readFile(node_path.join(distDirectory, logicalPath), {
34
- encoding: 'utf8'
35
- });
36
- const values = compiledModuleIdentityValues(source);
37
- if (!values.has(identity.buildMarker) || !values.has(identity.sourceRevision) || !values.has(identity.releaseVersion)) throw new Error(`[ultramodern-release-envelope] ${surface} execution module ${logicalPath} does not carry exact buildMarker ${identity.buildMarker}, sourceRevision ${identity.sourceRevision}, and releaseVersion ${identity.releaseVersion}.`);
38
- }
39
- };
40
13
  const flattenStrings = (value)=>'string' == typeof value ? [
41
14
  value
42
15
  ] : Array.isArray(value) ? value.flatMap(flattenStrings) : [];
@@ -179,6 +152,49 @@ const releaseArtifact = (logicalPath, runtime)=>({
179
152
  logicalPath,
180
153
  runtime
181
154
  });
155
+ const writeReleaseIdentityCarrierMetadata = async (artifactRoot, identity, carrierPaths)=>{
156
+ const surfacesByPath = new Map();
157
+ for (const [surface, logicalPaths] of Object.entries(carrierPaths)){
158
+ if (0 === logicalPaths.length) throw new Error(`[ultramodern-release-envelope] ${surface} has no declared release-identity carrier artifact.`);
159
+ for (const logicalPath of logicalPaths){
160
+ const surfaces = surfacesByPath.get(logicalPath) ?? new Set();
161
+ surfaces.add(surface);
162
+ surfacesByPath.set(logicalPath, surfaces);
163
+ }
164
+ }
165
+ const carriers = await Promise.all([
166
+ ...surfacesByPath
167
+ ].sort(([left], [right])=>left.localeCompare(right)).map(async ([logicalPath, surfaces])=>{
168
+ const bytes = await promises.readFile(node_path.join(artifactRoot, logicalPath));
169
+ return {
170
+ logicalPath,
171
+ byteLength: bytes.byteLength,
172
+ sha256: createHash('sha256').update(bytes).digest('hex'),
173
+ surfaces: [
174
+ ...surfaces
175
+ ].sort((left, right)=>left.localeCompare(right))
176
+ };
177
+ }));
178
+ const releaseEnvelopePath = await resolveSafeReleaseEnvelopePath({
179
+ artifactRoot,
180
+ createDirectory: true
181
+ });
182
+ if (!releaseEnvelopePath) throw new Error('[ultramodern-release-envelope] could not resolve private release metadata directory.');
183
+ const metadataPath = node_path.join(node_path.dirname(releaseEnvelopePath), node_path.basename(MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_PATH));
184
+ try {
185
+ const metadataStat = await promises.lstat(metadataPath);
186
+ if (metadataStat.isSymbolicLink() || !metadataStat.isFile()) throw new Error('[ultramodern-release-envelope] release identity carrier metadata must be a real file inside artifactRoot.');
187
+ } catch (error) {
188
+ if (!isMissingPathError(error)) throw error;
189
+ }
190
+ await promises.writeFile(metadataPath, `${JSON.stringify({
191
+ schemaVersion: MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_SCHEMA_VERSION,
192
+ kind: MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_KIND,
193
+ identity,
194
+ carriers
195
+ }, null, 2)}\n`);
196
+ return releaseArtifact(MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_PATH, 'release-identity-metadata');
197
+ };
182
198
  const createReleaseArtifactInputs = async (distDirectory, identity, target)=>{
183
199
  const files = await collectFiles(distDirectory);
184
200
  if ('node' === target && files.some((logicalPath)=>EFFECT_BFF_WORKER_PATTERN.test(logicalPath))) throw new Error('[ultramodern-release-envelope] Node target conflicts with a Cloudflare Effect API/BFF worker artifact; resolve the canonical deploy target instead of emitting a Node envelope for Cloudflare output.');
@@ -202,13 +218,7 @@ const createReleaseArtifactInputs = async (distDirectory, identity, target)=>{
202
218
  const clientExecutionPaths = await manifestReferencedClientModules(distDirectory, files);
203
219
  if (0 === clientExecutionPaths.length) throw new Error('[ultramodern-release-envelope] UI/client manifest references no compiled execution module.');
204
220
  const ssrExecutionPaths = await routeReferencedSsrModules(distDirectory, files, target);
205
- await assertEveryCompiledIdentityCarrier(distDirectory, clientExecutionPaths, identity, 'manifest-referenced UI/client');
206
- await assertEveryCompiledIdentityCarrier(distDirectory, ssrExecutionPaths, identity, 'node' === target ? 'route-referenced Node SSR' : 'route-referenced Cloudflare SSR');
207
- await assertEveryCompiledIdentityCarrier(distDirectory, ssrPaths, identity, 'node' === target ? 'compiled Node SSR closure' : 'compiled Cloudflare SSR/workerd closure');
208
- await assertEveryCompiledIdentityCarrier(distDirectory, 'node' === target ? nodeApiEntryPaths : apiBackendPaths, identity, 'node' === target ? 'Node API/backend' : 'Cloudflare API/backend');
209
- await assertEveryCompiledIdentityCarrier(distDirectory, [
210
- BACKEND_FEDERATION_REMOTE_ENTRY_FILE
211
- ], identity, 'backend Module Federation container');
221
+ if (0 === ssrExecutionPaths.length) throw new Error(`[ultramodern-release-envelope] route manifest references no emitted ${'node' === target ? 'Node' : 'Cloudflare'} SSR execution module.`);
212
222
  const runtimeByPath = new Map();
213
223
  const add = (paths, runtime)=>{
214
224
  for (const logicalPath of paths){
@@ -244,8 +254,25 @@ const createReleaseArtifactInputs = async (distDirectory, identity, target)=>{
244
254
  const artifacts = [
245
255
  ...runtimeByPath
246
256
  ].map(([logicalPath, runtime])=>releaseArtifact(logicalPath, runtime)).sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath));
257
+ const identityCarrierMetadata = await writeReleaseIdentityCarrierMetadata(distDirectory, identity, {
258
+ apiBackend: apiBackendPaths,
259
+ backendFederation: [
260
+ BACKEND_FEDERATION_MANIFEST_FILE,
261
+ BACKEND_FEDERATION_REMOTE_ENTRY_FILE
262
+ ],
263
+ ssr: [
264
+ ...new Set([
265
+ ...ssrExecutionPaths,
266
+ ...ssrPaths
267
+ ])
268
+ ],
269
+ uiClient: uiClientPaths.filter((logicalPath)=>COMPILED_MODULE_PATTERN.test(logicalPath))
270
+ });
247
271
  return {
248
- artifacts,
272
+ artifacts: [
273
+ ...artifacts,
274
+ identityCarrierMetadata
275
+ ].sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath)),
249
276
  surfaces
250
277
  };
251
278
  };
@@ -367,13 +394,7 @@ const createNodeStagedReleaseArtifactInputs = async (outputDirectory, identity)=
367
394
  ])if (0 === paths.length) throw new Error(`[ultramodern-release-envelope] final Node staging has no ${surface} artifacts.`);
368
395
  const clientExecutionPaths = await manifestReferencedClientModules(outputDirectory, files);
369
396
  const ssrExecutionPaths = await routeReferencedSsrModules(outputDirectory, files, 'node');
370
- await assertEveryCompiledIdentityCarrier(outputDirectory, clientExecutionPaths, identity, 'final manifest-referenced Node UI/client');
371
- await assertEveryCompiledIdentityCarrier(outputDirectory, ssrExecutionPaths, identity, 'final route-referenced Node SSR');
372
- await assertEveryCompiledIdentityCarrier(outputDirectory, ssrPaths.filter((logicalPath)=>'index.js' !== logicalPath), identity, 'final compiled Node SSR closure');
373
- await assertEveryCompiledIdentityCarrier(outputDirectory, apiBackendPaths.filter((logicalPath)=>logicalPath.startsWith('api/')), identity, 'final Node API/backend');
374
- await assertEveryCompiledIdentityCarrier(outputDirectory, [
375
- BACKEND_FEDERATION_REMOTE_ENTRY_FILE
376
- ], identity, 'final Node backend Module Federation container');
397
+ if (0 === clientExecutionPaths.length || 0 === ssrExecutionPaths.length) throw new Error('[ultramodern-release-envelope] final Node manifests must reference emitted UI/client and SSR execution modules.');
377
398
  const runtimeByPath = new Map(files.filter((logicalPath)=>!backendFederationPaths.has(logicalPath)).map((logicalPath)=>[
378
399
  logicalPath,
379
400
  'nodejs-deployment'
@@ -383,10 +404,27 @@ const createNodeStagedReleaseArtifactInputs = async (outputDirectory, identity)=
383
404
  for (const logicalPath of apiBackendPaths)runtimeByPath.set(logicalPath, 'nodejs');
384
405
  runtimeByPath.set(BACKEND_FEDERATION_MANIFEST_FILE, 'module-federation-manifest');
385
406
  runtimeByPath.set(BACKEND_FEDERATION_REMOTE_ENTRY_FILE, 'nodejs');
407
+ const identityCarrierMetadata = await writeReleaseIdentityCarrierMetadata(outputDirectory, identity, {
408
+ apiBackend: apiBackendPaths,
409
+ backendFederation: [
410
+ BACKEND_FEDERATION_MANIFEST_FILE,
411
+ BACKEND_FEDERATION_REMOTE_ENTRY_FILE
412
+ ],
413
+ ssr: [
414
+ ...new Set([
415
+ ...ssrExecutionPaths,
416
+ ...ssrPaths.filter((logicalPath)=>'index.js' !== logicalPath)
417
+ ])
418
+ ],
419
+ uiClient: uiClientPaths.filter((logicalPath)=>COMPILED_MODULE_PATTERN.test(logicalPath))
420
+ });
386
421
  return {
387
422
  artifacts: [
388
- ...runtimeByPath
389
- ].map(([logicalPath, runtime])=>releaseArtifact(logicalPath, runtime)).sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath)),
423
+ ...[
424
+ ...runtimeByPath
425
+ ].map(([logicalPath, runtime])=>releaseArtifact(logicalPath, runtime)),
426
+ identityCarrierMetadata
427
+ ].sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath)),
390
428
  surfaces: {
391
429
  uiClient: [
392
430
  ...uiClientPaths
@@ -460,13 +498,7 @@ const createCloudflareStagedReleaseArtifactInputs = async (outputDirectory, iden
460
498
  ])if (!files.includes(logicalPath)) throw new Error(`[ultramodern-release-envelope] final Cloudflare staging is missing ${logicalPath}.`);
461
499
  const clientExecutionPaths = await manifestReferencedClientModules(outputDirectory, files, 'public/mf-manifest.json');
462
500
  const ssrExecutionPaths = await routeReferencedSsrModules(outputDirectory, files, 'cloudflare', 'server/route.json');
463
- await assertEveryCompiledIdentityCarrier(outputDirectory, clientExecutionPaths, identity, 'final manifest-referenced Cloudflare UI/client');
464
- await assertEveryCompiledIdentityCarrier(outputDirectory, ssrExecutionPaths, identity, 'final route-referenced Cloudflare SSR');
465
- await assertEveryCompiledIdentityCarrier(outputDirectory, ssrPaths.filter((logicalPath)=>logicalPath.startsWith('worker/')), identity, 'final compiled Cloudflare SSR/workerd closure');
466
- await assertEveryCompiledIdentityCarrier(outputDirectory, apiBackendPaths, identity, 'final Cloudflare API/backend');
467
- await assertEveryCompiledIdentityCarrier(outputDirectory, [
468
- backendContainerPath
469
- ], identity, 'final Cloudflare backend Module Federation container');
501
+ if (0 === clientExecutionPaths.length || 0 === ssrExecutionPaths.length) throw new Error('[ultramodern-release-envelope] final Cloudflare manifests must reference emitted UI/client and SSR execution modules.');
470
502
  const runtimeByPath = new Map();
471
503
  for (const logicalPath of files)runtimeByPath.set(logicalPath, 'cloudflare-deployment');
472
504
  const add = (paths, runtime)=>{
@@ -481,10 +513,27 @@ const createCloudflareStagedReleaseArtifactInputs = async (outputDirectory, iden
481
513
  add([
482
514
  backendContainerPath
483
515
  ], 'commonjs-module');
516
+ const identityCarrierMetadata = await writeReleaseIdentityCarrierMetadata(outputDirectory, identity, {
517
+ apiBackend: apiBackendPaths,
518
+ backendFederation: [
519
+ backendManifestPath,
520
+ backendContainerPath
521
+ ],
522
+ ssr: [
523
+ ...new Set([
524
+ ...ssrExecutionPaths,
525
+ ...ssrPaths.filter((logicalPath)=>logicalPath.startsWith('worker/'))
526
+ ])
527
+ ],
528
+ uiClient: uiClientPaths.filter((logicalPath)=>COMPILED_MODULE_PATTERN.test(logicalPath))
529
+ });
484
530
  return {
485
531
  artifacts: [
486
- ...runtimeByPath
487
- ].map(([logicalPath, runtime])=>releaseArtifact(logicalPath, runtime)).sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath)),
532
+ ...[
533
+ ...runtimeByPath
534
+ ].map(([logicalPath, runtime])=>releaseArtifact(logicalPath, runtime)),
535
+ identityCarrierMetadata
536
+ ].sort((left, right)=>left.logicalPath.localeCompare(right.logicalPath)),
488
537
  surfaces: {
489
538
  uiClient: [
490
539
  ...uiClientPaths
@@ -521,4 +570,4 @@ const verifyCloudflareReleaseEnvelopeStaging = async (outputDirectory)=>readFram
521
570
  expectedTarget: 'cloudflare',
522
571
  required: true
523
572
  });
524
- export { MICROVERTICAL_RELEASE_ENVELOPE_PATH, emitCloudflareStagedReleaseEnvelope, emitFrameworkMicroVerticalReleaseEnvelope, emitNodeStagedReleaseEnvelope, readFrameworkMicroVerticalReleaseEnvelope, stageCloudflareReleaseEnvelope, verifyBuildOutputReleaseEnvelope, verifyCloudflareReleaseEnvelopeStaging, verifyNodeReleaseEnvelopeStaging };
573
+ export { MICROVERTICAL_RELEASE_ENVELOPE_PATH, MICROVERTICAL_RELEASE_IDENTITY_CARRIERS_PATH, emitCloudflareStagedReleaseEnvelope, emitFrameworkMicroVerticalReleaseEnvelope, emitNodeStagedReleaseEnvelope, readFrameworkMicroVerticalReleaseEnvelope, stageCloudflareReleaseEnvelope, verifyBuildOutputReleaseEnvelope, verifyCloudflareReleaseEnvelopeStaging, verifyNodeReleaseEnvelopeStaging };