@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.5 → 3.2.0-ultramodern.50

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 (129) hide show
  1. package/dist/cjs/builder/generator/getBuilderEnvironments.js +143 -8
  2. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +41 -5
  3. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +3 -1
  4. package/dist/cjs/plugins/deploy/index.js +17 -6
  5. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +220 -0
  6. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +258 -0
  7. package/dist/cjs/rsbuild.js +3 -0
  8. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +132 -8
  9. package/dist/esm/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  10. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  11. package/dist/esm/plugins/deploy/index.mjs +10 -4
  12. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +176 -0
  13. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +258 -0
  14. package/dist/esm/rsbuild.mjs +5 -2
  15. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +134 -9
  16. package/dist/esm-node/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  17. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  18. package/dist/esm-node/plugins/deploy/index.mjs +10 -4
  19. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +177 -0
  20. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +258 -0
  21. package/dist/esm-node/rsbuild.mjs +5 -2
  22. package/dist/types/baseline.d.ts +46 -0
  23. package/dist/types/builder/builder-rspack/index.d.ts +2 -0
  24. package/dist/types/builder/generator/adapterCopy.d.ts +3 -0
  25. package/dist/types/builder/generator/createBuilderProviderConfig.d.ts +3 -0
  26. package/dist/types/builder/generator/createCopyPattern.d.ts +16 -0
  27. package/dist/types/builder/generator/getBuilderEnvironments.d.ts +6 -0
  28. package/dist/types/builder/generator/index.d.ts +8 -0
  29. package/dist/types/builder/index.d.ts +3 -0
  30. package/dist/types/builder/shared/builderPlugins/adapterBasic.d.ts +3 -0
  31. package/dist/types/builder/shared/builderPlugins/adapterHtml.d.ts +3 -0
  32. package/dist/types/builder/shared/builderPlugins/adapterPrecompress.d.ts +3 -0
  33. package/dist/types/builder/shared/builderPlugins/adapterSSR.d.ts +3 -0
  34. package/dist/types/builder/shared/builderPlugins/builderHooks.d.ts +3 -0
  35. package/dist/types/builder/shared/builderPlugins/index.d.ts +5 -0
  36. package/dist/types/builder/shared/bundlerPlugins/HtmlAsyncChunkPlugin.d.ts +7 -0
  37. package/dist/types/builder/shared/bundlerPlugins/HtmlBottomTemplate.d.ts +9 -0
  38. package/dist/types/builder/shared/bundlerPlugins/RouterPlugin.d.ts +32 -0
  39. package/dist/types/builder/shared/bundlerPlugins/index.d.ts +3 -0
  40. package/dist/types/builder/shared/createCopyInfo.d.ts +8 -0
  41. package/dist/types/builder/shared/index.d.ts +3 -0
  42. package/dist/types/builder/shared/loaders/serverModuleLoader.d.ts +3 -0
  43. package/dist/types/builder/shared/types.d.ts +6 -0
  44. package/dist/types/commands/build.d.ts +4 -0
  45. package/dist/types/commands/deploy.d.ts +3 -0
  46. package/dist/types/commands/dev.d.ts +9 -0
  47. package/dist/types/commands/index.d.ts +10 -0
  48. package/dist/types/commands/info.d.ts +18 -0
  49. package/dist/types/commands/inspect.d.ts +4 -0
  50. package/dist/types/commands/runtime.d.ts +11 -0
  51. package/dist/types/commands/serve.d.ts +8 -0
  52. package/dist/types/compat/hooks.d.ts +7 -0
  53. package/dist/types/compat/index.d.ts +2 -0
  54. package/dist/types/compat/utils.d.ts +13 -0
  55. package/dist/types/config/default.d.ts +3 -0
  56. package/dist/types/config/index.d.ts +2 -0
  57. package/dist/types/config/initialize/index.d.ts +3 -0
  58. package/dist/types/config/initialize/inits.d.ts +4 -0
  59. package/dist/types/constants.d.ts +2 -0
  60. package/dist/types/defineConfig.d.ts +11 -0
  61. package/dist/types/esm/register-esm.d.mts +5 -0
  62. package/dist/types/esm/ts-paths-loader.d.mts +6 -0
  63. package/dist/types/exports/server.d.ts +1 -0
  64. package/dist/types/index.d.ts +17 -0
  65. package/dist/types/locale/en.d.ts +44 -0
  66. package/dist/types/locale/index.d.ts +3 -0
  67. package/dist/types/locale/zh.d.ts +44 -0
  68. package/dist/types/plugins/analyze/constants.d.ts +3 -0
  69. package/dist/types/plugins/analyze/getBundleEntry.d.ts +4 -0
  70. package/dist/types/plugins/analyze/getFileSystemEntry.d.ts +7 -0
  71. package/dist/types/plugins/analyze/getHtmlTemplate.d.ts +27 -0
  72. package/dist/types/plugins/analyze/getServerRoutes.d.ts +8 -0
  73. package/dist/types/plugins/analyze/index.d.ts +3 -0
  74. package/dist/types/plugins/analyze/isDefaultExportFunction.d.ts +1 -0
  75. package/dist/types/plugins/analyze/templates.d.ts +5 -0
  76. package/dist/types/plugins/analyze/utils.d.ts +10 -0
  77. package/dist/types/plugins/deploy/index.d.ts +6 -0
  78. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +2 -0
  79. package/dist/types/plugins/deploy/platforms/gh-pages.d.ts +2 -0
  80. package/dist/types/plugins/deploy/platforms/netlify.d.ts +2 -0
  81. package/dist/types/plugins/deploy/platforms/node.d.ts +2 -0
  82. package/dist/types/plugins/deploy/platforms/platform.d.ts +17 -0
  83. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +4 -0
  84. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.cts +2 -0
  85. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.mts +2 -0
  86. package/dist/types/plugins/deploy/platforms/templates/node-entry.d.cts +1 -0
  87. package/dist/types/plugins/deploy/platforms/templates/node-entry.d.mts +1 -0
  88. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.cts +2 -0
  89. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.mts +2 -0
  90. package/dist/types/plugins/deploy/platforms/vercel.d.ts +2 -0
  91. package/dist/types/plugins/deploy/types.d.ts +3 -0
  92. package/dist/types/plugins/deploy/utils/generator.d.ts +24 -0
  93. package/dist/types/plugins/deploy/utils/index.d.ts +16 -0
  94. package/dist/types/plugins/initialize/index.d.ts +3 -0
  95. package/dist/types/plugins/serverBuild.d.ts +3 -0
  96. package/dist/types/plugins/serverRuntime.d.ts +3 -0
  97. package/dist/types/presetUltramodern.d.ts +6 -0
  98. package/dist/types/rsbuild.d.ts +12 -0
  99. package/dist/types/run/index.d.ts +20 -0
  100. package/dist/types/types/config/deploy.d.ts +46 -0
  101. package/dist/types/types/config/dev.d.ts +55 -0
  102. package/dist/types/types/config/experiments.d.ts +3 -0
  103. package/dist/types/types/config/html.d.ts +3 -0
  104. package/dist/types/types/config/index.d.ts +48 -0
  105. package/dist/types/types/config/output.d.ts +61 -0
  106. package/dist/types/types/config/performance.d.ts +3 -0
  107. package/dist/types/types/config/resolve.d.ts +2 -0
  108. package/dist/types/types/config/security.d.ts +2 -0
  109. package/dist/types/types/config/source.d.ts +61 -0
  110. package/dist/types/types/config/testing.d.ts +8 -0
  111. package/dist/types/types/config/tools.d.ts +21 -0
  112. package/dist/types/types/index.d.ts +10 -0
  113. package/dist/types/types/plugin.d.ts +114 -0
  114. package/dist/types/types/utils.d.ts +1 -0
  115. package/dist/types/ultramodern/designSystem.d.ts +54 -0
  116. package/dist/types/utils/config.d.ts +2 -0
  117. package/dist/types/utils/createServer.d.ts +5 -0
  118. package/dist/types/utils/env.d.ts +2 -0
  119. package/dist/types/utils/generateWatchFiles.d.ts +2 -0
  120. package/dist/types/utils/getConfigFile.d.ts +1 -0
  121. package/dist/types/utils/getSelectedEntries.d.ts +5 -0
  122. package/dist/types/utils/initAppContext.d.ts +31 -0
  123. package/dist/types/utils/loadPlugins.d.ts +13 -0
  124. package/dist/types/utils/printInstructions.d.ts +3 -0
  125. package/dist/types/utils/register.d.ts +19 -0
  126. package/dist/types/utils/restart.d.ts +2 -0
  127. package/dist/types/utils/routes.d.ts +4 -0
  128. package/dist/types/utils/types.d.ts +49 -0
  129. package/package.json +15 -15
@@ -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 };
@@ -96,9 +96,10 @@ function applyFilterEntriesBySSRConfig({ isProd, chain, appNormalizedConfig }) {
96
96
  });
97
97
  }
98
98
  async function applySSRLoaderEntry(chain, optinos, isServer) {
99
- const { appContext } = optinos;
99
+ const { appContext, normalizedConfig } = optinos;
100
100
  const { internalDirectory } = appContext;
101
101
  const { entrypoints } = appContext;
102
+ const isRsc = isUseRsc(normalizedConfig);
102
103
  await Promise.all(entrypoints.map(async (entrypoint)=>{
103
104
  const { entryName } = entrypoint;
104
105
  const serverLoadersFile = getServerCombinedModuleFile(internalDirectory, entryName);
@@ -106,6 +107,7 @@ async function applySSRLoaderEntry(chain, optinos, isServer) {
106
107
  await fs.access(serverLoadersFile, fs.constants.F_OK);
107
108
  chain.entry(`${entryName}-server-loaders`).add(serverLoadersFile);
108
109
  } catch (err) {}
110
+ else if (isRsc) chain.entry(`${entryName}-server-loaders`).add("data:text/javascript,export%20{};");
109
111
  }));
110
112
  }
111
113
  function applySSRDataLoader(chain, options) {
@@ -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,177 @@
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: 'esm',
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
+ return [
117
+ '.cjs',
118
+ '.js',
119
+ '.mjs'
120
+ ].includes(node_path.extname(normalizedRelativePath));
121
+ };
122
+ const createCloudflarePreset = ({ appContext, modernConfig })=>{
123
+ const { appDirectory, distDirectory } = appContext;
124
+ const outputDirectory = node_path.join(appDirectory, '.output');
125
+ const publicDirectory = node_path.join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
126
+ const workerEntryPath = node_path.join(outputDirectory, WORKER_ENTRY);
127
+ const workerManifestPath = node_path.join(outputDirectory, WORKER_MANIFEST);
128
+ const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
129
+ const wranglerConfigPath = node_path.join(outputDirectory, 'wrangler.json');
130
+ const workerName = getConfiguredWorkerName(appDirectory, modernConfig);
131
+ return {
132
+ async prepare () {
133
+ await fs.remove(outputDirectory);
134
+ },
135
+ async writeOutput () {
136
+ await fs.copy(distDirectory, publicDirectory, {
137
+ filter: (src)=>shouldCopyToPublicAssets(src, distDirectory)
138
+ });
139
+ await fs.ensureDir(node_path.dirname(workerEntryPath));
140
+ await fs.ensureDir(node_path.dirname(workerManifestPath));
141
+ const routeSpecSourcePath = node_path.join(distDirectory, ROUTE_SPEC_FILE);
142
+ if (await fs.pathExists(routeSpecSourcePath)) await fs.copy(routeSpecSourcePath, routeSpecOutputPath);
143
+ const workerBundleSourceDirectory = node_path.join(distDirectory, WORKER_BUNDLE_DIRECTORY);
144
+ if (await fs.pathExists(workerBundleSourceDirectory)) await fs.copy(workerBundleSourceDirectory, node_path.join(outputDirectory, WORKER_BUNDLE_DIRECTORY), {
145
+ filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
146
+ });
147
+ await fs.writeJSON(wranglerConfigPath, {
148
+ $schema: 'node_modules/wrangler/config-schema.json',
149
+ name: workerName,
150
+ main: WORKER_ENTRY,
151
+ compatibility_date: getCompatibilityDate(),
152
+ compatibility_flags: [
153
+ 'nodejs_compat'
154
+ ],
155
+ assets: {
156
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
157
+ binding: ASSETS_BINDING,
158
+ run_worker_first: true
159
+ }
160
+ }, {
161
+ spaces: 2
162
+ });
163
+ await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig), {
164
+ spaces: 2
165
+ });
166
+ await fs.writeJSON(node_path.join(outputDirectory, 'package.json'), {
167
+ type: 'module'
168
+ });
169
+ },
170
+ async genEntry () {
171
+ const template = await readTemplate('cloudflare-entry.mjs');
172
+ const manifest = await fs.readJSON(workerManifestPath);
173
+ await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
174
+ }
175
+ };
176
+ };
177
+ export { createCloudflarePreset };
@@ -0,0 +1,258 @@
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 CORS_HEADERS = {
6
+ 'access-control-allow-headers': '*',
7
+ 'access-control-allow-methods': 'GET, HEAD, OPTIONS',
8
+ 'access-control-allow-origin': '*'
9
+ };
10
+ globalThis.__dirname ??= '/';
11
+ globalThis.__filename ??= '/index.js';
12
+ function withCorsHeaders(response) {
13
+ const headers = new Headers(response.headers);
14
+ for (const [name, value] of Object.entries(CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
15
+ return new Response(response.body, {
16
+ headers,
17
+ status: response.status,
18
+ statusText: response.statusText
19
+ });
20
+ }
21
+ function createCorsPreflightResponse(request) {
22
+ if ('OPTIONS' !== request.method) return null;
23
+ return new Response(null, {
24
+ headers: CORS_HEADERS,
25
+ status: 204
26
+ });
27
+ }
28
+ async function fetchAsset(request, env) {
29
+ const assets = env?.[ASSETS_BINDING];
30
+ if (!assets || 'function' != typeof assets.fetch) return null;
31
+ const response = await assets.fetch(request);
32
+ if (404 === response.status) return null;
33
+ return withCorsHeaders(response);
34
+ }
35
+ async function fetchAssetByPath(pathname, request, env) {
36
+ const url = new URL(request.url);
37
+ url.pathname = `/${pathname.replace(/^\/+/u, '')}`;
38
+ return fetchAsset(new Request(url, request), env);
39
+ }
40
+ async function fetchAssetByPathFollowingRedirects(pathname, request, env, visited = new Set()) {
41
+ const normalizedPathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
42
+ if (visited.has(normalizedPathname)) return null;
43
+ visited.add(normalizedPathname);
44
+ const response = await fetchAssetByPath(normalizedPathname, request, env);
45
+ if (response && response.status >= 300 && response.status < 400 && response.headers.has('location')) {
46
+ const location = response.headers.get('location');
47
+ if (location) {
48
+ const nextUrl = new URL(location, request.url);
49
+ const currentUrl = new URL(request.url);
50
+ if (nextUrl.origin === currentUrl.origin) return fetchAssetByPathFollowingRedirects(nextUrl.pathname, request, env, visited);
51
+ }
52
+ }
53
+ return response;
54
+ }
55
+ async function readAssetText(pathname, request, env) {
56
+ const response = await fetchAssetByPathFollowingRedirects(pathname, request, env);
57
+ if (!response || !response.ok) return;
58
+ return response.text();
59
+ }
60
+ async function readAssetJson(pathname, request, env) {
61
+ const text = await readAssetText(pathname, request, env);
62
+ if (!text) return {};
63
+ return JSON.parse(text);
64
+ }
65
+ function normalizeRoutePath(pathname) {
66
+ if ('/' === pathname) return pathname;
67
+ return pathname.replace(/\/+$/u, '');
68
+ }
69
+ function routeMatches(route, pathname) {
70
+ if ('string' != typeof route.urlPath) return false;
71
+ const routePath = normalizeRoutePath(route.urlPath);
72
+ const requestPath = normalizeRoutePath(pathname);
73
+ return routePath === requestPath || '/' === routePath && route.isSSR || requestPath.startsWith(`${routePath}/`);
74
+ }
75
+ function findRoute(request) {
76
+ const { pathname } = new URL(request.url);
77
+ const routes = MODERN_WORKER_MANIFEST.routeSpec.routes;
78
+ return [
79
+ ...routes
80
+ ].sort((left, right)=>{
81
+ const leftLength = left.urlPath?.length || 0;
82
+ const rightLength = right.urlPath?.length || 0;
83
+ return rightLength - leftLength;
84
+ }).find((route)=>routeMatches(route, pathname));
85
+ }
86
+ async function fetchRouteHtml(route, request, env) {
87
+ if (!route?.entryPath) return null;
88
+ return fetchAssetByPath(route.entryPath, request, env);
89
+ }
90
+ function createNoopMonitors() {
91
+ const noop = ()=>{};
92
+ return {
93
+ debug: noop,
94
+ error: noop,
95
+ info: noop,
96
+ warn: noop
97
+ };
98
+ }
99
+ function createRequestHandlerOptions({ route, htmlTemplate, routeManifest, loadableStats }) {
100
+ const monitors = createNoopMonitors();
101
+ return {
102
+ resource: {
103
+ route,
104
+ routeManifest,
105
+ loadableStats,
106
+ htmlTemplate,
107
+ entryName: route.entryName
108
+ },
109
+ params: {},
110
+ loaderContext: {},
111
+ config: {},
112
+ locals: {},
113
+ staticGenerate: false,
114
+ monitors,
115
+ onError (error) {
116
+ monitors.error(error);
117
+ },
118
+ onTiming () {},
119
+ reporter: {
120
+ reportTiming: ()=>{}
121
+ }
122
+ };
123
+ }
124
+ async function getRequestHandlerOptions(route, request, env) {
125
+ const [htmlTemplate, routeManifest, loadableStats] = await Promise.all([
126
+ readAssetText(route.entryPath, request, env),
127
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.routeManifest, request, env),
128
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.loadableStats, request, env)
129
+ ]);
130
+ return createRequestHandlerOptions({
131
+ route,
132
+ htmlTemplate: htmlTemplate || '',
133
+ routeManifest,
134
+ loadableStats
135
+ });
136
+ }
137
+ async function loadWorkerModule(workerPath) {
138
+ const loader = WORKER_MODULE_LOADERS[workerPath];
139
+ if (!loader) return;
140
+ if (!workerModulePromises.has(workerPath)) workerModulePromises.set(workerPath, loader());
141
+ return workerModulePromises.get(workerPath);
142
+ }
143
+ function getFetchHandler(workerModule) {
144
+ const defaultExport = workerModule.default;
145
+ return defaultExport && 'object' == typeof defaultExport && 'function' == typeof defaultExport.fetch && defaultExport.fetch.bind(defaultExport) || 'function' == typeof workerModule.fetch && workerModule.fetch;
146
+ }
147
+ async function getRequestHandler(workerModule) {
148
+ const defaultExport = workerModule.default;
149
+ const defaultRequestHandler = defaultExport && 'object' == typeof defaultExport && 'requestHandler' in defaultExport ? defaultExport.requestHandler : void 0;
150
+ return await workerModule.requestHandler || await defaultRequestHandler || ('function' == typeof defaultExport ? defaultExport : void 0);
151
+ }
152
+ async function dispatchRouteWorker(route, request, env, ctx) {
153
+ const workerPath = route.worker;
154
+ if (!workerPath) return new Response('Worker bundle not configured for SSR route', {
155
+ status: 500,
156
+ headers: {
157
+ 'content-type': 'text/plain; charset=utf-8'
158
+ }
159
+ });
160
+ const workerModule = await loadWorkerModule(workerPath);
161
+ if (!workerModule) return new Response(`Worker bundle not found: ${workerPath}`, {
162
+ status: 500,
163
+ headers: {
164
+ 'content-type': 'text/plain; charset=utf-8',
165
+ 'x-modern-js-route-worker': workerPath
166
+ }
167
+ });
168
+ const fetchHandler = getFetchHandler(workerModule);
169
+ if (fetchHandler) return fetchHandler(request, env, ctx);
170
+ const requestHandler = await getRequestHandler(workerModule);
171
+ if ('function' == typeof requestHandler) {
172
+ const requestHandlerOptions = await getRequestHandlerOptions(route, request, env);
173
+ return requestHandler(request, requestHandlerOptions);
174
+ }
175
+ return new Response(`Worker bundle has no fetch or requestHandler export: ${workerPath}`, {
176
+ status: 500,
177
+ headers: {
178
+ 'content-type': 'text/plain; charset=utf-8',
179
+ 'x-modern-js-route-worker': workerPath
180
+ }
181
+ });
182
+ }
183
+ function matchesPrefix(pathname, prefix) {
184
+ if (!prefix || '/' === prefix) return true;
185
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
186
+ return pathname === normalized || pathname.startsWith(`${normalized}/`);
187
+ }
188
+ function createRequestForMountedPrefix(request, prefix) {
189
+ if (!prefix || '/' === prefix) return request;
190
+ const url = new URL(request.url);
191
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
192
+ if (!matchesPrefix(url.pathname, normalized)) return request;
193
+ const nextPath = url.pathname.slice(normalized.length) || '/';
194
+ url.pathname = nextPath.startsWith('/') ? nextPath : `/${nextPath}`;
195
+ return new Request(url, request);
196
+ }
197
+ function createEffectContext(originalRequest, mountedRequest, env) {
198
+ const url = new URL(originalRequest.url);
199
+ return {
200
+ request: mountedRequest,
201
+ env: env || {},
202
+ path: url.pathname,
203
+ method: originalRequest.method,
204
+ operationContext: {
205
+ request: mountedRequest,
206
+ env: env || {},
207
+ path: url.pathname,
208
+ method: originalRequest.method
209
+ }
210
+ };
211
+ }
212
+ async function dispatchBffRequest(request, env) {
213
+ const bff = MODERN_WORKER_MANIFEST.bff;
214
+ if (!bff?.worker || !matchesPrefix(new URL(request.url).pathname, bff.prefix)) return null;
215
+ const workerModule = await loadWorkerModule(bff.worker);
216
+ if (!workerModule) return new Response(`BFF worker bundle not found: ${bff.worker}`, {
217
+ status: 500,
218
+ headers: {
219
+ 'content-type': 'text/plain; charset=utf-8',
220
+ 'x-modern-js-bff-worker': bff.worker
221
+ }
222
+ });
223
+ const mountedRequest = createRequestForMountedPrefix(request, bff.prefix);
224
+ const effectContext = createEffectContext(request, mountedRequest, env);
225
+ const defaultExport = workerModule.default;
226
+ const runtime = defaultExport && 'object' == typeof defaultExport ? {
227
+ ...workerModule,
228
+ ...defaultExport
229
+ } : workerModule;
230
+ const directHandler = 'function' == typeof runtime.handler && runtime.handler || 'function' == typeof defaultExport && defaultExport;
231
+ const createdHandler = 'function' == typeof runtime.createHandler ? runtime.createHandler().handler : void 0;
232
+ const handler = directHandler || createdHandler;
233
+ if ('function' != typeof handler) return new Response(`BFF worker bundle has no handler export: ${bff.worker}`, {
234
+ status: 500,
235
+ headers: {
236
+ 'content-type': 'text/plain; charset=utf-8',
237
+ 'x-modern-js-bff-worker': bff.worker
238
+ }
239
+ });
240
+ return handler.length > 1 ? handler(mountedRequest, effectContext) : handler(mountedRequest);
241
+ }
242
+ export default {
243
+ async fetch (request, env, ctx) {
244
+ const corsPreflightResponse = createCorsPreflightResponse(request);
245
+ if (corsPreflightResponse) return corsPreflightResponse;
246
+ const assetResponse = await fetchAsset(request, env);
247
+ if (assetResponse) return assetResponse;
248
+ const bffResponse = await dispatchBffRequest(request, env);
249
+ if (bffResponse) return withCorsHeaders(bffResponse);
250
+ const route = findRoute(request);
251
+ if (route?.worker) return withCorsHeaders(await dispatchRouteWorker(route, request, env, ctx));
252
+ const htmlResponse = await fetchRouteHtml(route, request, env);
253
+ if (htmlResponse) return htmlResponse;
254
+ return withCorsHeaders(new Response('Not found', {
255
+ status: 404
256
+ }));
257
+ }
258
+ };
@@ -1,17 +1,19 @@
1
1
  import "node:module";
2
2
  import { parseRspackConfig } from "@modern-js/builder";
3
+ import { INTERNAL_RUNTIME_PLUGINS } from "@modern-js/utils";
3
4
  import { builderPluginAdapterBasic, builderPluginAdapterHooks } from "./builder/shared/builderPlugins/index.mjs";
4
5
  import { DEFAULT_CONFIG_FILE } from "./constants.mjs";
5
6
  import { getConfigFile } from "./utils/getConfigFile.mjs";
7
+ import { loadInternalPlugins } from "./utils/loadPlugins.mjs";
6
8
  import { __webpack_require__ } from "./rslib-runtime.mjs";
7
9
  import * as __rspack_external__modern_js_plugin_cli_caa09fa2 from "@modern-js/plugin/cli";
8
10
  __webpack_require__.add({
9
- "@modern-js/plugin/cli?f956" (module) {
11
+ "@modern-js/plugin/cli?8936" (module) {
10
12
  module.exports = __rspack_external__modern_js_plugin_cli_caa09fa2;
11
13
  }
12
14
  });
13
15
  const MODERN_META_NAME = 'modern-js';
14
- const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?f956");
16
+ const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?8936");
15
17
  async function resolveModernRsbuildConfig(options) {
16
18
  const { cwd = process.cwd(), metaName = MODERN_META_NAME } = options;
17
19
  const configFile = options.configPath || getConfigFile(void 0, cwd);
@@ -20,6 +22,7 @@ async function resolveModernRsbuildConfig(options) {
20
22
  command: options.command,
21
23
  cwd,
22
24
  configFile,
25
+ internalPlugins: await loadInternalPlugins(cwd, INTERNAL_RUNTIME_PLUGINS),
23
26
  metaName,
24
27
  modifyModernConfig: options.modifyModernConfig
25
28
  });
@@ -0,0 +1,46 @@
1
+ import type { AppUserConfig } from './types';
2
+ export interface AppBaselineOptions {
3
+ /**
4
+ * Stable producer identity used by BFF cross-project clients.
5
+ * @default "app"
6
+ */
7
+ appId?: string;
8
+ /**
9
+ * Enable BFF requestId contract by default.
10
+ * @default true
11
+ */
12
+ enableBffRequestId?: boolean;
13
+ /**
14
+ * Enable telemetry contract by default.
15
+ * Exporters are still configured separately by applications.
16
+ * @default true
17
+ */
18
+ enableTelemetry?: boolean;
19
+ /**
20
+ * Enable telemetry exporters by default.
21
+ * @default true
22
+ */
23
+ enableTelemetryExporters?: boolean;
24
+ /**
25
+ * OTLP exporter endpoint.
26
+ * @default process.env.MODERN_TELEMETRY_OTLP_ENDPOINT || 'http://127.0.0.1:4318/v1/logs'
27
+ */
28
+ otlpEndpoint?: string;
29
+ /**
30
+ * VictoriaMetrics exporter endpoint.
31
+ * @default process.env.MODERN_TELEMETRY_VICTORIA_ENDPOINT || 'http://127.0.0.1:8428/api/v1/import/prometheus'
32
+ */
33
+ victoriaMetricsEndpoint?: string;
34
+ /**
35
+ * Enable fail-loud startup probing for telemetry exporters.
36
+ * @default true
37
+ */
38
+ telemetryFailLoudStartup?: boolean;
39
+ /**
40
+ * Enable app-level Module Federation SSR handshake by default.
41
+ * @default true
42
+ */
43
+ enableModuleFederationSSR?: boolean;
44
+ }
45
+ export declare const createAppBaselineConfig: (options?: AppBaselineOptions) => AppUserConfig;
46
+ export declare const withAppBaseline: (config: AppUserConfig, options?: AppBaselineOptions) => AppUserConfig;
@@ -0,0 +1,2 @@
1
+ import type { BuilderOptions } from '../shared';
2
+ export declare function createRspackBuilderForModern(options: BuilderOptions): Promise<any>;
@@ -0,0 +1,3 @@
1
+ import type { RsbuildPlugin } from '@modern-js/builder';
2
+ import type { BuilderOptions } from '../shared';
3
+ export declare const builderPluginAdapterCopy: (options: BuilderOptions) => RsbuildPlugin;
@@ -0,0 +1,3 @@
1
+ import type { AppNormalizedConfig } from '../../types';
2
+ import type { AppToolsContext } from '../../types/plugin';
3
+ export declare function createBuilderProviderConfig(resolveConfig: AppNormalizedConfig, appContext: AppToolsContext): Omit<AppNormalizedConfig, 'plugins'>;