@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.10 → 3.2.0-ultramodern.101

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 (44) hide show
  1. package/bin/modern.js +0 -0
  2. package/dist/cjs/baseline.js +43 -1
  3. package/dist/cjs/builder/generator/getBuilderEnvironments.js +191 -8
  4. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +41 -5
  5. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +3 -1
  6. package/dist/cjs/plugins/deploy/index.js +17 -6
  7. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +222 -0
  8. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +457 -0
  9. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  10. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  11. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  12. package/dist/cjs/rsbuild.js +3 -0
  13. package/dist/esm/baseline.mjs +33 -1
  14. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +180 -8
  15. package/dist/esm/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  16. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  17. package/dist/esm/plugins/deploy/index.mjs +10 -4
  18. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +178 -0
  19. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +457 -0
  20. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  21. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  22. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  23. package/dist/esm/rsbuild.mjs +5 -2
  24. package/dist/esm-node/baseline.mjs +33 -1
  25. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +185 -9
  26. package/dist/esm-node/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  27. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  28. package/dist/esm-node/plugins/deploy/index.mjs +10 -4
  29. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +179 -0
  30. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +457 -0
  31. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  32. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  33. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  34. package/dist/esm-node/rsbuild.mjs +5 -2
  35. package/dist/types/locale/en.d.ts +1 -1
  36. package/dist/types/locale/zh.d.ts +1 -1
  37. package/dist/types/plugins/deploy/index.d.ts +4 -1
  38. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +2 -0
  39. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +4 -0
  40. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.d.mts +5 -0
  41. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.d.mts +48 -0
  42. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-path.d.mts +21 -0
  43. package/dist/types/types/config/deploy.d.ts +8 -0
  44. package/package.json +18 -17
@@ -1,5 +1,6 @@
1
1
  import "node:module";
2
2
  import { provider } from "std-env";
3
+ import { createCloudflarePreset } from "./platforms/cloudflare.mjs";
3
4
  import { createGhPagesPreset } from "./platforms/gh-pages.mjs";
4
5
  import { createNetlifyPreset } from "./platforms/netlify.mjs";
5
6
  import { createNodePreset } from "./platforms/node.mjs";
@@ -9,14 +10,18 @@ const deployPresets = {
9
10
  node: createNodePreset,
10
11
  vercel: createVercelPreset,
11
12
  netlify: createNetlifyPreset,
12
- ghPages: createGhPagesPreset
13
+ ghPages: createGhPagesPreset,
14
+ cloudflare: createCloudflarePreset
13
15
  };
16
+ const getSupportedDeployTargets = ()=>Object.keys(deployPresets);
17
+ const isDeployTarget = (target)=>Object.prototype.hasOwnProperty.call(deployPresets, target);
18
+ const resolveDeployTarget = (modernConfig, envDeployTarget = process.env.MODERNJS_DEPLOY, detectedProvider = provider)=>modernConfig.deploy?.target || envDeployTarget || detectedProvider || 'node';
14
19
  async function getDeployPreset(appContext, modernConfig, deployTarget, api) {
15
20
  const { appDirectory, distDirectory, metaName } = appContext;
16
21
  const { useSSR, useAPI, useWebServer } = getProjectUsage(appDirectory, distDirectory, metaName);
17
22
  const needModernServer = useSSR || useAPI || useWebServer;
23
+ if (!isDeployTarget(deployTarget)) throw new Error(`Unknown deploy target: '${deployTarget}'. deploy.target or MODERNJS_DEPLOY should be one of: ${getSupportedDeployTargets().join(', ')}.`);
18
24
  const createPreset = deployPresets[deployTarget];
19
- if (!createPreset) throw new Error(`Unknown deploy target: '${deployTarget}'. MODERNJS_DEPLOY should be 'node', 'vercel', or 'netlify'.`);
20
25
  return createPreset({
21
26
  appContext,
22
27
  modernConfig,
@@ -27,12 +32,12 @@ async function getDeployPreset(appContext, modernConfig, deployTarget, api) {
27
32
  const deploy = ()=>({
28
33
  name: '@modern-js/plugin-deploy',
29
34
  setup: (api)=>{
30
- const deployTarget = process.env.MODERNJS_DEPLOY || provider || 'node';
31
35
  api.deploy(async ()=>{
32
36
  const appContext = api.getAppContext();
33
37
  const { metaName } = appContext;
34
- if ('modern-js' !== metaName && !process.env.MODERNJS_DEPLOY) return;
35
38
  const modernConfig = api.getNormalizedConfig();
39
+ const deployTarget = resolveDeployTarget(modernConfig);
40
+ if ('modern-js' !== metaName && !modernConfig.deploy?.target && !process.env.MODERNJS_DEPLOY) return;
36
41
  const deployPreset = await getDeployPreset(appContext, modernConfig, deployTarget, api);
37
42
  deployPreset?.prepare && await deployPreset?.prepare();
38
43
  deployPreset?.writeOutput && await deployPreset?.writeOutput();
@@ -42,3 +47,4 @@ const deploy = ()=>({
42
47
  }
43
48
  });
44
49
  export default deploy;
50
+ export { getSupportedDeployTargets, resolveDeployTarget };
@@ -0,0 +1,179 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { fs } from "@modern-js/utils";
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 ASSETS_BINDING = 'ASSETS';
8
+ const ROUTE_SPEC_FILE = 'route.json';
9
+ const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
10
+ const LOADABLE_STATS_FILE = 'loadable-stats.json';
11
+ const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
12
+ const PUBLIC_ASSETS_DIRECTORY = 'public';
13
+ const WORKER_BUNDLE_DIRECTORY = 'worker';
14
+ const SERVER_BUNDLE_DIRECTORY = 'bundles';
15
+ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
16
+ const getCompatibilityDate = ()=>new Date().toISOString().slice(0, 10);
17
+ const getWorkerName = (appDirectory)=>{
18
+ const basename = node_path.basename(appDirectory);
19
+ return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
20
+ };
21
+ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
22
+ const configuredName = modernConfig.deploy?.worker?.name?.trim();
23
+ return configuredName || getWorkerName(appDirectory);
24
+ };
25
+ const readRouteSpec = async (outputDirectory)=>{
26
+ const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
27
+ if (!await fs.pathExists(routeSpecPath)) return {
28
+ routes: []
29
+ };
30
+ const routeSpec = await fs.readJSON(routeSpecPath);
31
+ return {
32
+ ...routeSpec,
33
+ routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
34
+ };
35
+ };
36
+ const createWorkerManifest = async (outputDirectory, modernConfig)=>{
37
+ const routeSpec = await readRouteSpec(outputDirectory);
38
+ const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
39
+ const worker = 'string' == typeof route.worker ? route.worker : void 0;
40
+ return {
41
+ urlPath: route.urlPath,
42
+ entryName: route.entryName,
43
+ entryPath: route.entryPath,
44
+ isSSR: Boolean(route.isSSR),
45
+ worker,
46
+ workerExists: worker ? await fs.pathExists(node_path.join(outputDirectory, worker)) : false
47
+ };
48
+ }));
49
+ const bffPrefix = modernConfig.bff?.prefix;
50
+ const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
51
+ const isEffectBff = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
52
+ const effectBffWorkerExists = await fs.pathExists(node_path.join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
53
+ return {
54
+ version: 1,
55
+ runtime: {
56
+ type: 'cloudflare-module-worker',
57
+ entry: WORKER_ENTRY,
58
+ fetchExport: true,
59
+ nodeListen: false
60
+ },
61
+ assets: {
62
+ binding: ASSETS_BINDING,
63
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
64
+ runWorkerFirst: true
65
+ },
66
+ routeSpec: {
67
+ file: ROUTE_SPEC_OUTPUT,
68
+ routes
69
+ },
70
+ workerBundles: {
71
+ directory: WORKER_BUNDLE_DIRECTORY,
72
+ format: 'commonjs',
73
+ importableFromModuleWorker: true,
74
+ requestHandlerExport: 'requestHandler'
75
+ },
76
+ resources: {
77
+ loadableStats: LOADABLE_STATS_FILE,
78
+ routeManifest: ROUTE_MANIFEST_FILE
79
+ },
80
+ bff: isEffectBff && primaryBffPrefix && effectBffWorkerExists ? {
81
+ runtimeFramework: 'effect',
82
+ prefix: primaryBffPrefix,
83
+ worker: BFF_EFFECT_WORKER_ENTRY
84
+ } : void 0
85
+ };
86
+ };
87
+ const createWorkerModuleLoaders = (manifest)=>{
88
+ const imports = new Map();
89
+ for (const route of manifest.routeSpec.routes)if (route.worker && route.workerExists) {
90
+ const importPath = `../${String(route.worker).replace(/^\/+/u, '')}`;
91
+ imports.set(route.worker, `() => import(${JSON.stringify(importPath)})`);
92
+ }
93
+ if (manifest.bff?.worker) {
94
+ const importPath = `../${String(manifest.bff.worker).replace(/^\/+/u, '')}`;
95
+ imports.set(manifest.bff.worker, `() => import(${JSON.stringify(importPath)})`);
96
+ }
97
+ if (0 === imports.size) return '{}';
98
+ const loaders = [
99
+ ...imports.entries()
100
+ ].map(([worker, loader])=>`${JSON.stringify(worker)}: ${loader}`);
101
+ return `{\n${loaders.join(',\n')}\n}`;
102
+ };
103
+ const shouldCopyToPublicAssets = (src, distDirectory)=>{
104
+ const relativePath = node_path.relative(distDirectory, src);
105
+ if (!relativePath) return true;
106
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
107
+ const [topLevelDirectory] = normalizedRelativePath.split('/');
108
+ return normalizedRelativePath !== ROUTE_SPEC_FILE && topLevelDirectory !== WORKER_BUNDLE_DIRECTORY && topLevelDirectory !== SERVER_BUNDLE_DIRECTORY;
109
+ };
110
+ const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
111
+ const relativePath = node_path.relative(workerBundleDirectory, src);
112
+ if (!relativePath) return true;
113
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
114
+ const basename = node_path.basename(normalizedRelativePath);
115
+ if (basename.startsWith('.') || normalizedRelativePath.includes('/.')) return false;
116
+ if (fs.statSync(src).isDirectory()) return true;
117
+ return [
118
+ '.cjs',
119
+ '.js',
120
+ '.mjs'
121
+ ].includes(node_path.extname(normalizedRelativePath));
122
+ };
123
+ const createCloudflarePreset = ({ appContext, modernConfig })=>{
124
+ const { appDirectory, distDirectory } = appContext;
125
+ const outputDirectory = node_path.join(appDirectory, '.output');
126
+ const publicDirectory = node_path.join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
127
+ const workerEntryPath = node_path.join(outputDirectory, WORKER_ENTRY);
128
+ const workerManifestPath = node_path.join(outputDirectory, WORKER_MANIFEST);
129
+ const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
130
+ const wranglerConfigPath = node_path.join(outputDirectory, 'wrangler.json');
131
+ const workerName = getConfiguredWorkerName(appDirectory, modernConfig);
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
+ await fs.writeJSON(wranglerConfigPath, {
149
+ $schema: 'node_modules/wrangler/config-schema.json',
150
+ name: workerName,
151
+ main: WORKER_ENTRY,
152
+ compatibility_date: getCompatibilityDate(),
153
+ compatibility_flags: [
154
+ 'nodejs_compat',
155
+ 'global_fetch_strictly_public'
156
+ ],
157
+ assets: {
158
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
159
+ binding: ASSETS_BINDING,
160
+ run_worker_first: true
161
+ }
162
+ }, {
163
+ spaces: 2
164
+ });
165
+ await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig), {
166
+ spaces: 2
167
+ });
168
+ await fs.writeJSON(node_path.join(outputDirectory, 'package.json'), {
169
+ type: 'commonjs'
170
+ });
171
+ },
172
+ async genEntry () {
173
+ const template = await readTemplate('cloudflare-entry.mjs');
174
+ const manifest = await fs.readJSON(workerManifestPath);
175
+ await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
176
+ }
177
+ };
178
+ };
179
+ export { createCloudflarePreset };
@@ -0,0 +1,457 @@
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
+ const remoteJsonPromises = new Map();
6
+ const CORS_HEADERS = {
7
+ 'access-control-allow-headers': '*',
8
+ 'access-control-allow-methods': 'GET, HEAD, OPTIONS',
9
+ 'access-control-allow-origin': '*'
10
+ };
11
+ globalThis.__dirname ??= '/';
12
+ globalThis.__filename ??= '/index.js';
13
+ function withCorsHeaders(response) {
14
+ const headers = new Headers(response.headers);
15
+ for (const [name, value] of Object.entries(CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
16
+ return new Response(response.body, {
17
+ headers,
18
+ status: response.status,
19
+ statusText: response.statusText
20
+ });
21
+ }
22
+ function createRenderableRequest(request) {
23
+ if ('HEAD' !== request.method) return request;
24
+ return new Request(request, {
25
+ method: 'GET'
26
+ });
27
+ }
28
+ function finalizeResponseForRequest(response, request) {
29
+ if ('HEAD' !== request.method) return response;
30
+ const headers = new Headers(response.headers);
31
+ headers.delete('content-length');
32
+ return new Response(null, {
33
+ headers,
34
+ status: response.status,
35
+ statusText: response.statusText
36
+ });
37
+ }
38
+ function isFingerprintedAssetPathname(pathname) {
39
+ return /(?:^|\/)[^/]+\.[a-f0-9]{8,}\.(?:css|js|mjs|json|svg|png|jpe?g|webp|avif|gif|woff2?|ttf)$/iu.test(pathname);
40
+ }
41
+ function withAssetHeaders(response, request) {
42
+ const corsResponse = withCorsHeaders(response);
43
+ const headers = new Headers(corsResponse.headers);
44
+ const { pathname } = new URL(request.url);
45
+ if (isFingerprintedAssetPathname(pathname)) headers.set('cache-control', 'public, max-age=31536000, immutable');
46
+ return new Response(corsResponse.body, {
47
+ headers,
48
+ status: corsResponse.status,
49
+ statusText: corsResponse.statusText
50
+ });
51
+ }
52
+ function createCorsPreflightResponse(request) {
53
+ if ('OPTIONS' !== request.method) return null;
54
+ return new Response(null, {
55
+ headers: CORS_HEADERS,
56
+ status: 204
57
+ });
58
+ }
59
+ async function fetchAsset(request, env) {
60
+ const assets = env?.[ASSETS_BINDING];
61
+ if (!assets || 'function' != typeof assets.fetch) return null;
62
+ const response = await assets.fetch(request);
63
+ if (404 === response.status) return null;
64
+ return withAssetHeaders(response, request);
65
+ }
66
+ async function fetchAssetByPath(pathname, request, env) {
67
+ const url = new URL(request.url);
68
+ url.pathname = `/${pathname.replace(/^\/+/u, '')}`;
69
+ return fetchAsset(new Request(url, request), env);
70
+ }
71
+ async function fetchAssetByPathFollowingRedirects(pathname, request, env, visited = new Set()) {
72
+ const normalizedPathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
73
+ if (visited.has(normalizedPathname)) return null;
74
+ visited.add(normalizedPathname);
75
+ const response = await fetchAssetByPath(normalizedPathname, request, env);
76
+ if (response && response.status >= 300 && response.status < 400 && response.headers.has('location')) {
77
+ const location = response.headers.get('location');
78
+ if (location) {
79
+ const nextUrl = new URL(location, request.url);
80
+ const currentUrl = new URL(request.url);
81
+ if (nextUrl.origin === currentUrl.origin) return fetchAssetByPathFollowingRedirects(nextUrl.pathname, request, env, visited);
82
+ }
83
+ }
84
+ return response;
85
+ }
86
+ async function readAssetText(pathname, request, env) {
87
+ const response = await fetchAssetByPathFollowingRedirects(pathname, request, env);
88
+ if (!response || !response.ok) return;
89
+ return response.text();
90
+ }
91
+ async function readAssetJson(pathname, request, env) {
92
+ const text = await readAssetText(pathname, request, env);
93
+ if (!text) return {};
94
+ return JSON.parse(text);
95
+ }
96
+ function normalizeRoutePath(pathname) {
97
+ if ('/' === pathname) return pathname;
98
+ return pathname.replace(/\/+$/u, '');
99
+ }
100
+ function getPathExtension(pathname) {
101
+ const lastSegment = pathname.split('/').pop() || '';
102
+ const dotIndex = lastSegment.lastIndexOf('.');
103
+ if (dotIndex <= 0 || dotIndex === lastSegment.length - 1) return '';
104
+ return lastSegment.slice(dotIndex).toLowerCase();
105
+ }
106
+ function isAssetLikePathname(pathname) {
107
+ const extension = getPathExtension(pathname);
108
+ return '' !== extension && '.html' !== extension && '.htm' !== extension;
109
+ }
110
+ function routeMatchesExactly(route, pathname) {
111
+ if ('string' != typeof route?.urlPath) return false;
112
+ return normalizeRoutePath(route.urlPath) === normalizeRoutePath(pathname);
113
+ }
114
+ function routeMatches(route, pathname) {
115
+ if ('string' != typeof route.urlPath) return false;
116
+ const routePath = normalizeRoutePath(route.urlPath);
117
+ const requestPath = normalizeRoutePath(pathname);
118
+ return routePath === requestPath || '/' === routePath && route.isSSR || requestPath.startsWith(`${routePath}/`);
119
+ }
120
+ function findRoute(request) {
121
+ const { pathname } = new URL(request.url);
122
+ const routes = MODERN_WORKER_MANIFEST.routeSpec.routes;
123
+ return [
124
+ ...routes
125
+ ].sort((left, right)=>{
126
+ const leftLength = left.urlPath?.length || 0;
127
+ const rightLength = right.urlPath?.length || 0;
128
+ return rightLength - leftLength;
129
+ }).find((route)=>routeMatches(route, pathname));
130
+ }
131
+ async function fetchRouteHtml(route, request, env) {
132
+ if (!route?.entryPath) return null;
133
+ return fetchAssetByPath(route.entryPath, request, env);
134
+ }
135
+ function createNoopMonitors() {
136
+ const noop = ()=>{};
137
+ return {
138
+ debug: noop,
139
+ error: noop,
140
+ info: noop,
141
+ warn: noop
142
+ };
143
+ }
144
+ function createRequestHandlerOptions({ route, htmlTemplate, routeManifest, loadableStats }) {
145
+ const monitors = createNoopMonitors();
146
+ return {
147
+ resource: {
148
+ route,
149
+ routeManifest,
150
+ loadableStats,
151
+ htmlTemplate,
152
+ entryName: route.entryName
153
+ },
154
+ params: {},
155
+ loaderContext: {},
156
+ config: {},
157
+ locals: {},
158
+ staticGenerate: false,
159
+ monitors,
160
+ onError (error) {
161
+ monitors.error(error);
162
+ },
163
+ onTiming () {},
164
+ reporter: {
165
+ reportTiming: ()=>{}
166
+ }
167
+ };
168
+ }
169
+ function collectRouteCssAssets(route, routeManifest) {
170
+ const routeAssets = routeManifest?.routeAssets || {};
171
+ const candidateKeys = [
172
+ route.entryName,
173
+ `async-${route.entryName}`
174
+ ].filter(Boolean);
175
+ const assets = new Set();
176
+ for (const key of candidateKeys){
177
+ const routeAsset = routeAssets[key];
178
+ const cssAssets = [
179
+ ...Array.isArray(routeAsset?.referenceCssAssets) ? routeAsset.referenceCssAssets : [],
180
+ ...Array.isArray(routeAsset?.assets) ? routeAsset.assets : []
181
+ ];
182
+ for (const asset of cssAssets)if ('string' == typeof asset && asset.endsWith('.css')) assets.add(asset);
183
+ }
184
+ return [
185
+ ...assets
186
+ ];
187
+ }
188
+ function collectRenderedFederatedExposes(html) {
189
+ const renderedExposes = [];
190
+ const tagPattern = /<[^>]*data-modern-(?:boundary-id|mf-expose)=["'][^"']+["'][^>]*>/g;
191
+ const attributePattern = /\s(data-modern-(?:boundary-id|mf-expose))=["']([^"']+)["']/g;
192
+ for (const [tag] of html.matchAll(tagPattern)){
193
+ const attributes = {};
194
+ for (const [, name, value] of tag.matchAll(attributePattern))attributes[name] = value;
195
+ const boundaryId = attributes['data-modern-boundary-id'];
196
+ const expose = attributes['data-modern-mf-expose'];
197
+ if (boundaryId && expose) renderedExposes.push({
198
+ boundaryId,
199
+ expose
200
+ });
201
+ }
202
+ return renderedExposes;
203
+ }
204
+ function getRemoteManifestUrl(remote, request) {
205
+ const entry = remote?.entry;
206
+ if ('string' != typeof entry || 0 === entry.length) return;
207
+ return new URL(entry, request.url).toString();
208
+ }
209
+ async function fetchRemoteJson(jsonUrl) {
210
+ if (!remoteJsonPromises.has(jsonUrl)) remoteJsonPromises.set(jsonUrl, fetch(jsonUrl).then((response)=>{
211
+ if (!response.ok) {
212
+ remoteJsonPromises.delete(jsonUrl);
213
+ return {};
214
+ }
215
+ return response.json().catch(()=>{
216
+ remoteJsonPromises.delete(jsonUrl);
217
+ return {};
218
+ });
219
+ }).catch(()=>{
220
+ remoteJsonPromises.delete(jsonUrl);
221
+ return {};
222
+ }));
223
+ return remoteJsonPromises.get(jsonUrl);
224
+ }
225
+ function findRemoteExpose(remoteManifest, exposePath) {
226
+ const exposes = Array.isArray(remoteManifest?.exposes) ? remoteManifest.exposes : [];
227
+ const normalizedExpose = exposePath.replace(/^\.\//u, '');
228
+ return exposes.find((expose)=>{
229
+ if (!expose || 'object' != typeof expose) return false;
230
+ return expose.path === exposePath || expose.path === `./${normalizedExpose}` || expose.name === normalizedExpose;
231
+ });
232
+ }
233
+ function collectCssAssetEntries(assets) {
234
+ const cssAssets = assets?.css;
235
+ return [
236
+ ...Array.isArray(cssAssets?.sync) ? cssAssets.sync : [],
237
+ ...Array.isArray(cssAssets?.async) ? cssAssets.async : []
238
+ ].filter((asset)=>'string' == typeof asset && asset.endsWith('.css'));
239
+ }
240
+ function collectRouteManifestCssAssets(routeManifest) {
241
+ const routeAssets = routeManifest?.routeAssets || {};
242
+ const assets = new Set();
243
+ for (const routeAsset of Object.values(routeAssets)){
244
+ const cssAssets = [
245
+ ...Array.isArray(routeAsset?.referenceCssAssets) ? routeAsset.referenceCssAssets : [],
246
+ ...Array.isArray(routeAsset?.assets) ? routeAsset.assets : []
247
+ ];
248
+ for (const asset of cssAssets)if ('string' == typeof asset && asset.endsWith('.css')) assets.add(asset);
249
+ }
250
+ return [
251
+ ...assets
252
+ ];
253
+ }
254
+ async function collectRenderedRemoteCssHrefs(html, request, env) {
255
+ const renderedExposes = collectRenderedFederatedExposes(html);
256
+ if (0 === renderedExposes.length) return [];
257
+ const hostManifest = await readAssetJson('mf-manifest.json', request, env);
258
+ const remotes = Array.isArray(hostManifest?.remotes) ? hostManifest.remotes : [];
259
+ const remoteByBoundary = new Map();
260
+ const hrefs = new Set();
261
+ for (const remote of remotes){
262
+ if ('string' == typeof remote?.alias) remoteByBoundary.set(remote.alias, remote);
263
+ if ('string' == typeof remote?.federationContainerName) remoteByBoundary.set(remote.federationContainerName, remote);
264
+ }
265
+ await Promise.all(renderedExposes.map(async ({ boundaryId, expose })=>{
266
+ const remote = remoteByBoundary.get(boundaryId);
267
+ const manifestUrl = remote ? getRemoteManifestUrl(remote, request) : void 0;
268
+ if (!manifestUrl) return;
269
+ const remoteManifest = await fetchRemoteJson(manifestUrl);
270
+ const remoteExpose = findRemoteExpose(remoteManifest, expose);
271
+ const publicPath = 'string' == typeof remoteManifest?.metaData?.publicPath ? remoteManifest.metaData.publicPath : manifestUrl;
272
+ const remoteRouteManifest = await fetchRemoteJson(new URL('routes-manifest.json', publicPath).toString());
273
+ for (const asset of collectCssAssetEntries(remoteExpose?.assets))hrefs.add(new URL(asset, publicPath).toString());
274
+ for (const asset of collectRouteManifestCssAssets(remoteRouteManifest))hrefs.add(new URL(asset, publicPath).toString());
275
+ }));
276
+ return [
277
+ ...hrefs
278
+ ];
279
+ }
280
+ function escapeAttribute(value) {
281
+ return String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
282
+ }
283
+ async function withRouteCssLinks(response, route, routeManifest, request, env) {
284
+ const contentType = response.headers.get('content-type') || '';
285
+ if (!contentType.includes('text/html')) return response;
286
+ const html = await response.text();
287
+ const cssHrefs = [
288
+ ...collectRouteCssAssets(route, routeManifest).map((asset)=>new URL(asset, request.url).toString()),
289
+ ...await collectRenderedRemoteCssHrefs(html, request, env)
290
+ ];
291
+ if (0 === cssHrefs.length) return response;
292
+ const uniqueCssHrefs = [
293
+ ...new Set(cssHrefs)
294
+ ];
295
+ const headers = new Headers(response.headers);
296
+ for (const href of uniqueCssHrefs)headers.append('link', `<${href}>; rel=preload; as=style`);
297
+ const links = uniqueCssHrefs.filter((href)=>!html.includes(href)).map((href)=>`<link rel="stylesheet" href="${escapeAttribute(href)}">`);
298
+ if (0 === links.length || !html.includes('</head>')) return new Response(html, {
299
+ headers,
300
+ status: response.status,
301
+ statusText: response.statusText
302
+ });
303
+ return new Response(html.replace('</head>', `${links.join('')}</head>`), {
304
+ headers,
305
+ status: response.status,
306
+ statusText: response.statusText
307
+ });
308
+ }
309
+ async function getRequestHandlerOptions(route, request, env) {
310
+ const [htmlTemplate, routeManifest, loadableStats] = await Promise.all([
311
+ readAssetText(route.entryPath, request, env),
312
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.routeManifest, request, env),
313
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.loadableStats, request, env)
314
+ ]);
315
+ return createRequestHandlerOptions({
316
+ route,
317
+ htmlTemplate: htmlTemplate || '',
318
+ routeManifest,
319
+ loadableStats
320
+ });
321
+ }
322
+ async function loadWorkerModule(workerPath) {
323
+ const loader = WORKER_MODULE_LOADERS[workerPath];
324
+ if (!loader) return;
325
+ if (!workerModulePromises.has(workerPath)) workerModulePromises.set(workerPath, loader());
326
+ return workerModulePromises.get(workerPath);
327
+ }
328
+ function getRuntimeModule(workerModule) {
329
+ const defaultExport = workerModule.default;
330
+ const nestedDefaultExport = defaultExport && 'object' == typeof defaultExport ? defaultExport.default : void 0;
331
+ return defaultExport && 'object' == typeof defaultExport ? {
332
+ ...workerModule,
333
+ ...defaultExport,
334
+ ...nestedDefaultExport && 'object' == typeof nestedDefaultExport ? nestedDefaultExport : {}
335
+ } : workerModule;
336
+ }
337
+ function getFetchHandler(workerModule) {
338
+ const defaultExport = workerModule.default;
339
+ const runtime = getRuntimeModule(workerModule);
340
+ return 'function' == typeof runtime.fetch && runtime.fetch.bind(runtime) || 'function' == typeof defaultExport && defaultExport.fetch?.bind?.(defaultExport);
341
+ }
342
+ async function getRequestHandler(workerModule) {
343
+ const defaultExport = workerModule.default;
344
+ const runtime = getRuntimeModule(workerModule);
345
+ return await workerModule.requestHandler || await runtime.requestHandler || ('function' == typeof defaultExport ? defaultExport : void 0);
346
+ }
347
+ async function dispatchRouteWorker(route, request, env, ctx) {
348
+ const workerPath = route.worker;
349
+ if (!workerPath) return new Response('Worker bundle not configured for SSR route', {
350
+ status: 500,
351
+ headers: {
352
+ 'content-type': 'text/plain; charset=utf-8'
353
+ }
354
+ });
355
+ const workerModule = await loadWorkerModule(workerPath);
356
+ if (!workerModule) return new Response(`Worker bundle not found: ${workerPath}`, {
357
+ status: 500,
358
+ headers: {
359
+ 'content-type': 'text/plain; charset=utf-8',
360
+ 'x-modern-js-route-worker': workerPath
361
+ }
362
+ });
363
+ const fetchHandler = getFetchHandler(workerModule);
364
+ if (fetchHandler) return fetchHandler(request, env, ctx);
365
+ const requestHandler = await getRequestHandler(workerModule);
366
+ if ('function' == typeof requestHandler) {
367
+ const requestHandlerOptions = await getRequestHandlerOptions(route, request, env);
368
+ return withRouteCssLinks(await requestHandler(request, requestHandlerOptions), route, requestHandlerOptions.resource.routeManifest, request, env);
369
+ }
370
+ return new Response(`Worker bundle has no fetch or requestHandler export: ${workerPath}`, {
371
+ status: 500,
372
+ headers: {
373
+ 'content-type': 'text/plain; charset=utf-8',
374
+ 'x-modern-js-route-worker': workerPath
375
+ }
376
+ });
377
+ }
378
+ function matchesPrefix(pathname, prefix) {
379
+ if (!prefix || '/' === prefix) return true;
380
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
381
+ return pathname === normalized || pathname.startsWith(`${normalized}/`);
382
+ }
383
+ function createRequestForMountedPrefix(request, prefix) {
384
+ if (!prefix || '/' === prefix) return request;
385
+ const url = new URL(request.url);
386
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
387
+ if (!matchesPrefix(url.pathname, normalized)) return request;
388
+ const nextPath = url.pathname.slice(normalized.length) || '/';
389
+ url.pathname = nextPath.startsWith('/') ? nextPath : `/${nextPath}`;
390
+ return new Request(url, request);
391
+ }
392
+ function createEffectContext(originalRequest, mountedRequest, env) {
393
+ const url = new URL(originalRequest.url);
394
+ return {
395
+ request: mountedRequest,
396
+ env: env || {},
397
+ path: url.pathname,
398
+ method: originalRequest.method,
399
+ operationContext: {
400
+ request: mountedRequest,
401
+ env: env || {},
402
+ path: url.pathname,
403
+ method: originalRequest.method
404
+ }
405
+ };
406
+ }
407
+ async function dispatchBffRequest(request, env) {
408
+ const bff = MODERN_WORKER_MANIFEST.bff;
409
+ if (!bff?.worker || !matchesPrefix(new URL(request.url).pathname, bff.prefix)) return null;
410
+ const workerModule = await loadWorkerModule(bff.worker);
411
+ if (!workerModule) return new Response(`BFF worker bundle not found: ${bff.worker}`, {
412
+ status: 500,
413
+ headers: {
414
+ 'content-type': 'text/plain; charset=utf-8',
415
+ 'x-modern-js-bff-worker': bff.worker
416
+ }
417
+ });
418
+ const mountedRequest = createRequestForMountedPrefix(request, bff.prefix);
419
+ const effectContext = createEffectContext(request, mountedRequest, env);
420
+ const defaultExport = workerModule.default;
421
+ const runtime = getRuntimeModule(workerModule);
422
+ const directHandler = 'function' == typeof runtime.handler && runtime.handler || 'function' == typeof defaultExport && defaultExport;
423
+ const createdHandler = 'function' == typeof runtime.createHandler ? runtime.createHandler().handler : void 0;
424
+ const handler = directHandler || createdHandler;
425
+ if ('function' != typeof handler) return new Response(`BFF worker bundle has no handler export: ${bff.worker}`, {
426
+ status: 500,
427
+ headers: {
428
+ 'content-type': 'text/plain; charset=utf-8',
429
+ 'x-modern-js-bff-worker': bff.worker
430
+ }
431
+ });
432
+ return handler.length > 1 ? handler(mountedRequest, effectContext) : handler(mountedRequest);
433
+ }
434
+ export default {
435
+ async fetch (request, env, ctx) {
436
+ const corsPreflightResponse = createCorsPreflightResponse(request);
437
+ if (corsPreflightResponse) return corsPreflightResponse;
438
+ const assetResponse = await fetchAsset(request, env);
439
+ if (assetResponse) return finalizeResponseForRequest(assetResponse, request);
440
+ const bffResponse = await dispatchBffRequest(request, env);
441
+ if (bffResponse) return finalizeResponseForRequest(withCorsHeaders(bffResponse), request);
442
+ const route = findRoute(request);
443
+ const { pathname } = new URL(request.url);
444
+ if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return finalizeResponseForRequest(withCorsHeaders(new Response('Not found', {
445
+ status: 404
446
+ })), request);
447
+ if (route?.worker) {
448
+ const renderableRequest = createRenderableRequest(request);
449
+ return finalizeResponseForRequest(withCorsHeaders(await dispatchRouteWorker(route, renderableRequest, env, ctx)), request);
450
+ }
451
+ const htmlResponse = await fetchRouteHtml(route, request, env);
452
+ if (htmlResponse) return finalizeResponseForRequest(htmlResponse, request);
453
+ return finalizeResponseForRequest(withCorsHeaders(new Response('Not found', {
454
+ status: 404
455
+ })), request);
456
+ }
457
+ };