@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.99 → 3.4.0-ultramodern.1

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 (165) hide show
  1. package/dist/cjs/baseline.js +12 -92
  2. package/dist/cjs/builder/builder-rspack/index.js +9 -5
  3. package/dist/cjs/builder/generator/adapterCopy.js +9 -5
  4. package/dist/cjs/builder/generator/createBuilderProviderConfig.js +9 -5
  5. package/dist/cjs/builder/generator/createCopyPattern.js +9 -5
  6. package/dist/cjs/builder/generator/getBuilderEnvironments.js +41 -9
  7. package/dist/cjs/builder/generator/index.js +16 -5
  8. package/dist/cjs/builder/index.js +9 -5
  9. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +9 -5
  10. package/dist/cjs/builder/shared/builderPlugins/adapterHtml.js +10 -6
  11. package/dist/cjs/builder/shared/builderPlugins/adapterPrecompress.js +9 -5
  12. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +39 -9
  13. package/dist/cjs/builder/shared/builderPlugins/builderHooks.js +12 -8
  14. package/dist/cjs/builder/shared/builderPlugins/index.js +9 -5
  15. package/dist/cjs/builder/shared/bundlerPlugins/HtmlAsyncChunkPlugin.js +9 -5
  16. package/dist/cjs/builder/shared/bundlerPlugins/HtmlBottomTemplate.js +12 -8
  17. package/dist/cjs/builder/shared/bundlerPlugins/RouterPlugin.js +41 -8
  18. package/dist/cjs/builder/shared/bundlerPlugins/index.js +9 -5
  19. package/dist/cjs/builder/shared/createCopyInfo.js +9 -5
  20. package/dist/cjs/builder/shared/index.js +9 -5
  21. package/dist/cjs/builder/shared/lazyCompilation.js +94 -0
  22. package/dist/cjs/builder/shared/loaders/serverModuleLoader.js +12 -8
  23. package/dist/cjs/commands/build.js +9 -5
  24. package/dist/cjs/commands/deploy.js +9 -5
  25. package/dist/cjs/commands/dev.js +9 -5
  26. package/dist/cjs/commands/index.js +12 -11
  27. package/dist/cjs/commands/info.js +9 -5
  28. package/dist/cjs/commands/inspect.js +12 -8
  29. package/dist/cjs/commands/runtime.js +50 -13
  30. package/dist/cjs/commands/serve.js +9 -5
  31. package/dist/cjs/compat/hooks.js +9 -5
  32. package/dist/cjs/compat/index.js +9 -5
  33. package/dist/cjs/compat/utils.js +9 -5
  34. package/dist/cjs/config/default.js +27 -7
  35. package/dist/cjs/config/index.js +9 -5
  36. package/dist/cjs/config/initialize/index.js +9 -5
  37. package/dist/cjs/config/initialize/inits.js +9 -5
  38. package/dist/cjs/constants.js +13 -9
  39. package/dist/cjs/defineConfig.js +12 -8
  40. package/dist/cjs/esm/register-esm.js +12 -8
  41. package/dist/cjs/esm/ts-paths-loader.js +9 -5
  42. package/dist/cjs/index.js +23 -17
  43. package/dist/cjs/locale/en.js +12 -8
  44. package/dist/cjs/locale/index.js +9 -5
  45. package/dist/cjs/locale/zh.js +12 -8
  46. package/dist/cjs/plugins/analyze/constants.js +14 -10
  47. package/dist/cjs/plugins/analyze/getBundleEntry.js +9 -5
  48. package/dist/cjs/plugins/analyze/getFileSystemEntry.js +9 -5
  49. package/dist/cjs/plugins/analyze/getHtmlTemplate.js +9 -5
  50. package/dist/cjs/plugins/analyze/getServerRoutes.js +9 -5
  51. package/dist/cjs/plugins/analyze/index.js +12 -6
  52. package/dist/cjs/plugins/analyze/isDefaultExportFunction.js +10 -6
  53. package/dist/cjs/plugins/analyze/templates.js +12 -8
  54. package/dist/cjs/plugins/analyze/utils.js +9 -5
  55. package/dist/cjs/plugins/deploy/index.js +9 -5
  56. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +185 -7
  57. package/dist/cjs/plugins/deploy/platforms/gh-pages.js +9 -5
  58. package/dist/cjs/plugins/deploy/platforms/netlify.js +9 -5
  59. package/dist/cjs/plugins/deploy/platforms/node.js +9 -5
  60. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  61. package/dist/cjs/plugins/deploy/platforms/vercel.js +9 -5
  62. package/dist/cjs/plugins/deploy/utils/generator.js +9 -5
  63. package/dist/cjs/plugins/deploy/utils/index.js +19 -40
  64. package/dist/cjs/plugins/initialize/index.js +19 -6
  65. package/dist/cjs/plugins/serverBuild.js +9 -5
  66. package/dist/cjs/plugins/serverRuntime.js +12 -8
  67. package/dist/cjs/presetUltramodern.js +96 -7
  68. package/dist/cjs/rsbuild.js +55 -67
  69. package/dist/cjs/run/index.js +9 -5
  70. package/dist/cjs/types/config/cloudflareDeploy.js +18 -0
  71. package/dist/cjs/types/config/index.js +9 -5
  72. package/dist/cjs/types/config/precompress.js +18 -0
  73. package/dist/cjs/types/index.js +9 -5
  74. package/dist/cjs/ultramodern/designSystem.js +16 -12
  75. package/dist/cjs/utils/config.js +9 -5
  76. package/dist/cjs/utils/createServer.js +14 -10
  77. package/dist/cjs/utils/env.js +9 -5
  78. package/dist/cjs/utils/generateWatchFiles.js +9 -5
  79. package/dist/cjs/utils/getConfigFile.js +9 -5
  80. package/dist/cjs/utils/getSelectedEntries.js +9 -5
  81. package/dist/cjs/utils/initAppContext.js +9 -5
  82. package/dist/cjs/utils/loadPlugins.js +9 -5
  83. package/dist/cjs/utils/printInstructions.js +9 -5
  84. package/dist/cjs/utils/register.js +9 -5
  85. package/dist/cjs/utils/restart.js +9 -5
  86. package/dist/cjs/utils/routes.js +9 -5
  87. package/dist/esm/baseline.mjs +3 -77
  88. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +32 -4
  89. package/dist/esm/builder/generator/index.mjs +7 -0
  90. package/dist/esm/builder/shared/builderPlugins/adapterHtml.mjs +1 -1
  91. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +31 -5
  92. package/dist/esm/builder/shared/bundlerPlugins/RouterPlugin.mjs +32 -3
  93. package/dist/esm/builder/shared/lazyCompilation.mjs +44 -0
  94. package/dist/esm/commands/index.mjs +2 -5
  95. package/dist/esm/commands/runtime.mjs +33 -3
  96. package/dist/esm/config/default.mjs +14 -1
  97. package/dist/esm/index.mjs +3 -2
  98. package/dist/esm/plugins/analyze/index.mjs +3 -1
  99. package/dist/esm/plugins/analyze/isDefaultExportFunction.mjs +1 -1
  100. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +176 -2
  101. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  102. package/dist/esm/plugins/deploy/utils/index.mjs +11 -36
  103. package/dist/esm/plugins/initialize/index.mjs +11 -2
  104. package/dist/esm/presetUltramodern.mjs +77 -3
  105. package/dist/esm/rsbuild.mjs +1 -8
  106. package/dist/esm/types/config/cloudflareDeploy.mjs +0 -0
  107. package/dist/esm/types/config/precompress.mjs +0 -0
  108. package/dist/esm-node/baseline.mjs +3 -77
  109. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +32 -4
  110. package/dist/esm-node/builder/generator/index.mjs +7 -0
  111. package/dist/esm-node/builder/shared/builderPlugins/adapterHtml.mjs +1 -1
  112. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +31 -5
  113. package/dist/esm-node/builder/shared/bundlerPlugins/RouterPlugin.mjs +32 -3
  114. package/dist/esm-node/builder/shared/lazyCompilation.mjs +45 -0
  115. package/dist/esm-node/commands/index.mjs +2 -5
  116. package/dist/esm-node/commands/runtime.mjs +33 -3
  117. package/dist/esm-node/config/default.mjs +14 -1
  118. package/dist/esm-node/index.mjs +3 -2
  119. package/dist/esm-node/plugins/analyze/index.mjs +3 -1
  120. package/dist/esm-node/plugins/analyze/isDefaultExportFunction.mjs +1 -1
  121. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +176 -2
  122. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  123. package/dist/esm-node/plugins/deploy/utils/index.mjs +12 -36
  124. package/dist/esm-node/plugins/initialize/index.mjs +11 -2
  125. package/dist/esm-node/presetUltramodern.mjs +77 -3
  126. package/dist/esm-node/rsbuild.mjs +1 -8
  127. package/dist/esm-node/types/config/cloudflareDeploy.mjs +1 -0
  128. package/dist/esm-node/types/config/precompress.mjs +1 -0
  129. package/dist/types/baseline.d.ts +16 -46
  130. package/dist/types/builder/builder-rspack/index.d.ts +1 -1
  131. package/dist/types/builder/generator/index.d.ts +1 -1
  132. package/dist/types/builder/shared/bundlerPlugins/RouterPlugin.d.ts +3 -1
  133. package/dist/types/builder/shared/createCopyInfo.d.ts +1 -1
  134. package/dist/types/builder/shared/lazyCompilation.d.ts +43 -0
  135. package/dist/types/builder/shared/types.d.ts +10 -0
  136. package/dist/types/commands/index.d.ts +1 -1
  137. package/dist/types/commands/inspect.d.ts +1 -1
  138. package/dist/types/commands/runtime.d.ts +1 -0
  139. package/dist/types/config/default.d.ts +6 -0
  140. package/dist/types/locale/index.d.ts +89 -2
  141. package/dist/types/plugins/analyze/getFileSystemEntry.d.ts +2 -2
  142. package/dist/types/plugins/analyze/index.d.ts +1 -1
  143. package/dist/types/plugins/analyze/utils.d.ts +1 -1
  144. package/dist/types/plugins/deploy/index.d.ts +1 -1
  145. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +1 -1
  146. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.cts +1 -1
  147. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.cts +1 -1
  148. package/dist/types/plugins/deploy/utils/generator.d.ts +2 -2
  149. package/dist/types/plugins/deploy/utils/index.d.ts +1 -1
  150. package/dist/types/plugins/initialize/index.d.ts +1 -1
  151. package/dist/types/plugins/serverBuild.d.ts +1 -1
  152. package/dist/types/plugins/serverRuntime.d.ts +1 -1
  153. package/dist/types/presetUltramodern.d.ts +52 -2
  154. package/dist/types/rsbuild.d.ts +1 -1
  155. package/dist/types/run/index.d.ts +1 -1
  156. package/dist/types/types/config/cloudflareDeploy.d.ts +79 -0
  157. package/dist/types/types/config/deploy.d.ts +9 -15
  158. package/dist/types/types/config/output.d.ts +4 -20
  159. package/dist/types/types/config/precompress.d.ts +20 -0
  160. package/dist/types/types/plugin.d.ts +20 -0
  161. package/dist/types/utils/getConfigFile.d.ts +1 -1
  162. package/dist/types/utils/loadPlugins.d.ts +2 -2
  163. package/package.json +26 -21
  164. package/dist/esm/rslib-runtime.mjs +0 -18
  165. package/dist/esm-node/rslib-runtime.mjs +0 -19
@@ -54,9 +54,39 @@ const parseResponseBody = async (response)=>{
54
54
  };
55
55
  }
56
56
  };
57
+ const INDENT_STEP = ' ';
58
+ const formatScalar = (value)=>'string' == typeof value ? value : JSON.stringify(value) ?? 'undefined';
59
+ const formatHumanReadableLines = (value, indent)=>{
60
+ if (Array.isArray(value)) {
61
+ if (0 === value.length) return [
62
+ `${indent}(empty)`
63
+ ];
64
+ return value.flatMap((entry)=>null !== entry && 'object' == typeof entry ? [
65
+ `${indent}-`,
66
+ ...formatHumanReadableLines(entry, indent + INDENT_STEP)
67
+ ] : [
68
+ `${indent}- ${formatScalar(entry)}`
69
+ ]);
70
+ }
71
+ if (null !== value && 'object' == typeof value) {
72
+ const entries = Object.entries(value);
73
+ if (0 === entries.length) return [
74
+ `${indent}(empty)`
75
+ ];
76
+ return entries.flatMap(([key, entry])=>null !== entry && 'object' == typeof entry ? [
77
+ `${indent}${key}:`,
78
+ ...formatHumanReadableLines(entry, indent + INDENT_STEP)
79
+ ] : [
80
+ `${indent}${key}: ${formatScalar(entry)}`
81
+ ]);
82
+ }
83
+ return [
84
+ `${indent}${formatScalar(value)}`
85
+ ];
86
+ };
87
+ const formatRuntimeOutput = (payload, jsonOnly)=>jsonOnly ? JSON.stringify(payload, null, 2) : formatHumanReadableLines(payload, '').join('\n');
57
88
  const printOutput = (payload, jsonOnly)=>{
58
- if (jsonOnly) return void console.log(JSON.stringify(payload, null, 2));
59
- console.log(JSON.stringify(payload, null, 2));
89
+ console.log(formatRuntimeOutput(payload, jsonOnly));
60
90
  };
61
91
  const createRuntimeFallbackSignalPayload = (options)=>{
62
92
  const payload = {
@@ -113,4 +143,4 @@ const runtimeCommand = async (program, _api)=>{
113
143
  printOutput(responsePayload, options.json);
114
144
  });
115
145
  };
116
- export { createRuntimeFallbackSignalPayload, resolveRuntimeEndpoint, resolveToken, runtimeCommand };
146
+ export { createRuntimeFallbackSignalPayload, formatRuntimeOutput, resolveRuntimeEndpoint, resolveToken, runtimeCommand };
@@ -88,4 +88,17 @@ function createDefaultConfig(appContext) {
88
88
  builderPlugins: []
89
89
  };
90
90
  }
91
- export { createDefaultConfig };
91
+ const isStreamSSRConfig = (ssr)=>{
92
+ if (!ssr) return false;
93
+ if ('boolean' == typeof ssr) return ssr;
94
+ return 'string' !== ssr.mode;
95
+ };
96
+ function isLazyCompilationSafeByDefault(userConfig) {
97
+ const { server, output } = userConfig;
98
+ if (output?.ssg || output?.ssgByEntries && Object.keys(output.ssgByEntries).length > 0) return false;
99
+ if (server?.rsc) return false;
100
+ if (server?.ssr && !isStreamSSRConfig(server.ssr)) return false;
101
+ if (server?.ssrByEntries && 'object' == typeof server.ssrByEntries && Object.values(server.ssrByEntries).some((ssr)=>Boolean(ssr) && !isStreamSSRConfig(ssr))) return false;
102
+ return true;
103
+ }
104
+ export { createDefaultConfig, isLazyCompilationSafeByDefault };
@@ -3,7 +3,7 @@ import { getLocaleLanguage } from "@modern-js/i18n-utils/language-detector";
3
3
  import { createAsyncHook } from "@modern-js/plugin";
4
4
  import { cleanRequireCache, deprecatedCommands, emptyDir, getArgv, getCommand } from "@modern-js/utils";
5
5
  import path from "path";
6
- import { buildCommand, deployCommand, devCommand, infoCommand, inspectCommand, runtimeOperationsCommand, serverCommand } from "./commands/index.mjs";
6
+ import { buildCommand, deployCommand, devCommand, infoCommand, inspectCommand, runtimeCommand, serverCommand } from "./commands/index.mjs";
7
7
  import { compatPlugin } from "./compat/index.mjs";
8
8
  import { DEFAULT_RUNTIME_CONFIG_FILE } from "./constants.mjs";
9
9
  import { i18n } from "./locale/index.mjs";
@@ -43,6 +43,7 @@ const appTools = ()=>({
43
43
  deploy: createAsyncHook(),
44
44
  checkEntryPoint: createAsyncHook(),
45
45
  modifyEntrypoints: createAsyncHook(),
46
+ modifyBuilderEnvironments: createAsyncHook(),
46
47
  modifyFileSystemRoutes: createAsyncHook(),
47
48
  generateEntryCode: createAsyncHook(),
48
49
  onBeforeGenerateRoutes: createAsyncHook(),
@@ -71,7 +72,7 @@ const appTools = ()=>({
71
72
  deployCommand(program, api);
72
73
  inspectCommand(program, api);
73
74
  infoCommand(program, api);
74
- await runtimeOperationsCommand(program, api);
75
+ await runtimeCommand(program, api);
75
76
  deprecatedCommands(program);
76
77
  });
77
78
  api.onPrepare(async ()=>{
@@ -122,10 +122,12 @@ const analyze = ()=>({
122
122
  entrypoints
123
123
  });
124
124
  const normalizedConfig = api.getNormalizedConfig();
125
+ const { eagerRouteComponentFilesByEntry } = api.getAppContext();
125
126
  const createBuilderForModern = await createBuilderGenerator();
126
127
  const builder = await createBuilderForModern({
127
128
  normalizedConfig: normalizedConfig,
128
- appContext: appContext
129
+ appContext: appContext,
130
+ eagerRouteComponentFilesByEntry
129
131
  });
130
132
  builder.onBeforeBuild(async ({ bundlerConfigs, isFirstCompile, environments, isWatch })=>{
131
133
  if (!isFirstCompile) return;
@@ -20,7 +20,7 @@ const isDefaultExportFunction = (file)=>{
20
20
  [
21
21
  'pipelineOperator',
22
22
  {
23
- proposal: 'minimal'
23
+ proposal: 'fsharp'
24
24
  }
25
25
  ],
26
26
  'optionalChaining',
@@ -12,7 +12,88 @@ const PUBLIC_ASSETS_DIRECTORY = 'public';
12
12
  const WORKER_BUNDLE_DIRECTORY = 'worker';
13
13
  const SERVER_BUNDLE_DIRECTORY = 'bundles';
14
14
  const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
15
- const getCompatibilityDate = ()=>new Date().toISOString().slice(0, 10);
15
+ const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
16
+ const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
17
+ const DEFAULT_SECURITY_HEADERS = {
18
+ referrerPolicy: 'strict-origin-when-cross-origin',
19
+ contentTypeOptions: 'nosniff',
20
+ permissionsPolicy: 'camera=(), geolocation=(), microphone=(), payment=(), usb=()'
21
+ };
22
+ const DEFAULT_CORS_ALLOWED_METHODS = [
23
+ 'GET',
24
+ 'HEAD',
25
+ 'POST',
26
+ 'PUT',
27
+ 'PATCH',
28
+ 'DELETE',
29
+ 'OPTIONS'
30
+ ];
31
+ const DEFAULT_CSP_DIRECTIVES = {
32
+ 'base-uri': [
33
+ "'self'"
34
+ ],
35
+ 'connect-src': [
36
+ "'self'",
37
+ 'https:',
38
+ 'http:',
39
+ 'wss:',
40
+ 'ws:'
41
+ ],
42
+ 'default-src': [
43
+ "'self'"
44
+ ],
45
+ 'font-src': [
46
+ "'self'",
47
+ 'data:',
48
+ 'https:',
49
+ 'http:'
50
+ ],
51
+ 'form-action': [
52
+ "'self'"
53
+ ],
54
+ 'frame-ancestors': [
55
+ "'self'"
56
+ ],
57
+ 'img-src': [
58
+ "'self'",
59
+ 'data:',
60
+ 'blob:',
61
+ 'https:',
62
+ 'http:'
63
+ ],
64
+ 'manifest-src': [
65
+ "'self'",
66
+ 'https:',
67
+ 'http:'
68
+ ],
69
+ 'object-src': [
70
+ "'none'"
71
+ ],
72
+ "script-src": [
73
+ "'self'",
74
+ "'unsafe-inline'",
75
+ "'unsafe-eval'",
76
+ 'https:',
77
+ 'http:',
78
+ 'blob:'
79
+ ],
80
+ 'style-src': [
81
+ "'self'",
82
+ "'unsafe-inline'",
83
+ 'https:',
84
+ 'http:'
85
+ ],
86
+ 'worker-src': [
87
+ "'self'",
88
+ 'blob:'
89
+ ]
90
+ };
91
+ const getCompatibilityDate = (modernConfig)=>{
92
+ const configuredDate = modernConfig.deploy?.worker?.compatibilityDate?.trim();
93
+ const compatibilityDate = configuredDate || DEFAULT_COMPATIBILITY_DATE;
94
+ if (!COMPATIBILITY_DATE_PATTERN.test(compatibilityDate)) throw new Error(`deploy.worker.compatibilityDate must use YYYY-MM-DD, received ${JSON.stringify(compatibilityDate)}.`);
95
+ return compatibilityDate;
96
+ };
16
97
  const getWorkerName = (appDirectory)=>{
17
98
  const basename = node_path.basename(appDirectory);
18
99
  return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
@@ -21,6 +102,98 @@ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
21
102
  const configuredName = modernConfig.deploy?.worker?.name?.trim();
22
103
  return configuredName || getWorkerName(appDirectory);
23
104
  };
105
+ const normalizeDirectiveValues = (value)=>{
106
+ const values = Array.isArray(value) ? value : [
107
+ value
108
+ ];
109
+ return [
110
+ ...new Set(values.map((entry)=>entry.trim()).filter(Boolean))
111
+ ];
112
+ };
113
+ const appendDirectiveValues = (directives, name, values)=>{
114
+ if (!values?.length) return;
115
+ directives[name] = normalizeDirectiveValues([
116
+ ...directives[name] ?? [],
117
+ ...values
118
+ ]);
119
+ };
120
+ const createContentSecurityPolicy = (config)=>{
121
+ const mode = config?.mode ?? 'report-only';
122
+ if ('off' === mode) return {
123
+ mode,
124
+ directives: {},
125
+ reason: config?.reason
126
+ };
127
+ const directives = Object.fromEntries(Object.entries(DEFAULT_CSP_DIRECTIVES).map(([name, values])=>[
128
+ name,
129
+ [
130
+ ...values
131
+ ]
132
+ ]));
133
+ for (const [name, value] of Object.entries(config?.directives ?? {}))if (false === value) delete directives[name];
134
+ else directives[name] = normalizeDirectiveValues(value);
135
+ if (config?.frameAncestors === false) delete directives['frame-ancestors'];
136
+ else if (config?.frameAncestors) directives['frame-ancestors'] = normalizeDirectiveValues(config.frameAncestors);
137
+ appendDirectiveValues(directives, "script-src", config?.additionalScriptSrc);
138
+ appendDirectiveValues(directives, 'style-src', config?.additionalStyleSrc);
139
+ appendDirectiveValues(directives, 'connect-src', config?.additionalConnectSrc);
140
+ appendDirectiveValues(directives, 'img-src', config?.additionalImgSrc);
141
+ if (config?.reportUri) directives['report-uri'] = [
142
+ config.reportUri
143
+ ];
144
+ return {
145
+ mode,
146
+ directives,
147
+ reason: config?.reason
148
+ };
149
+ };
150
+ const createNoindexPolicy = (noindex)=>{
151
+ if (false === noindex) return {
152
+ workersDev: false,
153
+ localhost: false,
154
+ previewHostnames: []
155
+ };
156
+ if (true === noindex || void 0 === noindex) return {
157
+ workersDev: true,
158
+ localhost: true,
159
+ previewHostnames: []
160
+ };
161
+ return {
162
+ workersDev: noindex.workersDev ?? true,
163
+ localhost: noindex.localhost ?? true,
164
+ previewHostnames: noindex.previewHostnames ?? [],
165
+ reason: noindex.reason
166
+ };
167
+ };
168
+ const createCloudflareWorkerCorsPolicy = (cors)=>({
169
+ assets: cors?.assets ?? true,
170
+ allowedOrigins: normalizeDirectiveValues(cors?.allowedOrigins ?? []),
171
+ allowedMethods: cors?.allowedMethods?.length ? normalizeDirectiveValues(cors.allowedMethods.map((method)=>method.toUpperCase())) : DEFAULT_CORS_ALLOWED_METHODS,
172
+ allowedHeaders: cors?.allowedHeaders?.length ? normalizeDirectiveValues(cors.allowedHeaders) : [
173
+ '*'
174
+ ],
175
+ reason: cors?.reason
176
+ });
177
+ const createCloudflareWorkerSecurityPolicy = (modernConfig)=>{
178
+ const security = modernConfig.deploy?.worker?.security;
179
+ if (security?.enabled === false) return {
180
+ enabled: false,
181
+ cors: createCloudflareWorkerCorsPolicy(security.cors),
182
+ reason: security.reason
183
+ };
184
+ return {
185
+ enabled: true,
186
+ headers: {
187
+ referrerPolicy: security?.headers?.referrerPolicy ?? DEFAULT_SECURITY_HEADERS.referrerPolicy,
188
+ contentTypeOptions: security?.headers?.contentTypeOptions ?? DEFAULT_SECURITY_HEADERS.contentTypeOptions,
189
+ permissionsPolicy: security?.headers?.permissionsPolicy ?? DEFAULT_SECURITY_HEADERS.permissionsPolicy
190
+ },
191
+ contentSecurityPolicy: createContentSecurityPolicy(security?.contentSecurityPolicy),
192
+ noindex: createNoindexPolicy(security?.noindex),
193
+ cors: createCloudflareWorkerCorsPolicy(security?.cors),
194
+ reason: security?.reason
195
+ };
196
+ };
24
197
  const readRouteSpec = async (outputDirectory)=>{
25
198
  const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
26
199
  if (!await fs.pathExists(routeSpecPath)) return {
@@ -76,6 +249,7 @@ const createWorkerManifest = async (outputDirectory, modernConfig)=>{
76
249
  loadableStats: LOADABLE_STATS_FILE,
77
250
  routeManifest: ROUTE_MANIFEST_FILE
78
251
  },
252
+ security: createCloudflareWorkerSecurityPolicy(modernConfig),
79
253
  bff: isEffectBff && primaryBffPrefix && effectBffWorkerExists ? {
80
254
  runtimeFramework: 'effect',
81
255
  prefix: primaryBffPrefix,
@@ -148,7 +322,7 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
148
322
  $schema: 'node_modules/wrangler/config-schema.json',
149
323
  name: workerName,
150
324
  main: WORKER_ENTRY,
151
- compatibility_date: getCompatibilityDate(),
325
+ compatibility_date: getCompatibilityDate(modernConfig),
152
326
  compatibility_flags: [
153
327
  'nodejs_compat',
154
328
  'global_fetch_strictly_public'
@@ -3,27 +3,129 @@ const MODERN_WORKER_MANIFEST = p_workerManifest;
3
3
  const WORKER_MODULE_LOADERS = p_workerModuleLoaders;
4
4
  const workerModulePromises = new Map();
5
5
  const remoteJsonPromises = new Map();
6
- const CORS_HEADERS = {
6
+ const CORS_POLICY = MODERN_WORKER_MANIFEST.security?.cors || {};
7
+ const ASSET_CORS_ENABLED = false !== CORS_POLICY.assets;
8
+ const APP_CORS_ALLOWED_ORIGINS = (CORS_POLICY.allowedOrigins || []).map((origin)=>String(origin).toLowerCase());
9
+ const APP_CORS_ALLOWED_METHODS = (CORS_POLICY.allowedMethods?.length ? CORS_POLICY.allowedMethods : [
10
+ 'GET',
11
+ 'HEAD',
12
+ 'POST',
13
+ 'PUT',
14
+ 'PATCH',
15
+ 'DELETE',
16
+ 'OPTIONS'
17
+ ]).join(', ');
18
+ const APP_CORS_ALLOWED_HEADERS = (CORS_POLICY.allowedHeaders?.length ? CORS_POLICY.allowedHeaders : [
19
+ '*'
20
+ ]).join(', ');
21
+ const ASSET_CORS_HEADERS = {
7
22
  'access-control-allow-headers': '*',
8
23
  'access-control-allow-methods': 'GET, HEAD, OPTIONS',
9
24
  'access-control-allow-origin': '*'
10
25
  };
11
26
  globalThis.__dirname ??= '/';
12
27
  globalThis.__filename ??= '/index.js';
13
- function withCorsHeaders(response) {
28
+ function getAllowedAppCorsOrigin(request) {
29
+ if (0 === APP_CORS_ALLOWED_ORIGINS.length) return null;
30
+ const origin = request.headers.get('origin');
31
+ if (!origin) return null;
32
+ if (APP_CORS_ALLOWED_ORIGINS.includes('*')) return '*';
33
+ return APP_CORS_ALLOWED_ORIGINS.includes(origin.toLowerCase()) ? origin : null;
34
+ }
35
+ function appendVaryOrigin(headers) {
36
+ const vary = headers.get('vary');
37
+ if (!vary) return void headers.set('vary', 'origin');
38
+ const varyValues = vary.split(',').map((value)=>value.trim().toLowerCase());
39
+ if (!varyValues.includes('origin')) headers.set('vary', `${vary}, origin`);
40
+ }
41
+ function withAppCorsHeaders(response, request) {
42
+ const allowedOrigin = getAllowedAppCorsOrigin(request);
43
+ if (!allowedOrigin) return response;
14
44
  const headers = new Headers(response.headers);
15
- for (const [name, value] of Object.entries(CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
45
+ if (!headers.has('access-control-allow-origin')) headers.set('access-control-allow-origin', allowedOrigin);
46
+ if ('*' !== allowedOrigin) appendVaryOrigin(headers);
16
47
  return new Response(response.body, {
17
48
  headers,
18
49
  status: response.status,
19
50
  statusText: response.statusText
20
51
  });
21
52
  }
53
+ function withAssetCorsHeaders(response) {
54
+ if (!ASSET_CORS_ENABLED) return response;
55
+ const headers = new Headers(response.headers);
56
+ for (const [name, value] of Object.entries(ASSET_CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
57
+ return new Response(response.body, {
58
+ headers,
59
+ status: response.status,
60
+ statusText: response.statusText
61
+ });
62
+ }
63
+ function setHeaderIfEnabled(headers, name, value) {
64
+ if (false === value || 'string' != typeof value || '' === value.trim()) return;
65
+ if (!headers.has(name)) headers.set(name, value);
66
+ }
67
+ function renderContentSecurityPolicy(directives) {
68
+ return Object.entries(directives || {}).filter(([, values])=>Array.isArray(values) && values.length > 0).sort(([left], [right])=>left.localeCompare(right)).map(([name, values])=>`${name} ${values.join(' ')}`).join('; ');
69
+ }
70
+ function isHtmlResponse(response) {
71
+ return (response.headers.get('content-type') || '').includes('text/html');
72
+ }
73
+ function matchesPreviewHostname(hostname, pattern) {
74
+ const normalizedHostname = hostname.toLowerCase();
75
+ const normalizedPattern = String(pattern || '').toLowerCase();
76
+ if (!normalizedPattern) return false;
77
+ if (normalizedPattern.startsWith('*.')) return normalizedHostname.endsWith(normalizedPattern.slice(1));
78
+ return normalizedHostname === normalizedPattern;
79
+ }
80
+ function shouldNoindex(request, noindex) {
81
+ if (!noindex || false === noindex) return false;
82
+ const { hostname } = new URL(request.url);
83
+ const normalizedHostname = hostname.toLowerCase();
84
+ if (false !== noindex.localhost && ('localhost' === normalizedHostname || '127.0.0.1' === normalizedHostname || '[::1]' === normalizedHostname)) return true;
85
+ if (false !== noindex.workersDev && normalizedHostname.endsWith('.workers.dev')) return true;
86
+ return (noindex.previewHostnames || []).some((pattern)=>matchesPreviewHostname(normalizedHostname, pattern));
87
+ }
88
+ function withCloudflareSecurityHeaders(response, request) {
89
+ const security = MODERN_WORKER_MANIFEST.security;
90
+ if (!security || false === security.enabled) return response;
91
+ const headers = new Headers(response.headers);
92
+ const configuredHeaders = security.headers || {};
93
+ setHeaderIfEnabled(headers, 'referrer-policy', configuredHeaders.referrerPolicy);
94
+ setHeaderIfEnabled(headers, 'x-content-type-options', configuredHeaders.contentTypeOptions);
95
+ setHeaderIfEnabled(headers, 'permissions-policy', configuredHeaders.permissionsPolicy);
96
+ const csp = security.contentSecurityPolicy;
97
+ const cspHeader = csp?.mode === 'enforce' ? 'content-security-policy' : 'content-security-policy-report-only';
98
+ const cspValue = renderContentSecurityPolicy(csp?.directives);
99
+ if (isHtmlResponse(response) && csp?.mode !== 'off' && cspValue && !headers.has(cspHeader)) headers.set(cspHeader, cspValue);
100
+ if (shouldNoindex(request, security.noindex)) headers.set('x-robots-tag', 'noindex, nofollow');
101
+ return new Response(response.body, {
102
+ headers,
103
+ status: response.status,
104
+ statusText: response.statusText
105
+ });
106
+ }
107
+ function createRenderableRequest(request) {
108
+ if ('HEAD' !== request.method) return request;
109
+ return new Request(request, {
110
+ method: 'GET'
111
+ });
112
+ }
113
+ function finalizeResponseForRequest(response, request) {
114
+ const securedResponse = withCloudflareSecurityHeaders(response, request);
115
+ if ('HEAD' !== request.method) return securedResponse;
116
+ const headers = new Headers(securedResponse.headers);
117
+ headers.delete('content-length');
118
+ return new Response(null, {
119
+ headers,
120
+ status: securedResponse.status,
121
+ statusText: securedResponse.statusText
122
+ });
123
+ }
22
124
  function isFingerprintedAssetPathname(pathname) {
23
125
  return /(?:^|\/)[^/]+\.[a-f0-9]{8,}\.(?:css|js|mjs|json|svg|png|jpe?g|webp|avif|gif|woff2?|ttf)$/iu.test(pathname);
24
126
  }
25
127
  function withAssetHeaders(response, request) {
26
- const corsResponse = withCorsHeaders(response);
128
+ const corsResponse = withAssetCorsHeaders(response);
27
129
  const headers = new Headers(corsResponse.headers);
28
130
  const { pathname } = new URL(request.url);
29
131
  if (isFingerprintedAssetPathname(pathname)) headers.set('cache-control', 'public, max-age=31536000, immutable');
@@ -33,10 +135,30 @@ function withAssetHeaders(response, request) {
33
135
  statusText: corsResponse.statusText
34
136
  });
35
137
  }
36
- function createCorsPreflightResponse(request) {
138
+ async function createCorsPreflightResponse(request, env) {
37
139
  if ('OPTIONS' !== request.method) return null;
140
+ const allowedOrigin = getAllowedAppCorsOrigin(request);
141
+ if (allowedOrigin) {
142
+ const headers = new Headers({
143
+ 'access-control-allow-headers': APP_CORS_ALLOWED_HEADERS,
144
+ 'access-control-allow-methods': APP_CORS_ALLOWED_METHODS,
145
+ 'access-control-allow-origin': allowedOrigin
146
+ });
147
+ if ('*' !== allowedOrigin) headers.set('vary', 'origin');
148
+ return new Response(null, {
149
+ headers,
150
+ status: 204
151
+ });
152
+ }
153
+ if (!ASSET_CORS_ENABLED) return null;
154
+ const assets = env?.[ASSETS_BINDING];
155
+ if (!assets || 'function' != typeof assets.fetch) return null;
156
+ const assetResponse = await assets.fetch(new Request(request.url, {
157
+ method: 'HEAD'
158
+ }));
159
+ if (!assetResponse || 404 === assetResponse.status) return null;
38
160
  return new Response(null, {
39
- headers: CORS_HEADERS,
161
+ headers: ASSET_CORS_HEADERS,
40
162
  status: 204
41
163
  });
42
164
  }
@@ -417,22 +539,25 @@ async function dispatchBffRequest(request, env) {
417
539
  }
418
540
  export default {
419
541
  async fetch (request, env, ctx) {
420
- const corsPreflightResponse = createCorsPreflightResponse(request);
421
- if (corsPreflightResponse) return corsPreflightResponse;
542
+ const corsPreflightResponse = await createCorsPreflightResponse(request, env);
543
+ if (corsPreflightResponse) return finalizeResponseForRequest(corsPreflightResponse, request);
422
544
  const assetResponse = await fetchAsset(request, env);
423
- if (assetResponse) return assetResponse;
545
+ if (assetResponse) return finalizeResponseForRequest(assetResponse, request);
424
546
  const bffResponse = await dispatchBffRequest(request, env);
425
- if (bffResponse) return withCorsHeaders(bffResponse);
547
+ if (bffResponse) return finalizeResponseForRequest(withAppCorsHeaders(bffResponse, request), request);
426
548
  const route = findRoute(request);
427
549
  const { pathname } = new URL(request.url);
428
- if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return withCorsHeaders(new Response('Not found', {
550
+ if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return finalizeResponseForRequest(withAppCorsHeaders(new Response('Not found', {
429
551
  status: 404
430
- }));
431
- if (route?.worker) return withCorsHeaders(await dispatchRouteWorker(route, request, env, ctx));
552
+ }), request), request);
553
+ if (route?.worker) {
554
+ const renderableRequest = createRenderableRequest(request);
555
+ return finalizeResponseForRequest(withAppCorsHeaders(await dispatchRouteWorker(route, renderableRequest, env, ctx), request), request);
556
+ }
432
557
  const htmlResponse = await fetchRouteHtml(route, request, env);
433
- if (htmlResponse) return htmlResponse;
434
- return withCorsHeaders(new Response('Not found', {
558
+ if (htmlResponse) return finalizeResponseForRequest(htmlResponse, request);
559
+ return finalizeResponseForRequest(withAppCorsHeaders(new Response('Not found', {
435
560
  status: 404
436
- }));
561
+ }), request), request);
437
562
  }
438
563
  };
@@ -1,5 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
- import { ROUTE_SPEC_FILE, SERVER_DIR, fs, getMeta } from "@modern-js/utils";
2
+ import { pathToFileURL } from "node:url";
3
+ import { ROUTE_SPEC_FILE, SERVER_DIR, dynamicImport, fs, getMeta } from "@modern-js/utils";
3
4
  import path from "path";
4
5
  const normalizePath = (filePath)=>filePath.replace(/\\/g, '/');
5
6
  const getProjectUsage = (appDirectory, distDirectory, metaName)=>{
@@ -25,43 +26,17 @@ const getProjectUsage = (appDirectory, distDirectory, metaName)=>{
25
26
  };
26
27
  const getTemplatePath = (file)=>path.join(__dirname, '../platforms/templates', file);
27
28
  const readTemplate = async (file)=>(await fs.readFile(getTemplatePath(file))).toString();
28
- const localRequire = createRequire(path.join(__dirname, 'package.json'));
29
- const findNearestPackageJson = (resolvedEntry)=>{
30
- let currentDir = path.dirname(resolvedEntry);
31
- while(currentDir !== path.dirname(currentDir)){
32
- const manifestPath = path.join(currentDir, 'package.json');
33
- if (fs.existsSync(manifestPath)) return manifestPath;
34
- currentDir = path.dirname(currentDir);
35
- }
36
- };
37
- const splitPackageSpecifier = (entry)=>{
38
- const segments = entry.split('/');
39
- if (entry.startsWith('@')) {
40
- const [scope, name, ...rest] = segments;
41
- return {
42
- packageName: `${scope}/${name}`,
43
- exportKey: rest.length > 0 ? `./${rest.join('/')}` : '.'
44
- };
45
- }
46
- const [name, ...rest] = segments;
47
- return {
48
- packageName: name,
49
- exportKey: rest.length > 0 ? `./${rest.join('/')}` : '.'
50
- };
51
- };
52
29
  const resolveESMDependency = async (entry)=>{
30
+ const conditions = new Set([
31
+ 'node',
32
+ 'import',
33
+ 'module',
34
+ 'default'
35
+ ]);
53
36
  try {
54
- const { packageName, exportKey } = splitPackageSpecifier(entry);
55
- const resolvedEntry = localRequire.resolve(entry);
56
- const packageJsonPath = findNearestPackageJson(localRequire.resolve(packageName));
57
- if (!packageJsonPath) return normalizePath(resolvedEntry);
58
- const packageDir = path.dirname(packageJsonPath);
59
- const packageJson = fs.readJSONSync(packageJsonPath);
60
- const exportConfig = packageJson.exports?.[exportKey];
61
- if ('string' == typeof exportConfig) return normalizePath(path.join(packageDir, exportConfig));
62
- const esmExportPath = exportConfig?.node?.import || exportConfig?.import || exportConfig?.default;
63
- if ('string' == typeof esmExportPath) return normalizePath(path.join(packageDir, esmExportPath));
64
- return normalizePath(resolvedEntry);
37
+ const resolverPath = pathToFileURL(createRequire(__filename).resolve('import-meta-resolve')).href;
38
+ const { moduleResolve } = await dynamicImport(resolverPath);
39
+ return normalizePath(moduleResolve(entry, pathToFileURL(`${__dirname}/`), conditions, false).pathname.replace(/^\/(\w):/, '$1:'));
65
40
  } catch (err) {}
66
41
  };
67
42
  export { getProjectUsage, getTemplatePath, normalizePath, readTemplate, resolveESMDependency };
@@ -1,5 +1,5 @@
1
1
  import { ensureAbsolutePath, getPort, isDev, isDevCommand } from "@modern-js/utils";
2
- import { createDefaultConfig } from "../../config/index.mjs";
2
+ import { createDefaultConfig, isLazyCompilationSafeByDefault } from "../../config/index.mjs";
3
3
  const initialize = ()=>({
4
4
  name: '@modern-js/plugin-initialize',
5
5
  post: [
@@ -11,7 +11,16 @@ const initialize = ()=>({
11
11
  setup (api) {
12
12
  api.config(()=>{
13
13
  const appContext = api.getAppContext();
14
- return createDefaultConfig(appContext);
14
+ const userConfig = api.getConfig();
15
+ const defaultConfig = createDefaultConfig(appContext);
16
+ if (userConfig.dev?.lazyCompilation === void 0 && isLazyCompilationSafeByDefault(userConfig)) defaultConfig.dev = {
17
+ ...defaultConfig.dev,
18
+ lazyCompilation: {
19
+ imports: true,
20
+ entries: false
21
+ }
22
+ };
23
+ return defaultConfig;
15
24
  });
16
25
  api.modifyResolvedConfig(async (resolved)=>{
17
26
  let appContext = api.getAppContext();