@bleedingdev/modern-js-app-tools 3.5.0-ultramodern.30 → 3.5.0-ultramodern.31

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 (116) hide show
  1. package/dist/cjs/plugins/backend-federation/codegen.js +208 -0
  2. package/dist/cjs/plugins/backend-federation/config.js +217 -0
  3. package/dist/cjs/plugins/backend-federation/emit.js +139 -0
  4. package/dist/cjs/plugins/backendFederationBuild.js +4 -298
  5. package/dist/cjs/plugins/deploy/platforms/cloudflare/artifacts.js +127 -0
  6. package/dist/cjs/plugins/deploy/platforms/cloudflare/constants.js +137 -0
  7. package/dist/cjs/plugins/deploy/platforms/cloudflare/delivery-unit.js +118 -0
  8. package/dist/cjs/plugins/deploy/platforms/cloudflare/i18n-worker.js +135 -0
  9. package/dist/cjs/plugins/deploy/platforms/cloudflare/index.js +126 -0
  10. package/dist/cjs/plugins/deploy/platforms/cloudflare/security-policies.js +223 -0
  11. package/dist/cjs/plugins/deploy/platforms/cloudflare/types.js +18 -0
  12. package/dist/cjs/plugins/deploy/platforms/cloudflare/utils.js +66 -0
  13. package/dist/cjs/plugins/deploy/platforms/cloudflare/worker-manifest.js +178 -0
  14. package/dist/cjs/plugins/deploy/platforms/cloudflare/wrangler-config.js +189 -0
  15. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/identity.js +83 -0
  16. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/index.js +184 -0
  17. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/issues.js +54 -0
  18. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/manifest.js +83 -0
  19. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.js +158 -0
  20. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.js +137 -0
  21. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier.js +23 -363
  22. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +2 -745
  23. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  24. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  25. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  26. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  27. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  28. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  29. package/dist/esm/plugins/backend-federation/codegen.mjs +157 -0
  30. package/dist/esm/plugins/backend-federation/config.mjs +141 -0
  31. package/dist/esm/plugins/backend-federation/emit.mjs +88 -0
  32. package/dist/esm/plugins/backendFederationBuild.mjs +1 -296
  33. package/dist/esm/plugins/deploy/platforms/cloudflare/artifacts.mjs +64 -0
  34. package/dist/esm/plugins/deploy/platforms/cloudflare/constants.mjs +33 -0
  35. package/dist/esm/plugins/deploy/platforms/cloudflare/delivery-unit.mjs +67 -0
  36. package/dist/esm/plugins/deploy/platforms/cloudflare/i18n-worker.mjs +97 -0
  37. package/dist/esm/plugins/deploy/platforms/cloudflare/index.mjs +78 -0
  38. package/dist/esm/plugins/deploy/platforms/cloudflare/security-policies.mjs +167 -0
  39. package/dist/esm/plugins/deploy/platforms/cloudflare/types.mjs +0 -0
  40. package/dist/esm/plugins/deploy/platforms/cloudflare/utils.mjs +12 -0
  41. package/dist/esm/plugins/deploy/platforms/cloudflare/worker-manifest.mjs +118 -0
  42. package/dist/esm/plugins/deploy/platforms/cloudflare/wrangler-config.mjs +135 -0
  43. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/identity.mjs +45 -0
  44. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +129 -0
  45. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/issues.mjs +10 -0
  46. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/manifest.mjs +45 -0
  47. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.mjs +97 -0
  48. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +68 -0
  49. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier.mjs +1 -347
  50. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +1 -735
  51. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  52. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  53. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  54. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  55. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  56. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  57. package/dist/esm-node/plugins/backend-federation/codegen.mjs +158 -0
  58. package/dist/esm-node/plugins/backend-federation/config.mjs +142 -0
  59. package/dist/esm-node/plugins/backend-federation/emit.mjs +89 -0
  60. package/dist/esm-node/plugins/backendFederationBuild.mjs +1 -296
  61. package/dist/esm-node/plugins/deploy/platforms/cloudflare/artifacts.mjs +65 -0
  62. package/dist/esm-node/plugins/deploy/platforms/cloudflare/constants.mjs +34 -0
  63. package/dist/esm-node/plugins/deploy/platforms/cloudflare/delivery-unit.mjs +68 -0
  64. package/dist/esm-node/plugins/deploy/platforms/cloudflare/i18n-worker.mjs +98 -0
  65. package/dist/esm-node/plugins/deploy/platforms/cloudflare/index.mjs +79 -0
  66. package/dist/esm-node/plugins/deploy/platforms/cloudflare/security-policies.mjs +168 -0
  67. package/dist/esm-node/plugins/deploy/platforms/cloudflare/types.mjs +1 -0
  68. package/dist/esm-node/plugins/deploy/platforms/cloudflare/utils.mjs +13 -0
  69. package/dist/esm-node/plugins/deploy/platforms/cloudflare/worker-manifest.mjs +119 -0
  70. package/dist/esm-node/plugins/deploy/platforms/cloudflare/wrangler-config.mjs +136 -0
  71. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/identity.mjs +46 -0
  72. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +130 -0
  73. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/issues.mjs +11 -0
  74. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/manifest.mjs +46 -0
  75. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.mjs +98 -0
  76. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +69 -0
  77. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier.mjs +1 -347
  78. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +1 -735
  79. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  80. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  81. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  82. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  83. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  84. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  85. package/dist/types/plugins/backend-federation/codegen.d.ts +82 -0
  86. package/dist/types/plugins/backend-federation/config.d.ts +103 -0
  87. package/dist/types/plugins/backend-federation/emit.d.ts +13 -0
  88. package/dist/types/plugins/backendFederationBuild.d.ts +2 -11
  89. package/dist/types/plugins/deploy/platforms/cloudflare/artifacts.d.ts +15 -0
  90. package/dist/types/plugins/deploy/platforms/cloudflare/constants.d.ts +23 -0
  91. package/dist/types/plugins/deploy/platforms/cloudflare/delivery-unit.d.ts +23 -0
  92. package/dist/types/plugins/deploy/platforms/cloudflare/i18n-worker.d.ts +21 -0
  93. package/dist/types/plugins/deploy/platforms/cloudflare/index.d.ts +2 -0
  94. package/dist/types/plugins/deploy/platforms/cloudflare/security-policies.d.ts +88 -0
  95. package/dist/types/plugins/deploy/platforms/cloudflare/types.d.ts +5 -0
  96. package/dist/types/plugins/deploy/platforms/cloudflare/utils.d.ts +6 -0
  97. package/dist/types/plugins/deploy/platforms/cloudflare/worker-manifest.d.ts +100 -0
  98. package/dist/types/plugins/deploy/platforms/cloudflare/wrangler-config.d.ts +39 -0
  99. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/identity.d.ts +4 -0
  100. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/index.d.ts +18 -0
  101. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/issues.d.ts +14 -0
  102. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/manifest.d.ts +2 -0
  103. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.d.ts +13 -0
  104. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.d.ts +16 -0
  105. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier.d.ts +1 -32
  106. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +1 -2
  107. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.d.mts +1 -0
  108. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.d.mts +1 -0
  109. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.d.mts +1 -0
  110. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.d.mts +1 -0
  111. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.d.mts +1 -0
  112. package/package.json +11 -11
  113. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -879
  114. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -879
  115. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -879
  116. /package/dist/types/plugins/deploy/platforms/templates/{cloudflare-entry.d.mts → cloudflare-entry.006-fetch-handler.d.mts} +0 -0
@@ -1,735 +1 @@
1
- import node_path from "node:path";
2
- import { fs } from "@modern-js/utils";
3
- import { readTemplate } from "../utils/index.mjs";
4
- import { CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_OUTPUT_PACKAGE_FILE, CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY, CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_BUNDLE_FORMAT, CLOUDFLARE_WORKER_ENTRY, CLOUDFLARE_WRANGLER_CONFIG_FILE } from "./cloudflare-output-contract.mjs";
5
- import { createCloudflareOutputPlan } from "./cloudflare-output-plan.mjs";
6
- import { assertCloudflareOutput } from "./cloudflare-output-verifier.mjs";
7
- const WORKER_ENTRY = CLOUDFLARE_WORKER_ENTRY;
8
- const WRANGLER_CONFIG_FILE = CLOUDFLARE_WRANGLER_CONFIG_FILE;
9
- const OUTPUT_PACKAGE_FILE = CLOUDFLARE_OUTPUT_PACKAGE_FILE;
10
- const ASSETS_BINDING = CLOUDFLARE_ASSETS_BINDING;
11
- const ROUTE_SPEC_FILE = 'route.json';
12
- const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
13
- const LOADABLE_STATS_FILE = 'loadable-stats.json';
14
- const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
15
- const PUBLIC_ASSETS_DIRECTORY = CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY;
16
- const WORKER_BUNDLE_DIRECTORY = CLOUDFLARE_WORKER_BUNDLE_DIRECTORY;
17
- const SERVER_BUNDLE_DIRECTORY = 'bundles';
18
- const SERVER_OUTPUT_DIRECTORY = 'server';
19
- const DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES = [
20
- 'api',
21
- 'shared'
22
- ];
23
- const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
24
- const EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE = 'Ensure the Effect API entry exists at api/index.ts or bff.effect.entry, and import Cloudflare edge handlers from @modern-js/plugin-bff/effect-edge instead of lambda/Hono server helpers.';
25
- const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
26
- const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
27
- const REQUIRED_COMPATIBILITY_FLAGS = CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS;
28
- const RESERVED_ARTIFACT_DESTINATION_FILES = new Set([
29
- WRANGLER_CONFIG_FILE,
30
- OUTPUT_PACKAGE_FILE
31
- ]);
32
- const RESERVED_ARTIFACT_DESTINATION_DIRECTORIES = new Set([
33
- PUBLIC_ASSETS_DIRECTORY,
34
- SERVER_OUTPUT_DIRECTORY,
35
- WORKER_BUNDLE_DIRECTORY
36
- ]);
37
- const DEFAULT_SECURITY_HEADERS = {
38
- referrerPolicy: 'strict-origin-when-cross-origin',
39
- contentTypeOptions: 'nosniff',
40
- permissionsPolicy: 'camera=(), geolocation=(), microphone=(), payment=(), usb=()'
41
- };
42
- const DEFAULT_CORS_ALLOWED_METHODS = [
43
- 'GET',
44
- 'HEAD',
45
- 'POST',
46
- 'PUT',
47
- 'PATCH',
48
- 'DELETE',
49
- 'OPTIONS'
50
- ];
51
- const DEFAULT_CSP_DIRECTIVES = {
52
- 'base-uri': [
53
- "'self'"
54
- ],
55
- 'connect-src': [
56
- "'self'",
57
- 'https:',
58
- 'http:',
59
- 'wss:',
60
- 'ws:'
61
- ],
62
- 'default-src': [
63
- "'self'"
64
- ],
65
- 'font-src': [
66
- "'self'",
67
- 'data:',
68
- 'https:',
69
- 'http:'
70
- ],
71
- 'form-action': [
72
- "'self'"
73
- ],
74
- 'frame-ancestors': [
75
- "'self'"
76
- ],
77
- 'img-src': [
78
- "'self'",
79
- 'data:',
80
- 'blob:',
81
- 'https:',
82
- 'http:'
83
- ],
84
- 'manifest-src': [
85
- "'self'",
86
- 'https:',
87
- 'http:'
88
- ],
89
- 'object-src': [
90
- "'none'"
91
- ],
92
- "script-src": [
93
- "'self'",
94
- "'unsafe-inline'",
95
- "'unsafe-eval'",
96
- 'https:',
97
- 'http:',
98
- 'blob:'
99
- ],
100
- 'style-src': [
101
- "'self'",
102
- "'unsafe-inline'",
103
- 'https:',
104
- 'http:'
105
- ],
106
- 'worker-src': [
107
- "'self'",
108
- 'blob:'
109
- ]
110
- };
111
- const I18N_SERVER_PLUGIN_NAME = 'plugin-i18n/server';
112
- const DEFAULT_I18NEXT_DETECTION_OPTIONS = {
113
- order: [
114
- 'querystring',
115
- 'cookie',
116
- 'localStorage',
117
- 'header',
118
- 'navigator',
119
- 'htmlTag',
120
- 'path',
121
- 'subdomain'
122
- ],
123
- lookupQuerystring: 'lng',
124
- lookupCookie: 'i18next',
125
- lookupHeader: 'accept-language'
126
- };
127
- const SERVER_SIDE_I18N_DETECTORS = new Set([
128
- 'querystring',
129
- 'cookie',
130
- 'header'
131
- ]);
132
- const isRecord = (value)=>null !== value && 'object' == typeof value && !Array.isArray(value);
133
- const toStringArray = (value)=>Array.isArray(value) ? value.filter((entry)=>'string' == typeof entry) : [];
134
- const getI18nServerPlugin = (appContext)=>appContext.serverPlugins?.find((plugin)=>plugin.name.includes(I18N_SERVER_PLUGIN_NAME));
135
- const removeLocaleDetectionByEntry = (config)=>{
136
- const { localeDetectionByEntry: _localeDetectionByEntry, ...rest } = config;
137
- return rest;
138
- };
139
- const getEntryLocaleDetection = (entryName, localeDetection)=>{
140
- const byEntry = isRecord(localeDetection.localeDetectionByEntry) ? localeDetection.localeDetectionByEntry : void 0;
141
- const entryConfig = byEntry?.[entryName];
142
- const globalConfig = removeLocaleDetectionByEntry(localeDetection);
143
- return isRecord(entryConfig) ? {
144
- ...globalConfig,
145
- ...entryConfig
146
- } : globalConfig;
147
- };
148
- const normalizeI18nDetection = (detection)=>{
149
- const configured = isRecord(detection) ? detection : {};
150
- const rawOrder = Array.isArray(configured.order) ? configured.order : DEFAULT_I18NEXT_DETECTION_OPTIONS.order;
151
- const order = rawOrder.filter((entry)=>'string' == typeof entry && SERVER_SIDE_I18N_DETECTORS.has(entry));
152
- return {
153
- order: order.length > 0 ? order : [
154
- 'querystring',
155
- 'cookie',
156
- 'header'
157
- ],
158
- lookupQuerystring: 'string' == typeof configured.lookupQuerystring && configured.lookupQuerystring ? configured.lookupQuerystring : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupQuerystring,
159
- lookupCookie: 'string' == typeof configured.lookupCookie && configured.lookupCookie ? configured.lookupCookie : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupCookie,
160
- lookupHeader: 'string' == typeof configured.lookupHeader && configured.lookupHeader ? configured.lookupHeader : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupHeader
161
- };
162
- };
163
- const normalizeLocalisedUrls = (localisedUrls)=>{
164
- if (!isRecord(localisedUrls) || 0 === Object.keys(localisedUrls).length) return;
165
- const normalized = {};
166
- for (const [canonicalPath, languageMap] of Object.entries(localisedUrls)){
167
- if (!isRecord(languageMap)) continue;
168
- const normalizedLanguageMap = Object.fromEntries(Object.entries(languageMap).filter((entry)=>'string' == typeof entry[1] && entry[1].length > 0));
169
- if (Object.keys(normalizedLanguageMap).length > 0) normalized[canonicalPath] = normalizedLanguageMap;
170
- }
171
- return Object.keys(normalized).length > 0 ? normalized : void 0;
172
- };
173
- const normalizeWorkerI18nEntry = (entryName, localeDetection, staticRoutePrefixes)=>{
174
- const entryConfig = getEntryLocaleDetection(entryName, localeDetection);
175
- const languages = toStringArray(entryConfig.languages);
176
- if (true !== entryConfig.localePathRedirect || 0 === languages.length) return;
177
- const fallbackLanguage = 'string' == typeof entryConfig.fallbackLanguage && entryConfig.fallbackLanguage ? entryConfig.fallbackLanguage : 'en';
178
- const ignoreRedirectRoutes = Array.isArray(entryConfig.ignoreRedirectRoutes) ? toStringArray(entryConfig.ignoreRedirectRoutes) : [];
179
- const localisedUrls = normalizeLocalisedUrls(entryConfig.localisedUrls);
180
- return {
181
- i18nextDetector: false !== entryConfig.i18nextDetector,
182
- languages,
183
- fallbackLanguage,
184
- detection: normalizeI18nDetection(entryConfig.detection),
185
- ignoreRedirectRoutes,
186
- staticRoutePrefixes,
187
- ...localisedUrls ? {
188
- localisedUrls
189
- } : {}
190
- };
191
- };
192
- const createI18nWorkerManifest = (routeSpec, appContext)=>{
193
- const i18nServerPlugin = getI18nServerPlugin(appContext);
194
- const localeDetection = i18nServerPlugin?.options?.localeDetection;
195
- if (!isRecord(localeDetection)) return;
196
- const staticRoutePrefixes = toStringArray(i18nServerPlugin?.options?.staticRoutePrefixes);
197
- const entries = {};
198
- for (const route of routeSpec.routes){
199
- if ('string' != typeof route.entryName || entries[route.entryName]) continue;
200
- const entry = normalizeWorkerI18nEntry(route.entryName, localeDetection, staticRoutePrefixes);
201
- if (entry) entries[route.entryName] = entry;
202
- }
203
- return Object.keys(entries).length > 0 ? {
204
- entries
205
- } : void 0;
206
- };
207
- const getCompatibilityDate = (modernConfig)=>{
208
- const configuredDate = modernConfig.deploy?.worker?.compatibilityDate?.trim();
209
- const compatibilityDate = configuredDate || DEFAULT_COMPATIBILITY_DATE;
210
- if (!COMPATIBILITY_DATE_PATTERN.test(compatibilityDate)) throw new Error(`deploy.worker.compatibilityDate must use YYYY-MM-DD, received ${JSON.stringify(compatibilityDate)}.`);
211
- return compatibilityDate;
212
- };
213
- const getWorkerName = (appDirectory)=>{
214
- const basename = node_path.basename(appDirectory);
215
- return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
216
- };
217
- const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
218
- const configuredName = modernConfig.deploy?.worker?.name?.trim();
219
- return configuredName || getWorkerName(appDirectory);
220
- };
221
- const normalizeRelativePath = (value, label, scope = 'app output', options = {})=>{
222
- if ('string' != typeof value) throw new Error(`${label} must be a relative path inside the ${scope}.`);
223
- const normalized = value.trim().replace(/\\/g, '/').replace(/^\.\/+/u, '').replace(/\/+$/u, '');
224
- const segments = normalized.split('/');
225
- const isRootDestination = '.' === normalized;
226
- if (!normalized || node_path.isAbsolute(normalized) || !options.allowRoot && isRootDestination || segments.includes('..')) throw new Error(`${label} must be a relative path inside the ${scope}.`);
227
- return normalized;
228
- };
229
- const normalizeDirectiveValues = (value)=>{
230
- const values = Array.isArray(value) ? value : [
231
- value
232
- ];
233
- return [
234
- ...new Set(values.map((entry)=>entry.trim()).filter(Boolean))
235
- ];
236
- };
237
- const appendDirectiveValues = (directives, name, values)=>{
238
- if (!values?.length) return;
239
- directives[name] = normalizeDirectiveValues([
240
- ...directives[name] ?? [],
241
- ...values
242
- ]);
243
- };
244
- const createContentSecurityPolicy = (config)=>{
245
- const mode = config?.mode ?? 'report-only';
246
- if ('off' === mode) return {
247
- mode,
248
- directives: {},
249
- reason: config?.reason
250
- };
251
- const directives = Object.fromEntries(Object.entries(DEFAULT_CSP_DIRECTIVES).map(([name, values])=>[
252
- name,
253
- [
254
- ...values
255
- ]
256
- ]));
257
- for (const [name, value] of Object.entries(config?.directives ?? {}))if (false === value) delete directives[name];
258
- else directives[name] = normalizeDirectiveValues(value);
259
- if (config?.frameAncestors === false) delete directives['frame-ancestors'];
260
- else if (config?.frameAncestors) directives['frame-ancestors'] = normalizeDirectiveValues(config.frameAncestors);
261
- appendDirectiveValues(directives, "script-src", config?.additionalScriptSrc);
262
- appendDirectiveValues(directives, 'style-src', config?.additionalStyleSrc);
263
- appendDirectiveValues(directives, 'connect-src', config?.additionalConnectSrc);
264
- appendDirectiveValues(directives, 'img-src', config?.additionalImgSrc);
265
- if (config?.reportUri) directives['report-uri'] = [
266
- config.reportUri
267
- ];
268
- return {
269
- mode,
270
- directives,
271
- reason: config?.reason
272
- };
273
- };
274
- const createNoindexPolicy = (noindex)=>{
275
- if (false === noindex) return {
276
- workersDev: false,
277
- localhost: false,
278
- previewHostnames: []
279
- };
280
- if (true === noindex || void 0 === noindex) return {
281
- workersDev: true,
282
- localhost: true,
283
- previewHostnames: []
284
- };
285
- return {
286
- workersDev: noindex.workersDev ?? true,
287
- localhost: noindex.localhost ?? true,
288
- previewHostnames: noindex.previewHostnames ?? [],
289
- reason: noindex.reason
290
- };
291
- };
292
- const createCloudflareWorkerCorsPolicy = (cors)=>({
293
- assets: cors?.assets ?? true,
294
- allowedOrigins: normalizeDirectiveValues(cors?.allowedOrigins ?? []),
295
- allowedMethods: cors?.allowedMethods?.length ? normalizeDirectiveValues(cors.allowedMethods.map((method)=>method.toUpperCase())) : DEFAULT_CORS_ALLOWED_METHODS,
296
- allowedHeaders: cors?.allowedHeaders?.length ? normalizeDirectiveValues(cors.allowedHeaders) : [
297
- '*'
298
- ],
299
- reason: cors?.reason
300
- });
301
- const createCloudflareWorkerSecurityPolicy = (modernConfig)=>{
302
- const security = modernConfig.deploy?.worker?.security;
303
- if (security?.enabled === false) return {
304
- enabled: false,
305
- cors: createCloudflareWorkerCorsPolicy(security.cors),
306
- reason: security.reason
307
- };
308
- return {
309
- enabled: true,
310
- headers: {
311
- referrerPolicy: security?.headers?.referrerPolicy ?? DEFAULT_SECURITY_HEADERS.referrerPolicy,
312
- contentTypeOptions: security?.headers?.contentTypeOptions ?? DEFAULT_SECURITY_HEADERS.contentTypeOptions,
313
- permissionsPolicy: security?.headers?.permissionsPolicy ?? DEFAULT_SECURITY_HEADERS.permissionsPolicy
314
- },
315
- contentSecurityPolicy: createContentSecurityPolicy(security?.contentSecurityPolicy),
316
- noindex: createNoindexPolicy(security?.noindex),
317
- cors: createCloudflareWorkerCorsPolicy(security?.cors),
318
- reason: security?.reason
319
- };
320
- };
321
- const isJsonRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
322
- const getConfiguredWrangler = (modernConfig)=>{
323
- const wrangler = modernConfig.deploy?.worker?.wrangler;
324
- if (void 0 === wrangler) return {};
325
- if (!isJsonRecord(wrangler)) throw new Error('deploy.worker.wrangler must be a JSON object.');
326
- return wrangler;
327
- };
328
- const createWranglerCompatibilityFlags = (configuredFlags)=>{
329
- if (void 0 === configuredFlags) return [
330
- ...REQUIRED_COMPATIBILITY_FLAGS
331
- ];
332
- if (!Array.isArray(configuredFlags) || configuredFlags.some((flag)=>'string' != typeof flag)) throw new Error('deploy.worker.wrangler.compatibility_flags must be an array of strings.');
333
- return [
334
- ...new Set([
335
- ...configuredFlags,
336
- ...REQUIRED_COMPATIBILITY_FLAGS
337
- ])
338
- ];
339
- };
340
- const createWranglerAssetsConfig = (configuredAssets)=>{
341
- if (void 0 !== configuredAssets && !isJsonRecord(configuredAssets)) throw new Error('deploy.worker.wrangler.assets must be an object.');
342
- return {
343
- ...isJsonRecord(configuredAssets) ? configuredAssets : {},
344
- directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
345
- binding: ASSETS_BINDING,
346
- run_worker_first: true
347
- };
348
- };
349
- const assertNonEmptyString = (value, label)=>{
350
- if ('string' != typeof value || 0 === value.trim().length) throw new Error(`${label} must be a non-empty string.`);
351
- return value.trim();
352
- };
353
- const normalizeD1Database = (database, index)=>{
354
- const binding = assertNonEmptyString(database.binding, `deploy.worker.d1Databases[${index}].binding`);
355
- const databaseName = assertNonEmptyString(database.databaseName, `deploy.worker.d1Databases[${index}].databaseName`);
356
- const databaseId = assertNonEmptyString(database.databaseId, `deploy.worker.d1Databases[${index}].databaseId`);
357
- const migrationsDir = void 0 === database.migrationsDir ? void 0 : normalizeRelativePath(database.migrationsDir, `deploy.worker.d1Databases[${index}].migrationsDir`, 'app root');
358
- const previewDatabaseId = void 0 === database.previewDatabaseId ? void 0 : assertNonEmptyString(database.previewDatabaseId, `deploy.worker.d1Databases[${index}].previewDatabaseId`);
359
- return {
360
- binding,
361
- database_name: databaseName,
362
- database_id: databaseId,
363
- ...void 0 === migrationsDir ? {} : {
364
- migrations_dir: migrationsDir
365
- },
366
- ...void 0 === previewDatabaseId ? {} : {
367
- preview_database_id: previewDatabaseId
368
- },
369
- ...void 0 === database.remote ? {} : {
370
- remote: database.remote
371
- }
372
- };
373
- };
374
- const createWranglerD1Databases = (modernConfig, configuredWranglerD1)=>{
375
- const d1Databases = modernConfig.deploy?.worker?.d1Databases;
376
- if (void 0 === d1Databases) return configuredWranglerD1;
377
- if (void 0 !== configuredWranglerD1) throw new Error('Use deploy.worker.d1Databases or deploy.worker.wrangler.d1_databases, not both.');
378
- if (!Array.isArray(d1Databases)) throw new Error('deploy.worker.d1Databases must be an array.');
379
- return d1Databases.map(normalizeD1Database);
380
- };
381
- const normalizeServiceBinding = (service, index)=>{
382
- const binding = assertNonEmptyString(service.binding, `deploy.worker.services[${index}].binding`);
383
- const serviceName = assertNonEmptyString(service.service, `deploy.worker.services[${index}].service`);
384
- const prefix = void 0 === service.prefix ? void 0 : assertNonEmptyString(service.prefix, `deploy.worker.services[${index}].prefix`);
385
- return {
386
- binding,
387
- service: serviceName,
388
- ...void 0 === prefix ? {} : {
389
- prefix
390
- }
391
- };
392
- };
393
- const createWorkerServiceBindings = (modernConfig, configuredWranglerServices)=>{
394
- const services = modernConfig.deploy?.worker?.services;
395
- if (void 0 === services) return configuredWranglerServices;
396
- if (void 0 !== configuredWranglerServices) throw new Error('Use deploy.worker.services or deploy.worker.wrangler.services, not both.');
397
- if (!Array.isArray(services)) throw new Error('deploy.worker.services must be an array.');
398
- return services.map(normalizeServiceBinding);
399
- };
400
- const createWranglerServices = (serviceBindings)=>{
401
- if (!Array.isArray(serviceBindings)) return serviceBindings;
402
- if (!serviceBindings.every(isJsonRecord)) return serviceBindings;
403
- return serviceBindings.map((service)=>{
404
- const { prefix, ...wranglerService } = service;
405
- return wranglerService;
406
- });
407
- };
408
- const createWorkerManifestServiceBindings = (serviceBindings)=>{
409
- if (!Array.isArray(serviceBindings)) return;
410
- const dispatchBindings = serviceBindings.filter((service)=>isJsonRecord(service) && 'string' == typeof service.binding && 'string' == typeof service.service && 'string' == typeof service.prefix).map((service)=>({
411
- binding: service.binding,
412
- service: service.service,
413
- prefix: service.prefix,
414
- interface: 'fetch'
415
- }));
416
- return dispatchBindings.length > 0 ? dispatchBindings : void 0;
417
- };
418
- const createWranglerConfig = (appDirectory, modernConfig)=>{
419
- const wrangler = getConfiguredWrangler(modernConfig);
420
- const d1Databases = createWranglerD1Databases(modernConfig, wrangler.d1_databases);
421
- const serviceBindings = createWorkerServiceBindings(modernConfig, wrangler.services);
422
- const wranglerServices = createWranglerServices(serviceBindings);
423
- return {
424
- $schema: 'node_modules/wrangler/config-schema.json',
425
- name: getConfiguredWorkerName(appDirectory, modernConfig),
426
- compatibility_date: getCompatibilityDate(modernConfig),
427
- ...wrangler,
428
- main: WORKER_ENTRY,
429
- compatibility_flags: createWranglerCompatibilityFlags(wrangler.compatibility_flags),
430
- assets: createWranglerAssetsConfig(wrangler.assets),
431
- ...void 0 === d1Databases ? {} : {
432
- d1_databases: d1Databases
433
- },
434
- ...void 0 === wranglerServices ? {} : {
435
- services: wranglerServices
436
- }
437
- };
438
- };
439
- const normalizeCloudflareArtifact = (artifact, index)=>{
440
- const from = normalizeRelativePath(artifact.from, `deploy.worker.artifacts[${index}].from`, 'app root');
441
- const to = normalizeRelativePath(artifact.to, `deploy.worker.artifacts[${index}].to`, 'Cloudflare output');
442
- const [topLevelDestination] = to.split('/');
443
- const reservedDestination = RESERVED_ARTIFACT_DESTINATION_FILES.has(to) ? to : topLevelDestination;
444
- if (RESERVED_ARTIFACT_DESTINATION_FILES.has(to) || RESERVED_ARTIFACT_DESTINATION_DIRECTORIES.has(topLevelDestination)) throw new Error(`deploy.worker.artifacts[${index}].to must not target generated Cloudflare output path ${JSON.stringify(reservedDestination)}.`);
445
- return {
446
- from,
447
- to,
448
- index
449
- };
450
- };
451
- const getCloudflareArtifacts = (modernConfig)=>(modernConfig.deploy?.worker?.artifacts ?? []).map(normalizeCloudflareArtifact);
452
- const normalizeCloudflarePublicAsset = (asset, index)=>{
453
- const from = normalizeRelativePath(asset.from, `deploy.worker.publicAssets[${index}].from`, 'app root');
454
- const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output', {
455
- allowRoot: true
456
- });
457
- return {
458
- from,
459
- to,
460
- index
461
- };
462
- };
463
- const getCloudflarePublicAssets = (modernConfig)=>(modernConfig.deploy?.worker?.publicAssets ?? []).map(normalizeCloudflarePublicAsset);
464
- const copyCloudflareArtifacts = async (appDirectory, outputDirectory, artifacts)=>{
465
- for (const artifact of artifacts){
466
- const sourcePath = node_path.join(appDirectory, artifact.from);
467
- if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.artifacts[${artifact.index}].from does not exist: ${artifact.from}`);
468
- await fs.copy(sourcePath, node_path.join(outputDirectory, artifact.to));
469
- }
470
- };
471
- const copyCloudflarePublicAssets = async (appDirectory, publicDirectory, publicAssets)=>{
472
- for (const asset of publicAssets){
473
- const sourcePath = node_path.join(appDirectory, asset.from);
474
- if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.publicAssets[${asset.index}].from does not exist: ${asset.from}`);
475
- await fs.copy(sourcePath, node_path.join(publicDirectory, asset.to));
476
- }
477
- };
478
- const copyCloudflareD1Migrations = async (appDirectory, outputDirectory, modernConfig)=>{
479
- for (const [index, database] of (modernConfig.deploy?.worker?.d1Databases ?? []).entries()){
480
- if (!database.migrationsDir) continue;
481
- const migrationsDir = normalizeRelativePath(database.migrationsDir, `deploy.worker.d1Databases[${index}].migrationsDir`, 'app root');
482
- const sourcePath = node_path.join(appDirectory, migrationsDir);
483
- if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.d1Databases[${index}].migrationsDir does not exist: ${migrationsDir}`);
484
- await fs.copy(sourcePath, node_path.join(outputDirectory, migrationsDir));
485
- }
486
- };
487
- const readRouteSpec = async (outputDirectory)=>{
488
- const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
489
- if (!await fs.pathExists(routeSpecPath)) return {
490
- routes: []
491
- };
492
- const routeSpec = await fs.readJSON(routeSpecPath);
493
- return {
494
- ...routeSpec,
495
- routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
496
- };
497
- };
498
- const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
499
- const ULTRAMODERN_BUILD_MODULE = 'shared/ultramodern-build.ts';
500
- const nonEmptyString = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
501
- const toDeliveryUnitIdentity = (value)=>{
502
- if (!isRecord(value)) return;
503
- const unitId = nonEmptyString(value.unitId);
504
- const buildMarker = nonEmptyString(value.buildMarker);
505
- const sourceRevision = nonEmptyString(value.sourceRevision);
506
- if (!unitId || !buildMarker || !sourceRevision) return;
507
- return {
508
- unitId,
509
- buildMarker,
510
- sourceRevision
511
- };
512
- };
513
- const findWorkspaceRoot = async (appDirectory)=>{
514
- let current = node_path.resolve(appDirectory);
515
- for(;;){
516
- if (await fs.pathExists(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
517
- const parent = node_path.dirname(current);
518
- if (parent === current) return;
519
- current = parent;
520
- }
521
- };
522
- const resolveTopologyDeliveryUnit = async (appDirectory)=>{
523
- const workspaceRoot = await findWorkspaceRoot(appDirectory);
524
- if (!workspaceRoot) return;
525
- let compactConfig;
526
- try {
527
- compactConfig = await fs.readJSON(node_path.join(workspaceRoot, COMPACT_CONFIG_PATH));
528
- } catch {
529
- return;
530
- }
531
- if (!isRecord(compactConfig)) return;
532
- const topology = isRecord(compactConfig.topology) ? compactConfig.topology : void 0;
533
- const apps = Array.isArray(topology?.apps) ? topology.apps : [];
534
- const resolvedAppDirectory = node_path.resolve(appDirectory);
535
- for (const app of apps){
536
- if (!isRecord(app)) continue;
537
- const appPath = nonEmptyString(app.path);
538
- if (appPath && node_path.resolve(workspaceRoot, appPath.replace(/^\.\/+/u, '')) === resolvedAppDirectory) return toDeliveryUnitIdentity(app.deliveryUnit);
539
- }
540
- return toDeliveryUnitIdentity(compactConfig.deliveryUnit);
541
- };
542
- const resolveWorkerDeliveryUnitStamp = async (appDirectory)=>{
543
- const buildModulePath = node_path.join(appDirectory, ULTRAMODERN_BUILD_MODULE);
544
- if (!await fs.pathExists(buildModulePath)) return;
545
- const source = await fs.readFile(buildModulePath, 'utf8');
546
- const buildMarker = source.match(/\bbuild:\s*['"]([^'"]+)['"]/u)?.[1];
547
- const unitId = source.match(/\bunitId:\s*['"]([^'"]+)['"]/u)?.[1];
548
- const sourceRevision = source.match(/\bsourceRevision:\s*['"]([^'"]+)['"]/u)?.[1];
549
- if (!buildMarker || !unitId || !sourceRevision) return;
550
- const identity = {
551
- unitId,
552
- buildMarker,
553
- sourceRevision
554
- };
555
- return {
556
- ...identity,
557
- surfaces: {
558
- ui: {
559
- ...identity,
560
- surface: 'ui'
561
- },
562
- api: {
563
- ...identity,
564
- surface: 'api'
565
- }
566
- }
567
- };
568
- };
569
- const createMissingEffectBffWorkerError = (outputDirectory, worker)=>new Error(`Cloudflare Effect API runtime is configured, but the BFF worker bundle is missing: ${node_path.join(outputDirectory, worker)}. ${EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE}`);
570
- const createWorkerManifest = async (outputDirectory, modernConfig, appContext, deliveryUnitStamp)=>{
571
- const routeSpec = await readRouteSpec(outputDirectory);
572
- const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
573
- const worker = 'string' == typeof route.worker ? route.worker : void 0;
574
- return {
575
- urlPath: route.urlPath,
576
- entryName: route.entryName,
577
- entryPath: route.entryPath,
578
- isSSR: Boolean(route.isSSR),
579
- worker,
580
- workerExists: worker ? await fs.pathExists(node_path.join(outputDirectory, worker)) : false
581
- };
582
- }));
583
- const bffPrefix = modernConfig.bff?.prefix;
584
- const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
585
- const isEffectApi = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
586
- const effectApiWorkerExists = await fs.pathExists(node_path.join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
587
- const serviceBindings = createWorkerManifestServiceBindings(createWorkerServiceBindings(modernConfig, void 0));
588
- if (isEffectApi && primaryBffPrefix && !effectApiWorkerExists) throw createMissingEffectBffWorkerError(outputDirectory, BFF_EFFECT_WORKER_ENTRY);
589
- return {
590
- version: 1,
591
- runtime: {
592
- type: CLOUDFLARE_RUNTIME_TYPE,
593
- entry: WORKER_ENTRY,
594
- fetchExport: true,
595
- nodeListen: false
596
- },
597
- assets: {
598
- binding: ASSETS_BINDING,
599
- directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
600
- runWorkerFirst: true
601
- },
602
- routeSpec: {
603
- file: ROUTE_SPEC_OUTPUT,
604
- routes
605
- },
606
- workerBundles: {
607
- directory: WORKER_BUNDLE_DIRECTORY,
608
- format: CLOUDFLARE_WORKER_BUNDLE_FORMAT,
609
- importableFromModuleWorker: true,
610
- requestHandlerExport: 'requestHandler'
611
- },
612
- resources: {
613
- loadableStats: LOADABLE_STATS_FILE,
614
- routeManifest: ROUTE_MANIFEST_FILE
615
- },
616
- security: createCloudflareWorkerSecurityPolicy(modernConfig),
617
- ...deliveryUnitStamp ? {
618
- deliveryUnit: deliveryUnitStamp
619
- } : {},
620
- i18n: createI18nWorkerManifest(routeSpec, appContext),
621
- bff: isEffectApi && primaryBffPrefix && effectApiWorkerExists ? {
622
- runtimeFramework: 'effect',
623
- prefix: primaryBffPrefix,
624
- worker: BFF_EFFECT_WORKER_ENTRY
625
- } : void 0,
626
- ...void 0 === serviceBindings ? {} : {
627
- serviceBindings
628
- }
629
- };
630
- };
631
- const createWorkerModuleLoaders = (manifest)=>{
632
- const imports = new Map();
633
- for (const route of manifest.routeSpec.routes)if (route.worker && route.workerExists) {
634
- const importPath = `../${String(route.worker).replace(/^\/+/u, '')}`;
635
- imports.set(route.worker, `() => import(${JSON.stringify(importPath)})`);
636
- }
637
- if (manifest.bff?.worker) {
638
- const importPath = `../${String(manifest.bff.worker).replace(/^\/+/u, '')}`;
639
- imports.set(manifest.bff.worker, `() => import(${JSON.stringify(importPath)})`);
640
- }
641
- if (0 === imports.size) return '{}';
642
- const loaders = [
643
- ...imports.entries()
644
- ].map(([worker, loader])=>`${JSON.stringify(worker)}: ${loader}`);
645
- return `{\n${loaders.join(',\n')}\n}`;
646
- };
647
- const getPublicAssetExcludes = (appDirectory, modernConfig)=>[
648
- ...DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES.filter((directory)=>{
649
- try {
650
- return fs.statSync(node_path.join(appDirectory, directory)).isDirectory();
651
- } catch {
652
- return false;
653
- }
654
- }),
655
- ...modernConfig.deploy?.worker?.publicAssetExcludes ?? []
656
- ].map((entry)=>normalizeRelativePath(entry, 'deploy.worker.publicAssetExcludes'));
657
- const shouldCopyToPublicAssets = (src, distDirectory, publicAssetExcludes)=>{
658
- const relativePath = node_path.relative(distDirectory, src);
659
- if (!relativePath) return true;
660
- const normalizedRelativePath = relativePath.replace(/\\/g, '/');
661
- const [topLevelDirectory] = normalizedRelativePath.split('/');
662
- return normalizedRelativePath !== ROUTE_SPEC_FILE && topLevelDirectory !== WORKER_BUNDLE_DIRECTORY && topLevelDirectory !== SERVER_BUNDLE_DIRECTORY && !publicAssetExcludes.some((exclude)=>normalizedRelativePath === exclude || normalizedRelativePath.startsWith(`${exclude}/`));
663
- };
664
- const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
665
- const relativePath = node_path.relative(workerBundleDirectory, src);
666
- if (!relativePath) return true;
667
- const normalizedRelativePath = relativePath.replace(/\\/g, '/');
668
- const basename = node_path.basename(normalizedRelativePath);
669
- if (basename.startsWith('.') || normalizedRelativePath.includes('/.')) return false;
670
- if (fs.statSync(src).isDirectory()) return true;
671
- return [
672
- '.cjs',
673
- '.js',
674
- '.mjs'
675
- ].includes(node_path.extname(normalizedRelativePath));
676
- };
677
- const createCloudflarePreset = ({ appContext, modernConfig })=>{
678
- const { appDirectory, distDirectory } = appContext;
679
- const outputDirectory = node_path.join(appDirectory, '.output');
680
- const outputPlan = createCloudflareOutputPlan(outputDirectory);
681
- const publicDirectory = outputPlan.paths.publicAssets;
682
- const workerEntryPath = outputPlan.paths.workerEntry;
683
- const workerManifestPath = outputPlan.paths.workerManifest;
684
- const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
685
- const wranglerConfigPath = outputPlan.paths.wranglerConfig;
686
- const cloudflareArtifacts = getCloudflareArtifacts(modernConfig);
687
- const publicAssetExcludes = getPublicAssetExcludes(appDirectory, modernConfig);
688
- return {
689
- async prepare () {
690
- await fs.remove(outputDirectory);
691
- },
692
- async writeOutput () {
693
- await fs.copy(distDirectory, publicDirectory, {
694
- filter: (src)=>shouldCopyToPublicAssets(src, distDirectory, publicAssetExcludes)
695
- });
696
- await fs.ensureDir(node_path.dirname(workerEntryPath));
697
- await fs.ensureDir(node_path.dirname(workerManifestPath));
698
- const routeSpecSourcePath = node_path.join(distDirectory, ROUTE_SPEC_FILE);
699
- if (await fs.pathExists(routeSpecSourcePath)) await fs.copy(routeSpecSourcePath, routeSpecOutputPath);
700
- const workerBundleSourceDirectory = node_path.join(distDirectory, WORKER_BUNDLE_DIRECTORY);
701
- const workerBundleOutputDirectory = outputPlan.paths.workerBundle;
702
- if (await fs.pathExists(workerBundleSourceDirectory)) {
703
- await fs.copy(workerBundleSourceDirectory, workerBundleOutputDirectory, {
704
- filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
705
- });
706
- await fs.writeJSON(outputPlan.paths.workerPackage, outputPlan.packages.worker);
707
- }
708
- await copyCloudflareArtifacts(appDirectory, outputDirectory, cloudflareArtifacts);
709
- await copyCloudflarePublicAssets(appDirectory, publicDirectory, getCloudflarePublicAssets(modernConfig));
710
- await copyCloudflareD1Migrations(appDirectory, outputDirectory, modernConfig);
711
- await fs.writeJSON(wranglerConfigPath, createWranglerConfig(appDirectory, modernConfig), {
712
- spaces: 2
713
- });
714
- const deliveryUnitStamp = await resolveWorkerDeliveryUnitStamp(appDirectory);
715
- await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig, appContext, deliveryUnitStamp), {
716
- spaces: 2
717
- });
718
- await fs.writeJSON(outputPlan.paths.outputPackage, outputPlan.packages.output);
719
- },
720
- async genEntry () {
721
- const template = await readTemplate('cloudflare-entry.mjs');
722
- const manifest = await fs.readJSON(workerManifestPath);
723
- await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
724
- const topologyDeliveryUnit = await resolveTopologyDeliveryUnit(appDirectory);
725
- await assertCloudflareOutput({
726
- outputDirectory,
727
- importWorker: false,
728
- ...topologyDeliveryUnit ? {
729
- deliveryUnit: topologyDeliveryUnit
730
- } : {}
731
- });
732
- }
733
- };
734
- };
735
- export { createCloudflarePreset };
1
+ export { createCloudflarePreset } from "./cloudflare/index.mjs";