@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.17 → 3.2.0-ultramodern.22

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.
@@ -0,0 +1,184 @@
1
+ import node_path from "node:path";
2
+ import { fs } from "@modern-js/utils";
3
+ import { readTemplate } from "../utils/index.mjs";
4
+ const WORKER_ENTRY = 'server/index.mjs';
5
+ const WORKER_MANIFEST = 'server/modern-worker-manifest.json';
6
+ const ASSETS_BINDING = 'ASSETS';
7
+ const ROUTE_SPEC_FILE = 'route.json';
8
+ const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
9
+ const LOADABLE_STATS_FILE = 'loadable-stats.json';
10
+ const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
11
+ const PUBLIC_ASSETS_DIRECTORY = 'public';
12
+ const WORKER_BUNDLE_DIRECTORY = 'worker';
13
+ const SERVER_BUNDLE_DIRECTORY = 'bundles';
14
+ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
15
+ const getCompatibilityDate = ()=>new Date().toISOString().slice(0, 10);
16
+ const getWorkerName = (appDirectory)=>{
17
+ const basename = node_path.basename(appDirectory);
18
+ return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
19
+ };
20
+ const readRouteSpec = async (outputDirectory)=>{
21
+ const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
22
+ if (!await fs.pathExists(routeSpecPath)) return {
23
+ routes: []
24
+ };
25
+ const routeSpec = await fs.readJSON(routeSpecPath);
26
+ return {
27
+ ...routeSpec,
28
+ routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
29
+ };
30
+ };
31
+ const createWorkerManifest = async (outputDirectory, modernConfig)=>{
32
+ const routeSpec = await readRouteSpec(outputDirectory);
33
+ const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
34
+ const worker = 'string' == typeof route.worker ? route.worker : void 0;
35
+ return {
36
+ urlPath: route.urlPath,
37
+ entryName: route.entryName,
38
+ entryPath: route.entryPath,
39
+ isSSR: Boolean(route.isSSR),
40
+ worker,
41
+ bundle: 'string' == typeof route.bundle ? route.bundle : void 0,
42
+ workerExists: worker ? await fs.pathExists(node_path.join(outputDirectory, worker)) : false,
43
+ bundleExists: 'string' == typeof route.bundle ? await fs.pathExists(node_path.join(outputDirectory, route.bundle)) : false
44
+ };
45
+ }));
46
+ const bffPrefix = modernConfig.bff?.prefix;
47
+ const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
48
+ const isEffectBff = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
49
+ const effectBffWorkerExists = await fs.pathExists(node_path.join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
50
+ return {
51
+ version: 1,
52
+ runtime: {
53
+ type: 'cloudflare-module-worker',
54
+ entry: WORKER_ENTRY,
55
+ fetchExport: true,
56
+ nodeListen: false
57
+ },
58
+ assets: {
59
+ binding: ASSETS_BINDING,
60
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`
61
+ },
62
+ routeSpec: {
63
+ file: ROUTE_SPEC_OUTPUT,
64
+ routes
65
+ },
66
+ workerBundles: {
67
+ directory: WORKER_BUNDLE_DIRECTORY,
68
+ format: 'esm',
69
+ importableFromModuleWorker: true,
70
+ requestHandlerExport: 'requestHandler'
71
+ },
72
+ resources: {
73
+ loadableStats: LOADABLE_STATS_FILE,
74
+ routeManifest: ROUTE_MANIFEST_FILE
75
+ },
76
+ bff: isEffectBff && primaryBffPrefix && effectBffWorkerExists ? {
77
+ runtimeFramework: 'effect',
78
+ prefix: primaryBffPrefix,
79
+ worker: BFF_EFFECT_WORKER_ENTRY
80
+ } : void 0
81
+ };
82
+ };
83
+ const createWorkerModuleLoaders = (manifest)=>{
84
+ const imports = new Map();
85
+ for (const route of manifest.routeSpec.routes){
86
+ if (route.worker && route.workerExists) {
87
+ const importPath = `../${String(route.worker).replace(/^\/+/u, '')}`;
88
+ imports.set(route.worker, `() => import(${JSON.stringify(importPath)})`);
89
+ }
90
+ if (route.bundle && route.bundleExists) {
91
+ const importPath = `../${String(route.bundle).replace(/^\/+/u, '')}`;
92
+ imports.set(route.bundle, `() => import(${JSON.stringify(importPath)})`);
93
+ }
94
+ }
95
+ if (manifest.bff?.worker) {
96
+ const importPath = `../${String(manifest.bff.worker).replace(/^\/+/u, '')}`;
97
+ imports.set(manifest.bff.worker, `() => import(${JSON.stringify(importPath)})`);
98
+ }
99
+ if (0 === imports.size) return '{}';
100
+ const loaders = [
101
+ ...imports.entries()
102
+ ].map(([worker, loader])=>`${JSON.stringify(worker)}: ${loader}`);
103
+ return `{\n${loaders.join(',\n')}\n}`;
104
+ };
105
+ const shouldCopyToPublicAssets = (src, distDirectory)=>{
106
+ const relativePath = node_path.relative(distDirectory, src);
107
+ if (!relativePath) return true;
108
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
109
+ const [topLevelDirectory] = normalizedRelativePath.split('/');
110
+ return normalizedRelativePath !== ROUTE_SPEC_FILE && topLevelDirectory !== WORKER_BUNDLE_DIRECTORY && topLevelDirectory !== SERVER_BUNDLE_DIRECTORY;
111
+ };
112
+ const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
113
+ const relativePath = node_path.relative(workerBundleDirectory, src);
114
+ if (!relativePath) return true;
115
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
116
+ const basename = node_path.basename(normalizedRelativePath);
117
+ if (basename.startsWith('.') || normalizedRelativePath.includes('/.')) return false;
118
+ return [
119
+ '.cjs',
120
+ '.js',
121
+ '.mjs'
122
+ ].includes(node_path.extname(normalizedRelativePath));
123
+ };
124
+ const createCloudflarePreset = ({ appContext, modernConfig })=>{
125
+ const { appDirectory, distDirectory } = appContext;
126
+ const outputDirectory = node_path.join(appDirectory, '.output');
127
+ const publicDirectory = node_path.join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
128
+ const workerEntryPath = node_path.join(outputDirectory, WORKER_ENTRY);
129
+ const workerManifestPath = node_path.join(outputDirectory, WORKER_MANIFEST);
130
+ const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
131
+ const wranglerConfigPath = node_path.join(outputDirectory, 'wrangler.json');
132
+ return {
133
+ async prepare () {
134
+ await fs.remove(outputDirectory);
135
+ },
136
+ async writeOutput () {
137
+ await fs.copy(distDirectory, publicDirectory, {
138
+ filter: (src)=>shouldCopyToPublicAssets(src, distDirectory)
139
+ });
140
+ await fs.ensureDir(node_path.dirname(workerEntryPath));
141
+ await fs.ensureDir(node_path.dirname(workerManifestPath));
142
+ const routeSpecSourcePath = node_path.join(distDirectory, ROUTE_SPEC_FILE);
143
+ if (await fs.pathExists(routeSpecSourcePath)) await fs.copy(routeSpecSourcePath, routeSpecOutputPath);
144
+ const workerBundleSourceDirectory = node_path.join(distDirectory, WORKER_BUNDLE_DIRECTORY);
145
+ if (await fs.pathExists(workerBundleSourceDirectory)) await fs.copy(workerBundleSourceDirectory, node_path.join(outputDirectory, WORKER_BUNDLE_DIRECTORY), {
146
+ filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
147
+ });
148
+ const serverBundleSourceDirectory = node_path.join(distDirectory, SERVER_BUNDLE_DIRECTORY);
149
+ if (await fs.pathExists(serverBundleSourceDirectory)) {
150
+ await fs.copy(serverBundleSourceDirectory, node_path.join(outputDirectory, SERVER_BUNDLE_DIRECTORY));
151
+ await fs.writeJSON(node_path.join(outputDirectory, SERVER_BUNDLE_DIRECTORY, 'package.json'), {
152
+ type: 'commonjs'
153
+ });
154
+ }
155
+ await fs.writeJSON(wranglerConfigPath, {
156
+ $schema: 'node_modules/wrangler/config-schema.json',
157
+ name: getWorkerName(appDirectory),
158
+ main: WORKER_ENTRY,
159
+ compatibility_date: getCompatibilityDate(),
160
+ compatibility_flags: [
161
+ 'nodejs_compat'
162
+ ],
163
+ assets: {
164
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
165
+ binding: ASSETS_BINDING
166
+ }
167
+ }, {
168
+ spaces: 2
169
+ });
170
+ await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig), {
171
+ spaces: 2
172
+ });
173
+ await fs.writeJSON(node_path.join(outputDirectory, 'package.json'), {
174
+ type: 'module'
175
+ });
176
+ },
177
+ async genEntry () {
178
+ const template = await readTemplate('cloudflare-entry.mjs');
179
+ const manifest = await fs.readJSON(workerManifestPath);
180
+ await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
181
+ }
182
+ };
183
+ };
184
+ export { createCloudflarePreset };
@@ -0,0 +1,227 @@
1
+ const ASSETS_BINDING = 'ASSETS';
2
+ const MODERN_WORKER_MANIFEST = p_workerManifest;
3
+ const WORKER_MODULE_LOADERS = p_workerModuleLoaders;
4
+ const workerModulePromises = new Map();
5
+ globalThis.__dirname ??= '/';
6
+ globalThis.__filename ??= '/index.js';
7
+ async function fetchAsset(request, env) {
8
+ const assets = env?.[ASSETS_BINDING];
9
+ if (!assets || 'function' != typeof assets.fetch) return null;
10
+ const response = await assets.fetch(request);
11
+ if (404 === response.status) return null;
12
+ return response;
13
+ }
14
+ async function fetchAssetByPath(pathname, request, env) {
15
+ const url = new URL(request.url);
16
+ url.pathname = `/${pathname.replace(/^\/+/u, '')}`;
17
+ return fetchAsset(new Request(url, request), env);
18
+ }
19
+ async function readAssetText(pathname, request, env) {
20
+ const response = await fetchAssetByPath(pathname, request, env);
21
+ if (!response || !response.ok) return;
22
+ return response.text();
23
+ }
24
+ async function readAssetJson(pathname, request, env) {
25
+ const text = await readAssetText(pathname, request, env);
26
+ if (!text) return {};
27
+ return JSON.parse(text);
28
+ }
29
+ function normalizeRoutePath(pathname) {
30
+ if ('/' === pathname) return pathname;
31
+ return pathname.replace(/\/+$/u, '');
32
+ }
33
+ function routeMatches(route, pathname) {
34
+ if ('string' != typeof route.urlPath) return false;
35
+ const routePath = normalizeRoutePath(route.urlPath);
36
+ const requestPath = normalizeRoutePath(pathname);
37
+ return routePath === requestPath || '/' === routePath && route.isSSR || requestPath.startsWith(`${routePath}/`);
38
+ }
39
+ function findRoute(request) {
40
+ const { pathname } = new URL(request.url);
41
+ const routes = MODERN_WORKER_MANIFEST.routeSpec.routes;
42
+ return [
43
+ ...routes
44
+ ].sort((left, right)=>{
45
+ const leftLength = left.urlPath?.length || 0;
46
+ const rightLength = right.urlPath?.length || 0;
47
+ return rightLength - leftLength;
48
+ }).find((route)=>routeMatches(route, pathname));
49
+ }
50
+ async function fetchRouteHtml(route, request, env) {
51
+ if (!route?.entryPath) return null;
52
+ return fetchAssetByPath(route.entryPath, request, env);
53
+ }
54
+ function createNoopMonitors() {
55
+ const noop = ()=>{};
56
+ return {
57
+ debug: noop,
58
+ error: noop,
59
+ info: noop,
60
+ warn: noop
61
+ };
62
+ }
63
+ function createRequestHandlerOptions({ route, htmlTemplate, routeManifest, loadableStats }) {
64
+ const monitors = createNoopMonitors();
65
+ return {
66
+ resource: {
67
+ route,
68
+ routeManifest,
69
+ loadableStats,
70
+ htmlTemplate,
71
+ entryName: route.entryName
72
+ },
73
+ params: {},
74
+ loaderContext: {},
75
+ config: {},
76
+ locals: {},
77
+ staticGenerate: false,
78
+ monitors,
79
+ onError (error) {
80
+ monitors.error(error);
81
+ },
82
+ onTiming () {},
83
+ reporter: {
84
+ reportTiming: ()=>{}
85
+ }
86
+ };
87
+ }
88
+ async function getRequestHandlerOptions(route, request, env) {
89
+ const [htmlTemplate, routeManifest, loadableStats] = await Promise.all([
90
+ readAssetText(route.entryPath, request, env),
91
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.routeManifest, request, env),
92
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.loadableStats, request, env)
93
+ ]);
94
+ return createRequestHandlerOptions({
95
+ route,
96
+ htmlTemplate: htmlTemplate || '',
97
+ routeManifest,
98
+ loadableStats
99
+ });
100
+ }
101
+ async function loadWorkerModule(workerPath) {
102
+ const loader = WORKER_MODULE_LOADERS[workerPath];
103
+ if (!loader) return;
104
+ if (!workerModulePromises.has(workerPath)) workerModulePromises.set(workerPath, loader());
105
+ return workerModulePromises.get(workerPath);
106
+ }
107
+ function getFetchHandler(workerModule) {
108
+ const defaultExport = workerModule.default;
109
+ return defaultExport && 'object' == typeof defaultExport && 'function' == typeof defaultExport.fetch && defaultExport.fetch.bind(defaultExport) || 'function' == typeof workerModule.fetch && workerModule.fetch;
110
+ }
111
+ async function getRequestHandler(workerModule) {
112
+ const defaultExport = workerModule.default;
113
+ const defaultRequestHandler = defaultExport && 'object' == typeof defaultExport && 'requestHandler' in defaultExport ? defaultExport.requestHandler : void 0;
114
+ return await workerModule.requestHandler || await defaultRequestHandler || ('function' == typeof defaultExport ? defaultExport : void 0);
115
+ }
116
+ async function dispatchRouteWorker(route, request, env, ctx) {
117
+ const candidatePaths = [
118
+ route.worker,
119
+ route.bundle
120
+ ].filter(Boolean);
121
+ let missingPath;
122
+ for (const candidatePath of candidatePaths){
123
+ const workerModule = await loadWorkerModule(candidatePath);
124
+ if (!workerModule) {
125
+ missingPath = candidatePath;
126
+ continue;
127
+ }
128
+ const fetchHandler = getFetchHandler(workerModule);
129
+ if (fetchHandler) return fetchHandler(request, env, ctx);
130
+ const requestHandler = await getRequestHandler(workerModule);
131
+ if ('function' == typeof requestHandler) {
132
+ const requestHandlerOptions = await getRequestHandlerOptions(route, request, env);
133
+ return requestHandler(request, requestHandlerOptions);
134
+ }
135
+ }
136
+ if (missingPath) return new Response(`Worker bundle not found: ${missingPath}`, {
137
+ status: 500,
138
+ headers: {
139
+ 'content-type': 'text/plain; charset=utf-8',
140
+ 'x-modern-js-route-worker': missingPath
141
+ }
142
+ });
143
+ if (candidatePaths.length > 0) return new Response(`Worker bundle has no fetch or requestHandler export: ${candidatePaths.join(', ')}`, {
144
+ status: 500,
145
+ headers: {
146
+ 'content-type': 'text/plain; charset=utf-8',
147
+ 'x-modern-js-route-worker': candidatePaths.join(', ')
148
+ }
149
+ });
150
+ return new Response('Route has no worker bundle', {
151
+ status: 500
152
+ });
153
+ }
154
+ function matchesPrefix(pathname, prefix) {
155
+ if (!prefix || '/' === prefix) return true;
156
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
157
+ return pathname === normalized || pathname.startsWith(`${normalized}/`);
158
+ }
159
+ function createRequestForMountedPrefix(request, prefix) {
160
+ if (!prefix || '/' === prefix) return request;
161
+ const url = new URL(request.url);
162
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
163
+ if (!matchesPrefix(url.pathname, normalized)) return request;
164
+ const nextPath = url.pathname.slice(normalized.length) || '/';
165
+ url.pathname = nextPath.startsWith('/') ? nextPath : `/${nextPath}`;
166
+ return new Request(url, request);
167
+ }
168
+ function createEffectContext(originalRequest, mountedRequest, env) {
169
+ const url = new URL(originalRequest.url);
170
+ return {
171
+ request: mountedRequest,
172
+ env: env || {},
173
+ path: url.pathname,
174
+ method: originalRequest.method,
175
+ operationContext: {
176
+ request: mountedRequest,
177
+ env: env || {},
178
+ path: url.pathname,
179
+ method: originalRequest.method
180
+ }
181
+ };
182
+ }
183
+ async function dispatchBffRequest(request, env) {
184
+ const bff = MODERN_WORKER_MANIFEST.bff;
185
+ if (!bff?.worker || !matchesPrefix(new URL(request.url).pathname, bff.prefix)) return null;
186
+ const workerModule = await loadWorkerModule(bff.worker);
187
+ if (!workerModule) return new Response(`BFF worker bundle not found: ${bff.worker}`, {
188
+ status: 500,
189
+ headers: {
190
+ 'content-type': 'text/plain; charset=utf-8',
191
+ 'x-modern-js-bff-worker': bff.worker
192
+ }
193
+ });
194
+ const mountedRequest = createRequestForMountedPrefix(request, bff.prefix);
195
+ const effectContext = createEffectContext(request, mountedRequest, env);
196
+ const defaultExport = workerModule.default;
197
+ const runtime = defaultExport && 'object' == typeof defaultExport ? {
198
+ ...workerModule,
199
+ ...defaultExport
200
+ } : workerModule;
201
+ const directHandler = 'function' == typeof runtime.handler && runtime.handler || 'function' == typeof defaultExport && defaultExport;
202
+ const createdHandler = 'function' == typeof runtime.createHandler ? runtime.createHandler().handler : void 0;
203
+ const handler = directHandler || createdHandler;
204
+ if ('function' != typeof handler) return new Response(`BFF worker bundle has no handler export: ${bff.worker}`, {
205
+ status: 500,
206
+ headers: {
207
+ 'content-type': 'text/plain; charset=utf-8',
208
+ 'x-modern-js-bff-worker': bff.worker
209
+ }
210
+ });
211
+ return handler.length > 1 ? handler(mountedRequest, effectContext) : handler(mountedRequest);
212
+ }
213
+ export default {
214
+ async fetch (request, env, ctx) {
215
+ const assetResponse = await fetchAsset(request, env);
216
+ if (assetResponse) return assetResponse;
217
+ const bffResponse = await dispatchBffRequest(request, env);
218
+ if (bffResponse) return bffResponse;
219
+ const route = findRoute(request);
220
+ if (route?.worker) return dispatchRouteWorker(route, request, env, ctx);
221
+ const htmlResponse = await fetchRouteHtml(route, request, env);
222
+ if (htmlResponse) return htmlResponse;
223
+ return new Response('Not found', {
224
+ status: 404
225
+ });
226
+ }
227
+ };
@@ -7,12 +7,12 @@ import { loadInternalPlugins } from "./utils/loadPlugins.mjs";
7
7
  import { __webpack_require__ } from "./rslib-runtime.mjs";
8
8
  import * as __rspack_external__modern_js_plugin_cli_caa09fa2 from "@modern-js/plugin/cli";
9
9
  __webpack_require__.add({
10
- "@modern-js/plugin/cli?f956" (module) {
10
+ "@modern-js/plugin/cli?8936" (module) {
11
11
  module.exports = __rspack_external__modern_js_plugin_cli_caa09fa2;
12
12
  }
13
13
  });
14
14
  const MODERN_META_NAME = 'modern-js';
15
- const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?f956");
15
+ const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?8936");
16
16
  async function resolveModernRsbuildConfig(options) {
17
17
  const { cwd = process.cwd(), metaName = MODERN_META_NAME } = options;
18
18
  const configFile = options.configPath || getConfigFile(void 0, cwd);
@@ -1,6 +1,42 @@
1
- import "node:module";
1
+ import __rslib_shim_module__ from "node:module";
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
+ import node_fs from "node:fs";
4
+ import node_path from "node:path";
2
5
  import { SERVICE_WORKER_ENVIRONMENT_NAME } from "@modern-js/builder";
3
6
  import { isProd, isSSR, isServiceWorker, isUseRsc, isUseSSRBundle } from "@modern-js/utils";
7
+ const BFF_EFFECT_WORKER_ENTRY_NAME = '__modern_bff_effect';
8
+ const BFF_EFFECT_WORKER_RUNTIME_QUERY = 'modern-bff-runtime';
9
+ const JS_OR_TS_EXTS = [
10
+ '.ts',
11
+ '.tsx',
12
+ '.js',
13
+ '.jsx',
14
+ '.mjs',
15
+ '.cjs'
16
+ ];
17
+ function findExistingFile(candidates) {
18
+ return candidates.find((candidate)=>node_fs.existsSync(candidate));
19
+ }
20
+ function resolvePackageFile(packageName, filePath, paths) {
21
+ try {
22
+ const packageJsonPath = require.resolve(`${packageName}/package.json`, {
23
+ paths
24
+ });
25
+ const packageFile = node_path.join(node_path.dirname(packageJsonPath), filePath);
26
+ return node_fs.existsSync(packageFile) ? node_fs.realpathSync(packageFile) : void 0;
27
+ } catch {
28
+ return;
29
+ }
30
+ }
31
+ function setAliasIfPresent(alias, name, value) {
32
+ if (value) alias.set(name, value);
33
+ }
34
+ function getEffectBffEntry(normalizedConfig, appContext) {
35
+ if (!normalizedConfig.bff || 'hono' === normalizedConfig.bff.runtimeFramework) return;
36
+ const configuredEntry = normalizedConfig.bff.effect?.entry;
37
+ const entryWithoutExtension = configuredEntry ? node_path.isAbsolute(configuredEntry) ? configuredEntry : node_path.resolve(appContext.appDirectory, configuredEntry) : node_path.resolve(appContext.apiDirectory, 'effect', 'index');
38
+ return findExistingFile(JS_OR_TS_EXTS.map((extension)=>`${entryWithoutExtension}${extension}`));
39
+ }
4
40
  function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig) {
5
41
  const entries = {};
6
42
  const { entrypoints = [], checkedEntries } = appContext;
@@ -17,6 +53,11 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
17
53
  const v = entries[entry];
18
54
  serverEntries[entry] = v.map((entry)=>entry.replace('index.jsx', 'index.server.jsx')).map((entry)=>entry.replace('bootstrap.jsx', 'bootstrap.server.jsx'));
19
55
  }
56
+ const cloudflareWorkerServerEntries = {};
57
+ for(const entry in entries){
58
+ const v = entries[entry];
59
+ cloudflareWorkerServerEntries[entry] = v.map((entry)=>entry.replace('index.jsx', 'index.server.jsx')).map((entry)=>entry.replace('bootstrap.jsx', 'index.server.jsx'));
60
+ }
20
61
  const environments = {
21
62
  client: {
22
63
  output: {
@@ -41,14 +82,101 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
41
82
  }
42
83
  };
43
84
  const useWorkerTarget = isServiceWorker(normalizedConfig);
44
- if (useWorkerTarget) environments[SERVICE_WORKER_ENVIRONMENT_NAME] = {
45
- output: {
46
- target: 'web-worker'
47
- },
48
- source: {
49
- entry: serverEntries
50
- }
51
- };
85
+ if (useWorkerTarget) {
86
+ const useCloudflareModuleWorker = normalizedConfig.deploy?.target === 'cloudflare';
87
+ const effectBffEntry = useCloudflareModuleWorker ? getEffectBffEntry(normalizedConfig, appContext) : void 0;
88
+ const tanstackRouterSsrServerFile = useCloudflareModuleWorker ? resolvePackageFile('@tanstack/router-core', 'dist/esm/ssr/ssr-server.js', [
89
+ appContext.appDirectory,
90
+ process.cwd()
91
+ ]) : void 0;
92
+ const runtimeRscWorkerFile = useCloudflareModuleWorker ? resolvePackageFile('@modern-js/runtime', 'dist/esm/rsc/server.worker.mjs', [
93
+ appContext.appDirectory,
94
+ process.cwd()
95
+ ]) : void 0;
96
+ const renderRscWorkerFile = useCloudflareModuleWorker ? resolvePackageFile('@modern-js/render', 'dist/esm/rscWorker.mjs', [
97
+ appContext.appDirectory,
98
+ process.cwd()
99
+ ]) : void 0;
100
+ const reactFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'index.js', [
101
+ appContext.appDirectory,
102
+ process.cwd()
103
+ ]) : void 0;
104
+ const reactJsxRuntimeFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'jsx-runtime.js', [
105
+ appContext.appDirectory,
106
+ process.cwd()
107
+ ]) : void 0;
108
+ const reactJsxDevRuntimeFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'jsx-dev-runtime.js', [
109
+ appContext.appDirectory,
110
+ process.cwd()
111
+ ]) : void 0;
112
+ const reactDomFile = useCloudflareModuleWorker ? resolvePackageFile('react-dom', 'index.js', [
113
+ appContext.appDirectory,
114
+ process.cwd()
115
+ ]) : void 0;
116
+ const reactDomServerEdgeFile = useCloudflareModuleWorker ? resolvePackageFile('react-dom', 'server.edge.js', [
117
+ appContext.appDirectory,
118
+ process.cwd()
119
+ ]) : void 0;
120
+ const baseWorkerEntries = useCloudflareModuleWorker ? cloudflareWorkerServerEntries : serverEntries;
121
+ const workerEntries = effectBffEntry ? {
122
+ ...baseWorkerEntries,
123
+ [BFF_EFFECT_WORKER_ENTRY_NAME]: [
124
+ `${effectBffEntry}?${BFF_EFFECT_WORKER_RUNTIME_QUERY}`
125
+ ]
126
+ } : baseWorkerEntries;
127
+ environments[SERVICE_WORKER_ENVIRONMENT_NAME] = {
128
+ output: {
129
+ target: useCloudflareModuleWorker ? 'web' : 'web-worker',
130
+ ...useCloudflareModuleWorker ? {
131
+ module: true
132
+ } : {}
133
+ },
134
+ source: {
135
+ entry: workerEntries
136
+ },
137
+ tools: {
138
+ htmlPlugin: false,
139
+ ...useCloudflareModuleWorker ? {
140
+ bundlerChain: (chain)=>{
141
+ chain.merge({
142
+ experiments: {
143
+ outputModule: true
144
+ }
145
+ });
146
+ chain.externalsPresets({
147
+ node: true
148
+ });
149
+ chain.target('webworker');
150
+ chain.plugins.delete('plugin-module-federation');
151
+ if (tanstackRouterSsrServerFile) {
152
+ chain.resolve.alias.set('@tanstack/router-core/ssr/server$', tanstackRouterSsrServerFile);
153
+ chain.resolve.alias.set('@tanstack/router-core/ssr/server', tanstackRouterSsrServerFile);
154
+ }
155
+ if (runtimeRscWorkerFile) {
156
+ chain.resolve.alias.set('@modern-js/runtime/rsc/server$', runtimeRscWorkerFile);
157
+ chain.resolve.alias.set('@modern-js/runtime/rsc/server', runtimeRscWorkerFile);
158
+ }
159
+ if (renderRscWorkerFile) {
160
+ chain.resolve.alias.set('@modern-js/render/rsc$', renderRscWorkerFile);
161
+ chain.resolve.alias.set('@modern-js/render/rsc', renderRscWorkerFile);
162
+ chain.resolve.alias.set('@modern-js/render/rsc-worker$', renderRscWorkerFile);
163
+ }
164
+ setAliasIfPresent(chain.resolve.alias, 'react$', reactFile);
165
+ setAliasIfPresent(chain.resolve.alias, 'react/jsx-runtime$', reactJsxRuntimeFile);
166
+ setAliasIfPresent(chain.resolve.alias, 'react/jsx-dev-runtime$', reactJsxDevRuntimeFile);
167
+ setAliasIfPresent(chain.resolve.alias, 'react-dom$', reactDomFile);
168
+ setAliasIfPresent(chain.resolve.alias, 'react-dom/server.edge$', reactDomServerEdgeFile);
169
+ chain.resolve.alias.set('react-server-dom-rspack/server.node$', 'react-server-dom-rspack/server.edge');
170
+ chain.resolve.alias.set('react-server-dom-rspack/server.node', 'react-server-dom-rspack/server.edge');
171
+ chain.resolve.alias.set('react-server-dom-rspack/client.node$', 'react-server-dom-rspack/client.edge');
172
+ chain.resolve.alias.set('react-server-dom-rspack/client.node', 'react-server-dom-rspack/client.edge');
173
+ chain.resolve.fallback.set('async_hooks', false);
174
+ chain.resolve.fallback.set('node:async_hooks', false);
175
+ }
176
+ } : {}
177
+ }
178
+ };
179
+ }
52
180
  return {
53
181
  environments,
54
182
  builderConfig: tempBuilderConfig
@@ -9,8 +9,11 @@ const builderPluginAdapterBasic = (options)=>({
9
9
  setup (api) {
10
10
  api.modifyBundlerChain((chain, { target, CHAIN_ID, environment })=>{
11
11
  const isServiceWorker = environment.name === SERVICE_WORKER_ENVIRONMENT_NAME;
12
- if ('node' === target || isServiceWorker) applyNodeCompat(isServiceWorker, chain);
13
- if ('web' === target) {
12
+ const isWebTargetServiceWorker = isServiceWorker && 'web' === target;
13
+ if ('node' === target || isServiceWorker) applyNodeCompat(isServiceWorker, chain, {
14
+ includeNodeExtensions: !isWebTargetServiceWorker
15
+ });
16
+ if ('web' === target && !isServiceWorker) {
14
17
  const bareServerModuleReg = /\.(server|node)\.[tj]sx?$/;
15
18
  const depExt = 'mjs';
16
19
  chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(bareServerModuleReg);
@@ -26,8 +29,40 @@ const builderPluginAdapterBasic = (options)=>({
26
29
  });
27
30
  api.modifyRspackConfig((config, { target, environment })=>{
28
31
  const isServiceWorker = environment.name === SERVICE_WORKER_ENVIRONMENT_NAME;
32
+ const isWebTargetServiceWorker = isServiceWorker && 'web' === target;
29
33
  if ('node' === target || isServiceWorker) {
30
- const extensionAlias = {
34
+ const extensionAlias = isWebTargetServiceWorker ? {
35
+ '.js': [
36
+ '.worker.js',
37
+ '.server.js',
38
+ '.js'
39
+ ],
40
+ '.jsx': [
41
+ '.worker.jsx',
42
+ '.server.jsx',
43
+ '.jsx'
44
+ ],
45
+ '.ts': [
46
+ '.worker.ts',
47
+ '.server.ts',
48
+ '.ts'
49
+ ],
50
+ '.tsx': [
51
+ '.worker.tsx',
52
+ '.server.tsx',
53
+ '.tsx'
54
+ ],
55
+ '.mjs': [
56
+ '.worker.mjs',
57
+ '.server.mjs',
58
+ '.mjs'
59
+ ],
60
+ '.json': [
61
+ '.worker.json',
62
+ '.server.json',
63
+ '.json'
64
+ ]
65
+ } : {
31
66
  '.js': [
32
67
  '.node.js',
33
68
  '.server.js',
@@ -68,7 +103,8 @@ const builderPluginAdapterBasic = (options)=>({
68
103
  });
69
104
  }
70
105
  });
71
- function applyNodeCompat(isServiceWorker, chain) {
106
+ function applyNodeCompat(isServiceWorker, chain, options = {}) {
107
+ const { includeNodeExtensions = true } = options;
72
108
  const nodeExts = [
73
109
  '.node.js',
74
110
  '.node.jsx',
@@ -87,7 +123,7 @@ function applyNodeCompat(isServiceWorker, chain) {
87
123
  '.worker.ts',
88
124
  '.worker.tsx'
89
125
  ];
90
- for (const ext of nodeExts)chain.resolve.extensions.prepend(ext);
126
+ if (includeNodeExtensions) for (const ext of nodeExts)chain.resolve.extensions.prepend(ext);
91
127
  if (isServiceWorker) for (const ext of webWorkerExts)chain.resolve.extensions.prepend(ext);
92
128
  }
93
129
  export { builderPluginAdapterBasic };