@bleedingdev/modern-js-app-tools 3.5.0-ultramodern.27 → 3.5.0-ultramodern.29

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 (28) hide show
  1. package/dist/cjs/index.js +50 -44
  2. package/dist/cjs/plugins/backendFederationBuild.js +347 -0
  3. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-contract.js +91 -0
  4. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-plan.js +93 -0
  5. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier.js +402 -0
  6. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +158 -30
  7. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  8. package/dist/esm/index.mjs +2 -0
  9. package/dist/esm/plugins/backendFederationBuild.mjs +296 -0
  10. package/dist/esm/plugins/deploy/platforms/cloudflare-output-contract.mjs +17 -0
  11. package/dist/esm/plugins/deploy/platforms/cloudflare-output-plan.mjs +45 -0
  12. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier.mjs +347 -0
  13. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +158 -30
  14. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  15. package/dist/esm-node/index.mjs +2 -0
  16. package/dist/esm-node/plugins/backendFederationBuild.mjs +297 -0
  17. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-contract.mjs +18 -0
  18. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-plan.mjs +46 -0
  19. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier.mjs +348 -0
  20. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +158 -30
  21. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  22. package/dist/types/plugins/backendFederationBuild.d.ts +11 -0
  23. package/dist/types/plugins/deploy/platforms/cloudflare-output-contract.d.ts +13 -0
  24. package/dist/types/plugins/deploy/platforms/cloudflare-output-plan.d.ts +33 -0
  25. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier.d.ts +32 -0
  26. package/dist/types/types/config/cloudflareDeploy.d.ts +11 -0
  27. package/dist/types/types/config/deploy.d.ts +11 -3
  28. package/package.json +17 -11
@@ -0,0 +1,348 @@
1
+ import "node:module";
2
+ import promises from "node:fs/promises";
3
+ import node_path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_ENTRY } from "./cloudflare-output-contract.mjs";
6
+ import { createCloudflareOutputPlan } from "./cloudflare-output-plan.mjs";
7
+ const SOURCE_SCAN_FILE_PATTERN = /\.(?:[cm]?[jt]s|json)$/u;
8
+ const SOURCE_SCAN_IGNORED_DIRECTORY_NAMES = new Set([
9
+ '.codex',
10
+ '.fastcontext',
11
+ '.git',
12
+ '.mf',
13
+ '.modernjs',
14
+ '.output',
15
+ 'coverage',
16
+ 'dist',
17
+ 'dist-cloudflare',
18
+ 'node_modules',
19
+ 'repos',
20
+ 'topology'
21
+ ]);
22
+ const FORBIDDEN_MUTATION_PATTERNS = [
23
+ {
24
+ code: 'forbidden-mutation-pattern',
25
+ message: "Generated Cloudflare server worker output must not be rewritten by app scripts.",
26
+ pattern: /\.output\/server\/index\.mjs/u
27
+ },
28
+ {
29
+ code: 'forbidden-mutation-pattern',
30
+ message: "Generated Cloudflare server worker output must not be rewritten by app scripts.",
31
+ pattern: /path\.join\(\s*['"`]\.output['"`]\s*,\s*['"`]server['"`]\s*,\s*['"`]index\.mjs['"`]\s*\)/u
32
+ },
33
+ {
34
+ code: 'forbidden-mutation-pattern',
35
+ message: "Generated Cloudflare BFF worker bundles must not be rewritten by app scripts.",
36
+ pattern: /\.output\/worker\/[^'"`]*\.(?:mjs|cjs|js)/u
37
+ },
38
+ {
39
+ code: 'forbidden-mutation-pattern',
40
+ message: "Generated Cloudflare BFF worker bundles must not be rewritten by app scripts.",
41
+ pattern: /path\.join\(\s*['"`]\.output['"`]\s*,\s*['"`]worker['"`]\s*,\s*['"`][^'"`]+\.(?:mjs|cjs|js)['"`]\s*\)/u
42
+ },
43
+ {
44
+ code: 'forbidden-mutation-pattern',
45
+ message: "Drizzle entityKind worker bundle markers must be fixed in the framework toolchain, not post-build scripts.",
46
+ pattern: /replaceAll\(\s*['"`];entityKind(?:,entityKind)?;/u
47
+ },
48
+ {
49
+ code: 'forbidden-mutation-pattern',
50
+ message: "Effect BFF Cloudflare dispatch must not depend on duck-typed runtime helper probing in app scripts.",
51
+ pattern: /(?:typeof\s+[^;\n]*dispatchEffectBffRequest|['"`]dispatchEffectBffRequest['"`]\s+in\s+|\.dispatchEffectBffRequest\b)/u
52
+ },
53
+ {
54
+ code: 'forbidden-mutation-pattern',
55
+ message: "Effect BFF Cloudflare dispatch must not branch on handler.length in app scripts.",
56
+ pattern: /\bhandler\s*\.\s*length\b/u
57
+ }
58
+ ];
59
+ const pathExists = async (filePath)=>{
60
+ try {
61
+ await promises.access(filePath);
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ };
67
+ const readJson = async (filePath)=>JSON.parse(await promises.readFile(filePath, 'utf-8'));
68
+ const addIssue = (issues, issue)=>{
69
+ issues.push(issue);
70
+ };
71
+ const assertEqual = (issues, actual, expected, issue)=>{
72
+ if (actual !== expected) addIssue(issues, issue);
73
+ };
74
+ const assertFlag = (issues, flags, flag, issue)=>{
75
+ if (!Array.isArray(flags) || !flags.includes(flag)) addIssue(issues, issue);
76
+ };
77
+ 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) : [];
78
+ const getEffectBffWorker = (manifest)=>manifest?.bff?.runtimeFramework === 'effect' && 'string' == typeof manifest.bff.worker ? manifest.bff.worker : void 0;
79
+ const getWorkerBundleReferences = (manifest)=>{
80
+ const effectBffWorker = getEffectBffWorker(manifest);
81
+ return [
82
+ ...effectBffWorker ? [
83
+ {
84
+ kind: 'effect-bff',
85
+ reference: effectBffWorker
86
+ }
87
+ ] : [],
88
+ ...getReferencedRouteWorkers(manifest).map((reference)=>({
89
+ kind: 'route',
90
+ reference
91
+ }))
92
+ ];
93
+ };
94
+ const resolveWorkerBundleReference = (issues, outputDirectory, reference, manifestPath)=>{
95
+ const workerRoot = node_path.resolve(outputDirectory, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY);
96
+ const workerPath = node_path.resolve(outputDirectory, reference.reference);
97
+ const relativeToWorkerRoot = node_path.relative(workerRoot, workerPath);
98
+ if (node_path.isAbsolute(reference.reference) || relativeToWorkerRoot.startsWith('..') || node_path.isAbsolute(relativeToWorkerRoot)) {
99
+ addIssue(issues, {
100
+ code: 'invalid-manifest',
101
+ message: 'Cloudflare output manifest worker bundle references must stay under worker/.',
102
+ path: manifestPath
103
+ });
104
+ return null;
105
+ }
106
+ return {
107
+ ...reference,
108
+ path: workerPath
109
+ };
110
+ };
111
+ const missingWorkerBundleMessage = (reference)=>'effect-bff' === reference.kind ? 'Cloudflare Effect BFF manifest points to a missing worker bundle.' : 'Cloudflare route worker manifest points to a missing worker bundle.';
112
+ const DELIVERY_UNIT_IDENTITY_FIELDS = [
113
+ 'unitId',
114
+ 'buildMarker',
115
+ 'sourceRevision'
116
+ ];
117
+ const verifyDeliveryUnitIdentity = (issues, manifest, manifestPath, declared)=>{
118
+ const stamped = manifest?.deliveryUnit;
119
+ const hasStamp = Boolean(stamped) && 'object' == typeof stamped;
120
+ if (declared) {
121
+ if (!hasStamp) return void addIssue(issues, {
122
+ code: 'missing-delivery-unit',
123
+ message: `Cloudflare worker manifest is missing the delivery-unit identity declared by the workspace topology (expected unitId ${declared.unitId}, buildMarker ${declared.buildMarker}).`,
124
+ path: manifestPath
125
+ });
126
+ for (const field of DELIVERY_UNIT_IDENTITY_FIELDS)assertEqual(issues, stamped[field], declared[field], {
127
+ code: 'delivery-unit-drift',
128
+ message: `Cloudflare worker manifest deliveryUnit.${field} must match the topology delivery-unit record (expected ${declared[field]}, received ${stamped[field] ?? 'undefined'}).`,
129
+ path: manifestPath
130
+ });
131
+ }
132
+ if (hasStamp && stamped.surfaces && 'object' == typeof stamped.surfaces) for (const surface of [
133
+ 'ui',
134
+ 'api'
135
+ ]){
136
+ const marker = stamped.surfaces[surface];
137
+ if (!marker || 'object' != typeof marker) {
138
+ addIssue(issues, {
139
+ code: 'missing-delivery-unit',
140
+ message: `Cloudflare worker manifest is missing the ${surface} delivery-unit surface marker.`,
141
+ path: manifestPath
142
+ });
143
+ continue;
144
+ }
145
+ for (const field of DELIVERY_UNIT_IDENTITY_FIELDS)assertEqual(issues, marker[field], stamped[field], {
146
+ code: 'delivery-unit-drift',
147
+ message: `Cloudflare worker manifest ${surface} surface deliveryUnit.${field} must derive from one delivery-unit record (expected ${stamped[field] ?? 'undefined'}, received ${marker[field] ?? 'undefined'}).`,
148
+ path: manifestPath
149
+ });
150
+ }
151
+ };
152
+ const verifyManifestShape = (issues, manifest, manifestPath)=>{
153
+ assertEqual(issues, manifest.runtime?.type, CLOUDFLARE_RUNTIME_TYPE, {
154
+ code: 'invalid-manifest',
155
+ message: 'Cloudflare output manifest runtime.type must be cloudflare-module-worker.',
156
+ path: manifestPath
157
+ });
158
+ assertEqual(issues, manifest.runtime?.entry, CLOUDFLARE_WORKER_ENTRY, {
159
+ code: 'invalid-manifest',
160
+ message: `Cloudflare output manifest runtime.entry must be ${CLOUDFLARE_WORKER_ENTRY}.`,
161
+ path: manifestPath
162
+ });
163
+ assertEqual(issues, manifest.runtime?.fetchExport, true, {
164
+ code: 'invalid-manifest',
165
+ message: 'Cloudflare output manifest runtime.fetchExport must be true.',
166
+ path: manifestPath
167
+ });
168
+ assertEqual(issues, manifest.runtime?.nodeListen, false, {
169
+ code: 'invalid-manifest',
170
+ message: 'Cloudflare output manifest runtime.nodeListen must be false.',
171
+ path: manifestPath
172
+ });
173
+ assertEqual(issues, manifest.assets?.binding, CLOUDFLARE_ASSETS_BINDING, {
174
+ code: 'invalid-manifest',
175
+ message: 'Cloudflare output manifest assets.binding must be ASSETS.',
176
+ path: manifestPath
177
+ });
178
+ assertEqual(issues, manifest.assets?.directory, `./${CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY}`, {
179
+ code: 'invalid-manifest',
180
+ message: 'Cloudflare output manifest assets.directory must be ./public.',
181
+ path: manifestPath
182
+ });
183
+ assertEqual(issues, manifest.assets?.runWorkerFirst, true, {
184
+ code: 'invalid-manifest',
185
+ message: 'Cloudflare output manifest assets.runWorkerFirst must be true.',
186
+ path: manifestPath
187
+ });
188
+ };
189
+ const walkFiles = async (root)=>{
190
+ if (!await pathExists(root)) return [];
191
+ const entries = await promises.readdir(root, {
192
+ withFileTypes: true
193
+ });
194
+ const files = [];
195
+ for (const entry of entries){
196
+ if (SOURCE_SCAN_IGNORED_DIRECTORY_NAMES.has(entry.name)) continue;
197
+ const entryPath = node_path.join(root, entry.name);
198
+ if (entry.isDirectory()) {
199
+ files.push(...await walkFiles(entryPath));
200
+ continue;
201
+ }
202
+ if (SOURCE_SCAN_FILE_PATTERN.test(entry.name)) files.push(entryPath);
203
+ }
204
+ return files;
205
+ };
206
+ const verifyCloudflareOutputMutationPolicy = async (options)=>{
207
+ const issues = [];
208
+ const files = (await Promise.all(options.scanRoots.map((scanRoot)=>walkFiles(node_path.resolve(scanRoot))))).flat();
209
+ for (const file of files){
210
+ const source = await promises.readFile(file, 'utf-8');
211
+ for (const forbidden of FORBIDDEN_MUTATION_PATTERNS)if (forbidden.pattern.test(source)) addIssue(issues, {
212
+ code: forbidden.code,
213
+ message: forbidden.message,
214
+ path: file
215
+ });
216
+ }
217
+ return {
218
+ ok: 0 === issues.length,
219
+ issues
220
+ };
221
+ };
222
+ const verifyWorkerImport = async (issues, entryPath)=>{
223
+ try {
224
+ const worker = (await import(`${pathToFileURL(entryPath).href}?t=${Date.now()}`)).default;
225
+ if (!worker || 'function' != typeof worker.fetch) addIssue(issues, {
226
+ code: 'worker-import-failed',
227
+ message: 'Cloudflare server entry must default-export a Worker with fetch.',
228
+ path: entryPath
229
+ });
230
+ } catch (error) {
231
+ addIssue(issues, {
232
+ code: 'worker-import-failed',
233
+ message: `Cloudflare server entry could not be imported: ${error instanceof Error ? error.message : String(error)}`,
234
+ path: entryPath
235
+ });
236
+ }
237
+ };
238
+ const verifyCloudflareOutput = async (options)=>{
239
+ const outputDirectory = node_path.resolve(options.outputDirectory);
240
+ const issues = [];
241
+ const outputPlan = createCloudflareOutputPlan(outputDirectory);
242
+ for (const relativePath of outputPlan.requiredFiles){
243
+ const filePath = node_path.join(outputDirectory, relativePath);
244
+ if (!await pathExists(filePath)) addIssue(issues, {
245
+ code: 'missing-file',
246
+ message: `Cloudflare output is missing ${relativePath}.`,
247
+ path: filePath
248
+ });
249
+ }
250
+ const manifestPath = outputPlan.paths.workerManifest;
251
+ const wranglerPath = outputPlan.paths.wranglerConfig;
252
+ const packagePath = outputPlan.paths.outputPackage;
253
+ const workerPackagePath = outputPlan.paths.workerPackage;
254
+ const manifest = await pathExists(manifestPath) ? await readJson(manifestPath) : void 0;
255
+ const wrangler = await pathExists(wranglerPath) ? await readJson(wranglerPath) : void 0;
256
+ const outputPackage = await pathExists(packagePath) ? await readJson(packagePath) : void 0;
257
+ const workerPackage = await pathExists(workerPackagePath) ? await readJson(workerPackagePath) : void 0;
258
+ if (manifest) {
259
+ verifyManifestShape(issues, manifest, manifestPath);
260
+ verifyDeliveryUnitIdentity(issues, manifest, manifestPath, options.deliveryUnit);
261
+ const workerReferences = getWorkerBundleReferences(manifest);
262
+ if (workerReferences.length > 0 && !await pathExists(workerPackagePath)) addIssue(issues, {
263
+ code: 'missing-file',
264
+ message: 'Cloudflare output is missing worker/package.json for referenced worker bundles.',
265
+ path: workerPackagePath
266
+ });
267
+ if (manifest.bff?.runtimeFramework === 'effect' && !getEffectBffWorker(manifest)) addIssue(issues, {
268
+ code: 'missing-worker-bundle',
269
+ message: 'Cloudflare Effect BFF manifest points to a missing worker bundle.'
270
+ });
271
+ for (const workerReference of workerReferences){
272
+ const resolvedWorker = resolveWorkerBundleReference(issues, outputDirectory, workerReference, manifestPath);
273
+ if (!resolvedWorker) continue;
274
+ const workerExists = await pathExists(resolvedWorker.path);
275
+ if (!workerExists) addIssue(issues, {
276
+ code: 'missing-worker-bundle',
277
+ message: missingWorkerBundleMessage(workerReference),
278
+ path: resolvedWorker.path
279
+ });
280
+ if (workerExists && 'effect-bff' === resolvedWorker.kind) {
281
+ const workerSource = await promises.readFile(resolvedWorker.path, 'utf-8');
282
+ if (workerSource.includes(';entityKind;') || workerSource.includes(';entityKind,entityKind;')) addIssue(issues, {
283
+ code: 'invalid-worker-bundle',
284
+ message: 'Cloudflare Effect BFF worker bundle contains invalid Drizzle entityKind marker references.',
285
+ path: resolvedWorker.path
286
+ });
287
+ }
288
+ }
289
+ }
290
+ if (wrangler) {
291
+ assertEqual(issues, wrangler.main, outputPlan.wrangler.main, {
292
+ code: 'invalid-wrangler',
293
+ message: `wrangler.json main must be ${outputPlan.wrangler.main}.`,
294
+ path: wranglerPath
295
+ });
296
+ assertEqual(issues, wrangler.assets?.binding, outputPlan.wrangler.assets.binding, {
297
+ code: 'invalid-wrangler',
298
+ message: 'wrangler.json assets.binding must be ASSETS.',
299
+ path: wranglerPath
300
+ });
301
+ assertEqual(issues, wrangler.assets?.directory, outputPlan.wrangler.assets.directory, {
302
+ code: 'invalid-wrangler',
303
+ message: 'wrangler.json assets.directory must be ./public.',
304
+ path: wranglerPath
305
+ });
306
+ assertEqual(issues, wrangler.assets?.run_worker_first, outputPlan.wrangler.assets.run_worker_first, {
307
+ code: 'invalid-wrangler',
308
+ message: 'wrangler.json assets.run_worker_first must be true.',
309
+ path: wranglerPath
310
+ });
311
+ for (const flag of outputPlan.wrangler.requiredCompatibilityFlags)assertFlag(issues, wrangler.compatibility_flags, flag, {
312
+ code: 'invalid-wrangler',
313
+ message: `wrangler.json compatibility_flags must include ${flag}.`,
314
+ path: wranglerPath
315
+ });
316
+ }
317
+ if (outputPackage) assertEqual(issues, outputPackage.type, outputPlan.packages.output.type, {
318
+ code: 'invalid-package',
319
+ message: '.output/package.json must declare type module.',
320
+ path: packagePath
321
+ });
322
+ if (workerPackage) assertEqual(issues, workerPackage.type, outputPlan.packages.worker.type, {
323
+ code: 'invalid-package',
324
+ message: '.output/worker/package.json must declare type commonjs.',
325
+ path: workerPackagePath
326
+ });
327
+ for (const leakedPath of outputPlan.publicLeakDirectories){
328
+ const publicPath = node_path.join(outputPlan.paths.publicAssets, leakedPath);
329
+ if (await pathExists(publicPath)) addIssue(issues, {
330
+ code: 'public-output-leak',
331
+ message: `Framework-owned ${leakedPath} output leaked into public assets.`,
332
+ path: publicPath
333
+ });
334
+ }
335
+ if (false !== options.importWorker && await pathExists(outputPlan.paths.workerEntry)) await verifyWorkerImport(issues, outputPlan.paths.workerEntry);
336
+ return {
337
+ ok: 0 === issues.length,
338
+ issues
339
+ };
340
+ };
341
+ const assertCloudflareOutput = async (options)=>{
342
+ const result = await verifyCloudflareOutput(options);
343
+ if (!result.ok) throw new Error([
344
+ 'Cloudflare output verification failed:',
345
+ ...result.issues.map((issue)=>`- ${issue.code}: ${issue.message}${issue.path ? ` (${issue.path})` : ''}`)
346
+ ].join('\n'));
347
+ };
348
+ export { assertCloudflareOutput, verifyCloudflareOutput, verifyCloudflareOutputMutationPolicy };
@@ -2,17 +2,19 @@ import "node:module";
2
2
  import node_path from "node:path";
3
3
  import { fs } from "@modern-js/utils";
4
4
  import { readTemplate } from "../utils/index.mjs";
5
- const WORKER_ENTRY = 'server/index.mjs';
6
- const WORKER_MANIFEST = 'server/modern-worker-manifest.json';
7
- const WRANGLER_CONFIG_FILE = 'wrangler.json';
8
- const OUTPUT_PACKAGE_FILE = 'package.json';
9
- const ASSETS_BINDING = 'ASSETS';
5
+ import { CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_OUTPUT_PACKAGE_FILE, CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY, CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_BUNDLE_FORMAT, CLOUDFLARE_WORKER_ENTRY, CLOUDFLARE_WRANGLER_CONFIG_FILE } from "./cloudflare-output-contract.mjs";
6
+ import { createCloudflareOutputPlan } from "./cloudflare-output-plan.mjs";
7
+ import { assertCloudflareOutput } from "./cloudflare-output-verifier.mjs";
8
+ const WORKER_ENTRY = CLOUDFLARE_WORKER_ENTRY;
9
+ const WRANGLER_CONFIG_FILE = CLOUDFLARE_WRANGLER_CONFIG_FILE;
10
+ const OUTPUT_PACKAGE_FILE = CLOUDFLARE_OUTPUT_PACKAGE_FILE;
11
+ const ASSETS_BINDING = CLOUDFLARE_ASSETS_BINDING;
10
12
  const ROUTE_SPEC_FILE = 'route.json';
11
13
  const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
12
14
  const LOADABLE_STATS_FILE = 'loadable-stats.json';
13
15
  const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
14
- const PUBLIC_ASSETS_DIRECTORY = 'public';
15
- const WORKER_BUNDLE_DIRECTORY = 'worker';
16
+ const PUBLIC_ASSETS_DIRECTORY = CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY;
17
+ const WORKER_BUNDLE_DIRECTORY = CLOUDFLARE_WORKER_BUNDLE_DIRECTORY;
16
18
  const SERVER_BUNDLE_DIRECTORY = 'bundles';
17
19
  const SERVER_OUTPUT_DIRECTORY = 'server';
18
20
  const DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES = [
@@ -23,10 +25,7 @@ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.
23
25
  const EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE = 'Ensure the Effect API entry exists at api/index.ts or bff.effect.entry, and import Cloudflare edge handlers from @modern-js/plugin-bff/effect-edge instead of lambda/Hono server helpers.';
24
26
  const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
25
27
  const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
26
- const REQUIRED_COMPATIBILITY_FLAGS = [
27
- 'nodejs_compat',
28
- 'global_fetch_strictly_public'
29
- ];
28
+ const REQUIRED_COMPATIBILITY_FLAGS = CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS;
30
29
  const RESERVED_ARTIFACT_DESTINATION_FILES = new Set([
31
30
  WRANGLER_CONFIG_FILE,
32
31
  OUTPUT_PACKAGE_FILE
@@ -220,11 +219,12 @@ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
220
219
  const configuredName = modernConfig.deploy?.worker?.name?.trim();
221
220
  return configuredName || getWorkerName(appDirectory);
222
221
  };
223
- const normalizeRelativePath = (value, label, scope = 'app output')=>{
222
+ const normalizeRelativePath = (value, label, scope = 'app output', options = {})=>{
224
223
  if ('string' != typeof value) throw new Error(`${label} must be a relative path inside the ${scope}.`);
225
224
  const normalized = value.trim().replace(/\\/g, '/').replace(/^\.\/+/u, '').replace(/\/+$/u, '');
226
225
  const segments = normalized.split('/');
227
- if (!normalized || node_path.isAbsolute(normalized) || '.' === normalized || segments.includes('..')) throw new Error(`${label} must be a relative path inside the ${scope}.`);
226
+ const isRootDestination = '.' === normalized;
227
+ if (!normalized || node_path.isAbsolute(normalized) || !options.allowRoot && isRootDestination || segments.includes('..')) throw new Error(`${label} must be a relative path inside the ${scope}.`);
228
228
  return normalized;
229
229
  };
230
230
  const normalizeDirectiveValues = (value)=>{
@@ -379,9 +379,48 @@ const createWranglerD1Databases = (modernConfig, configuredWranglerD1)=>{
379
379
  if (!Array.isArray(d1Databases)) throw new Error('deploy.worker.d1Databases must be an array.');
380
380
  return d1Databases.map(normalizeD1Database);
381
381
  };
382
+ const normalizeServiceBinding = (service, index)=>{
383
+ const binding = assertNonEmptyString(service.binding, `deploy.worker.services[${index}].binding`);
384
+ const serviceName = assertNonEmptyString(service.service, `deploy.worker.services[${index}].service`);
385
+ const prefix = void 0 === service.prefix ? void 0 : assertNonEmptyString(service.prefix, `deploy.worker.services[${index}].prefix`);
386
+ return {
387
+ binding,
388
+ service: serviceName,
389
+ ...void 0 === prefix ? {} : {
390
+ prefix
391
+ }
392
+ };
393
+ };
394
+ const createWorkerServiceBindings = (modernConfig, configuredWranglerServices)=>{
395
+ const services = modernConfig.deploy?.worker?.services;
396
+ if (void 0 === services) return configuredWranglerServices;
397
+ if (void 0 !== configuredWranglerServices) throw new Error('Use deploy.worker.services or deploy.worker.wrangler.services, not both.');
398
+ if (!Array.isArray(services)) throw new Error('deploy.worker.services must be an array.');
399
+ return services.map(normalizeServiceBinding);
400
+ };
401
+ const createWranglerServices = (serviceBindings)=>{
402
+ if (!Array.isArray(serviceBindings)) return serviceBindings;
403
+ if (!serviceBindings.every(isJsonRecord)) return serviceBindings;
404
+ return serviceBindings.map((service)=>{
405
+ const { prefix, ...wranglerService } = service;
406
+ return wranglerService;
407
+ });
408
+ };
409
+ const createWorkerManifestServiceBindings = (serviceBindings)=>{
410
+ if (!Array.isArray(serviceBindings)) return;
411
+ const dispatchBindings = serviceBindings.filter((service)=>isJsonRecord(service) && 'string' == typeof service.binding && 'string' == typeof service.service && 'string' == typeof service.prefix).map((service)=>({
412
+ binding: service.binding,
413
+ service: service.service,
414
+ prefix: service.prefix,
415
+ interface: 'fetch'
416
+ }));
417
+ return dispatchBindings.length > 0 ? dispatchBindings : void 0;
418
+ };
382
419
  const createWranglerConfig = (appDirectory, modernConfig)=>{
383
420
  const wrangler = getConfiguredWrangler(modernConfig);
384
421
  const d1Databases = createWranglerD1Databases(modernConfig, wrangler.d1_databases);
422
+ const serviceBindings = createWorkerServiceBindings(modernConfig, wrangler.services);
423
+ const wranglerServices = createWranglerServices(serviceBindings);
385
424
  return {
386
425
  $schema: 'node_modules/wrangler/config-schema.json',
387
426
  name: getConfiguredWorkerName(appDirectory, modernConfig),
@@ -392,6 +431,9 @@ const createWranglerConfig = (appDirectory, modernConfig)=>{
392
431
  assets: createWranglerAssetsConfig(wrangler.assets),
393
432
  ...void 0 === d1Databases ? {} : {
394
433
  d1_databases: d1Databases
434
+ },
435
+ ...void 0 === wranglerServices ? {} : {
436
+ services: wranglerServices
395
437
  }
396
438
  };
397
439
  };
@@ -410,7 +452,9 @@ const normalizeCloudflareArtifact = (artifact, index)=>{
410
452
  const getCloudflareArtifacts = (modernConfig)=>(modernConfig.deploy?.worker?.artifacts ?? []).map(normalizeCloudflareArtifact);
411
453
  const normalizeCloudflarePublicAsset = (asset, index)=>{
412
454
  const from = normalizeRelativePath(asset.from, `deploy.worker.publicAssets[${index}].from`, 'app root');
413
- const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output');
455
+ const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output', {
456
+ allowRoot: true
457
+ });
414
458
  return {
415
459
  from,
416
460
  to,
@@ -452,8 +496,79 @@ const readRouteSpec = async (outputDirectory)=>{
452
496
  routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
453
497
  };
454
498
  };
499
+ const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
500
+ const ULTRAMODERN_BUILD_MODULE = 'shared/ultramodern-build.ts';
501
+ const nonEmptyString = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
502
+ const toDeliveryUnitIdentity = (value)=>{
503
+ if (!isRecord(value)) return;
504
+ const unitId = nonEmptyString(value.unitId);
505
+ const buildMarker = nonEmptyString(value.buildMarker);
506
+ const sourceRevision = nonEmptyString(value.sourceRevision);
507
+ if (!unitId || !buildMarker || !sourceRevision) return;
508
+ return {
509
+ unitId,
510
+ buildMarker,
511
+ sourceRevision
512
+ };
513
+ };
514
+ const findWorkspaceRoot = async (appDirectory)=>{
515
+ let current = node_path.resolve(appDirectory);
516
+ for(;;){
517
+ if (await fs.pathExists(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
518
+ const parent = node_path.dirname(current);
519
+ if (parent === current) return;
520
+ current = parent;
521
+ }
522
+ };
523
+ const resolveTopologyDeliveryUnit = async (appDirectory)=>{
524
+ const workspaceRoot = await findWorkspaceRoot(appDirectory);
525
+ if (!workspaceRoot) return;
526
+ let compactConfig;
527
+ try {
528
+ compactConfig = await fs.readJSON(node_path.join(workspaceRoot, COMPACT_CONFIG_PATH));
529
+ } catch {
530
+ return;
531
+ }
532
+ if (!isRecord(compactConfig)) return;
533
+ const topology = isRecord(compactConfig.topology) ? compactConfig.topology : void 0;
534
+ const apps = Array.isArray(topology?.apps) ? topology.apps : [];
535
+ const resolvedAppDirectory = node_path.resolve(appDirectory);
536
+ for (const app of apps){
537
+ if (!isRecord(app)) continue;
538
+ const appPath = nonEmptyString(app.path);
539
+ if (appPath && node_path.resolve(workspaceRoot, appPath.replace(/^\.\/+/u, '')) === resolvedAppDirectory) return toDeliveryUnitIdentity(app.deliveryUnit);
540
+ }
541
+ return toDeliveryUnitIdentity(compactConfig.deliveryUnit);
542
+ };
543
+ const resolveWorkerDeliveryUnitStamp = async (appDirectory)=>{
544
+ const buildModulePath = node_path.join(appDirectory, ULTRAMODERN_BUILD_MODULE);
545
+ if (!await fs.pathExists(buildModulePath)) return;
546
+ const source = await fs.readFile(buildModulePath, 'utf8');
547
+ const buildMarker = source.match(/\bbuild:\s*['"]([^'"]+)['"]/u)?.[1];
548
+ const unitId = source.match(/\bunitId:\s*['"]([^'"]+)['"]/u)?.[1];
549
+ const sourceRevision = source.match(/\bsourceRevision:\s*['"]([^'"]+)['"]/u)?.[1];
550
+ if (!buildMarker || !unitId || !sourceRevision) return;
551
+ const identity = {
552
+ unitId,
553
+ buildMarker,
554
+ sourceRevision
555
+ };
556
+ return {
557
+ ...identity,
558
+ surfaces: {
559
+ ui: {
560
+ ...identity,
561
+ surface: 'ui'
562
+ },
563
+ api: {
564
+ ...identity,
565
+ surface: 'api'
566
+ }
567
+ }
568
+ };
569
+ };
455
570
  const createMissingEffectBffWorkerError = (outputDirectory, worker)=>new Error(`Cloudflare Effect API runtime is configured, but the BFF worker bundle is missing: ${node_path.join(outputDirectory, worker)}. ${EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE}`);
456
- const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>{
571
+ const createWorkerManifest = async (outputDirectory, modernConfig, appContext, deliveryUnitStamp)=>{
457
572
  const routeSpec = await readRouteSpec(outputDirectory);
458
573
  const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
459
574
  const worker = 'string' == typeof route.worker ? route.worker : void 0;
@@ -470,11 +585,12 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
470
585
  const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
471
586
  const isEffectApi = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
472
587
  const effectApiWorkerExists = await fs.pathExists(node_path.join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
588
+ const serviceBindings = createWorkerManifestServiceBindings(createWorkerServiceBindings(modernConfig, void 0));
473
589
  if (isEffectApi && primaryBffPrefix && !effectApiWorkerExists) throw createMissingEffectBffWorkerError(outputDirectory, BFF_EFFECT_WORKER_ENTRY);
474
590
  return {
475
591
  version: 1,
476
592
  runtime: {
477
- type: 'cloudflare-module-worker',
593
+ type: CLOUDFLARE_RUNTIME_TYPE,
478
594
  entry: WORKER_ENTRY,
479
595
  fetchExport: true,
480
596
  nodeListen: false
@@ -490,7 +606,7 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
490
606
  },
491
607
  workerBundles: {
492
608
  directory: WORKER_BUNDLE_DIRECTORY,
493
- format: 'commonjs',
609
+ format: CLOUDFLARE_WORKER_BUNDLE_FORMAT,
494
610
  importableFromModuleWorker: true,
495
611
  requestHandlerExport: 'requestHandler'
496
612
  },
@@ -499,12 +615,18 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
499
615
  routeManifest: ROUTE_MANIFEST_FILE
500
616
  },
501
617
  security: createCloudflareWorkerSecurityPolicy(modernConfig),
618
+ ...deliveryUnitStamp ? {
619
+ deliveryUnit: deliveryUnitStamp
620
+ } : {},
502
621
  i18n: createI18nWorkerManifest(routeSpec, appContext),
503
622
  bff: isEffectApi && primaryBffPrefix && effectApiWorkerExists ? {
504
623
  runtimeFramework: 'effect',
505
624
  prefix: primaryBffPrefix,
506
625
  worker: BFF_EFFECT_WORKER_ENTRY
507
- } : void 0
626
+ } : void 0,
627
+ ...void 0 === serviceBindings ? {} : {
628
+ serviceBindings
629
+ }
508
630
  };
509
631
  };
510
632
  const createWorkerModuleLoaders = (manifest)=>{
@@ -556,11 +678,12 @@ const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
556
678
  const createCloudflarePreset = ({ appContext, modernConfig })=>{
557
679
  const { appDirectory, distDirectory } = appContext;
558
680
  const outputDirectory = node_path.join(appDirectory, '.output');
559
- const publicDirectory = node_path.join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
560
- const workerEntryPath = node_path.join(outputDirectory, WORKER_ENTRY);
561
- const workerManifestPath = node_path.join(outputDirectory, WORKER_MANIFEST);
681
+ const outputPlan = createCloudflareOutputPlan(outputDirectory);
682
+ const publicDirectory = outputPlan.paths.publicAssets;
683
+ const workerEntryPath = outputPlan.paths.workerEntry;
684
+ const workerManifestPath = outputPlan.paths.workerManifest;
562
685
  const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
563
- const wranglerConfigPath = node_path.join(outputDirectory, WRANGLER_CONFIG_FILE);
686
+ const wranglerConfigPath = outputPlan.paths.wranglerConfig;
564
687
  const cloudflareArtifacts = getCloudflareArtifacts(modernConfig);
565
688
  const publicAssetExcludes = getPublicAssetExcludes(appDirectory, modernConfig);
566
689
  return {
@@ -576,14 +699,12 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
576
699
  const routeSpecSourcePath = node_path.join(distDirectory, ROUTE_SPEC_FILE);
577
700
  if (await fs.pathExists(routeSpecSourcePath)) await fs.copy(routeSpecSourcePath, routeSpecOutputPath);
578
701
  const workerBundleSourceDirectory = node_path.join(distDirectory, WORKER_BUNDLE_DIRECTORY);
579
- const workerBundleOutputDirectory = node_path.join(outputDirectory, WORKER_BUNDLE_DIRECTORY);
702
+ const workerBundleOutputDirectory = outputPlan.paths.workerBundle;
580
703
  if (await fs.pathExists(workerBundleSourceDirectory)) {
581
704
  await fs.copy(workerBundleSourceDirectory, workerBundleOutputDirectory, {
582
705
  filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
583
706
  });
584
- await fs.writeJSON(node_path.join(workerBundleOutputDirectory, 'package.json'), {
585
- type: 'commonjs'
586
- });
707
+ await fs.writeJSON(outputPlan.paths.workerPackage, outputPlan.packages.worker);
587
708
  }
588
709
  await copyCloudflareArtifacts(appDirectory, outputDirectory, cloudflareArtifacts);
589
710
  await copyCloudflarePublicAssets(appDirectory, publicDirectory, getCloudflarePublicAssets(modernConfig));
@@ -591,17 +712,24 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
591
712
  await fs.writeJSON(wranglerConfigPath, createWranglerConfig(appDirectory, modernConfig), {
592
713
  spaces: 2
593
714
  });
594
- await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig, appContext), {
715
+ const deliveryUnitStamp = await resolveWorkerDeliveryUnitStamp(appDirectory);
716
+ await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig, appContext, deliveryUnitStamp), {
595
717
  spaces: 2
596
718
  });
597
- await fs.writeJSON(node_path.join(outputDirectory, OUTPUT_PACKAGE_FILE), {
598
- type: 'module'
599
- });
719
+ await fs.writeJSON(outputPlan.paths.outputPackage, outputPlan.packages.output);
600
720
  },
601
721
  async genEntry () {
602
722
  const template = await readTemplate('cloudflare-entry.mjs');
603
723
  const manifest = await fs.readJSON(workerManifestPath);
604
724
  await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
725
+ const topologyDeliveryUnit = await resolveTopologyDeliveryUnit(appDirectory);
726
+ await assertCloudflareOutput({
727
+ outputDirectory,
728
+ importWorker: false,
729
+ ...topologyDeliveryUnit ? {
730
+ deliveryUnit: topologyDeliveryUnit
731
+ } : {}
732
+ });
605
733
  }
606
734
  };
607
735
  };