@astrojs/cloudflare 7.5.3 → 7.6.0

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.
package/dist/index.js CHANGED
@@ -1,431 +1,509 @@
1
- import { createRedirectsFromAstroRoutes } from "@astrojs/underscore-redirects";
2
- import { AstroError } from "astro/errors";
3
- import esbuild from "esbuild";
4
- import { Miniflare } from "miniflare";
5
- import * as fs from "node:fs";
6
- import * as os from "node:os";
7
- import { dirname, relative, sep } from "node:path";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
9
- import glob from "tiny-glob";
10
- import { getAdapter } from "./getAdapter.js";
11
- import { deduplicatePatterns } from "./utils/deduplicatePatterns.js";
12
- import { getCFObject } from "./utils/getCFObject.js";
13
- import {
14
- getD1Bindings,
15
- getDOBindings,
16
- getEnvVars,
17
- getKVBindings,
18
- getR2Bindings
19
- } from "./utils/parser.js";
20
- import { prependForwardSlash } from "./utils/prependForwardSlash.js";
21
- import { rewriteWasmImportPath } from "./utils/rewriteWasmImportPath.js";
22
- import { wasmModuleLoader } from "./utils/wasm-module-loader.js";
23
- function createIntegration(args) {
24
- let _config;
25
- let _buildConfig;
26
- let _mf;
27
- let _entryPoints = /* @__PURE__ */ new Map();
28
- const SERVER_BUILD_FOLDER = "/$server_build/";
29
- const isModeDirectory = args?.mode === "directory";
30
- const functionPerRoute = args?.functionPerRoute ?? false;
31
- const runtimeMode = args?.runtime ?? "off";
32
- return {
33
- name: "@astrojs/cloudflare",
34
- hooks: {
35
- "astro:config:setup": ({ config, updateConfig }) => {
36
- updateConfig({
37
- build: {
38
- client: new URL(`.${config.base}`, config.outDir),
39
- server: new URL(`.${SERVER_BUILD_FOLDER}`, config.outDir),
40
- serverEntry: "_worker.mjs",
41
- redirects: false
42
- },
43
- vite: {
44
- // load .wasm files as WebAssembly modules
45
- plugins: [
46
- wasmModuleLoader({
47
- disabled: !args?.wasmModuleImports,
48
- assetsDirectory: config.build.assets
49
- })
50
- ]
51
- }
52
- });
53
- },
54
- "astro:config:done": ({ setAdapter, config }) => {
55
- setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
56
- _config = config;
57
- _buildConfig = config.build;
58
- if (_config.output === "static") {
59
- throw new AstroError(
60
- '[@astrojs/cloudflare] `output: "server"` or `output: "hybrid"` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.'
61
- );
62
- }
63
- if (_config.base === SERVER_BUILD_FOLDER) {
64
- throw new AstroError(
65
- '[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.'
66
- );
67
- }
68
- },
69
- "astro:server:setup": ({ server }) => {
70
- if (runtimeMode !== "off") {
71
- server.middlewares.use(async function middleware(req, res, next) {
72
- try {
73
- const cf = await getCFObject(runtimeMode);
74
- const vars = await getEnvVars();
75
- const D1Bindings = await getD1Bindings();
76
- const R2Bindings = await getR2Bindings();
77
- const KVBindings = await getKVBindings();
78
- const DOBindings = await getDOBindings();
79
- let bindingsEnv = new Object({});
80
- const originalPWD = process.env.PWD;
81
- process.env.PWD = process.cwd();
82
- _mf = new Miniflare({
83
- modules: true,
84
- script: "",
85
- cache: true,
86
- cachePersist: true,
87
- cacheWarnUsage: true,
88
- d1Databases: D1Bindings,
89
- d1Persist: true,
90
- r2Buckets: R2Bindings,
91
- r2Persist: true,
92
- kvNamespaces: KVBindings,
93
- kvPersist: true,
94
- durableObjects: DOBindings,
95
- durableObjectsPersist: true
96
- });
97
- await _mf.ready;
98
- for (const D1Binding of D1Bindings) {
99
- const db = await _mf.getD1Database(D1Binding);
100
- Reflect.set(bindingsEnv, D1Binding, db);
101
- }
102
- for (const R2Binding of R2Bindings) {
103
- const bucket = await _mf.getR2Bucket(R2Binding);
104
- Reflect.set(bindingsEnv, R2Binding, bucket);
105
- }
106
- for (const KVBinding of KVBindings) {
107
- const namespace = await _mf.getKVNamespace(KVBinding);
108
- Reflect.set(bindingsEnv, KVBinding, namespace);
109
- }
110
- for (const key in DOBindings) {
111
- if (Object.prototype.hasOwnProperty.call(DOBindings, key)) {
112
- const DO = await _mf.getDurableObjectNamespace(key);
113
- Reflect.set(bindingsEnv, key, DO);
1
+ import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
2
+ import { AstroError } from 'astro/errors';
3
+ import esbuild from 'esbuild';
4
+ import { Miniflare } from 'miniflare';
5
+ import * as fs from 'node:fs';
6
+ import * as os from 'node:os';
7
+ import { dirname, relative, sep } from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+ import glob from 'tiny-glob';
10
+ import { getAdapter } from './getAdapter.js';
11
+ import { deduplicatePatterns } from './utils/deduplicatePatterns.js';
12
+ import { getCFObject } from './utils/getCFObject.js';
13
+ import { getD1Bindings, getDOBindings, getEnvVars, getKVBindings, getR2Bindings, } from './utils/parser.js';
14
+ import { prependForwardSlash } from './utils/prependForwardSlash.js';
15
+ import { rewriteWasmImportPath } from './utils/rewriteWasmImportPath.js';
16
+ import { wasmModuleLoader } from './utils/wasm-module-loader.js';
17
+ const RUNTIME_WARNING = `You are using a deprecated string format for the \`runtime\` API. Please update to the current format for better support.
18
+
19
+ Example:
20
+ Old Format: 'local'
21
+ Current Format: { mode: 'local', persistTo: '.wrangler/state/v3' }
22
+
23
+ Please refer to our runtime documentation for more details on the format. https://docs.astro.build/en/guides/integrations-guide/cloudflare/#runtime`;
24
+ export default function createIntegration(args) {
25
+ let _config;
26
+ let _buildConfig;
27
+ let _mf;
28
+ let _entryPoints = new Map();
29
+ const SERVER_BUILD_FOLDER = '/$server_build/';
30
+ const isModeDirectory = args?.mode === 'directory';
31
+ const functionPerRoute = args?.functionPerRoute ?? false;
32
+ let runtimeMode = { mode: 'off' };
33
+ if (args?.runtime === 'remote') {
34
+ runtimeMode = { mode: 'remote' };
35
+ }
36
+ else if (args?.runtime === 'local') {
37
+ runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
38
+ }
39
+ else if (typeof args?.runtime === 'object' &&
40
+ args?.runtime.mode === 'local' &&
41
+ args.runtime.persistTo === undefined) {
42
+ runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
43
+ }
44
+ else {
45
+ runtimeMode = args?.runtime;
46
+ }
47
+ return {
48
+ name: '@astrojs/cloudflare',
49
+ hooks: {
50
+ 'astro:config:setup': ({ config, updateConfig }) => {
51
+ updateConfig({
52
+ build: {
53
+ client: new URL(`.${config.base}`, config.outDir),
54
+ server: new URL(`.${SERVER_BUILD_FOLDER}`, config.outDir),
55
+ serverEntry: '_worker.mjs',
56
+ redirects: false,
57
+ },
58
+ vite: {
59
+ // load .wasm files as WebAssembly modules
60
+ plugins: [
61
+ wasmModuleLoader({
62
+ disabled: !args?.wasmModuleImports,
63
+ assetsDirectory: config.build.assets,
64
+ }),
65
+ ],
66
+ },
67
+ });
68
+ },
69
+ 'astro:config:done': ({ setAdapter, config, logger }) => {
70
+ setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
71
+ _config = config;
72
+ _buildConfig = config.build;
73
+ if (_config.output === 'static') {
74
+ throw new AstroError('[@astrojs/cloudflare] `output: "server"` or `output: "hybrid"` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.');
75
+ }
76
+ if (_config.base === SERVER_BUILD_FOLDER) {
77
+ throw new AstroError('[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.');
78
+ }
79
+ if (typeof args?.runtime === 'string') {
80
+ logger.warn(RUNTIME_WARNING);
81
+ }
82
+ },
83
+ 'astro:server:setup': ({ server }) => {
84
+ if (runtimeMode.mode === 'local') {
85
+ const typedRuntimeMode = runtimeMode;
86
+ server.middlewares.use(async function middleware(req, res, next) {
87
+ try {
88
+ const cf = await getCFObject(typedRuntimeMode.mode);
89
+ const vars = await getEnvVars();
90
+ const D1Bindings = await getD1Bindings();
91
+ const R2Bindings = await getR2Bindings();
92
+ const KVBindings = await getKVBindings();
93
+ const DOBindings = await getDOBindings();
94
+ let bindingsEnv = new Object({});
95
+ // fix for the error "kj/filesystem-disk-unix.c++:1709: warning: PWD environment variable doesn't match current directory."
96
+ // note: This mismatch might be primarily due to the test runner.
97
+ const originalPWD = process.env.PWD;
98
+ process.env.PWD = process.cwd();
99
+ _mf = new Miniflare({
100
+ modules: true,
101
+ script: '',
102
+ cache: true,
103
+ cachePersist: true,
104
+ cacheWarnUsage: true,
105
+ d1Databases: D1Bindings,
106
+ d1Persist: `${typedRuntimeMode.persistTo}/d1`,
107
+ r2Buckets: R2Bindings,
108
+ r2Persist: `${typedRuntimeMode.persistTo}/r2`,
109
+ kvNamespaces: KVBindings,
110
+ kvPersist: `${typedRuntimeMode.persistTo}/kv`,
111
+ durableObjects: DOBindings,
112
+ durableObjectsPersist: `${typedRuntimeMode.persistTo}/do`,
113
+ });
114
+ await _mf.ready;
115
+ for (const D1Binding of D1Bindings) {
116
+ const db = await _mf.getD1Database(D1Binding);
117
+ Reflect.set(bindingsEnv, D1Binding, db);
118
+ }
119
+ for (const R2Binding of R2Bindings) {
120
+ const bucket = await _mf.getR2Bucket(R2Binding);
121
+ Reflect.set(bindingsEnv, R2Binding, bucket);
122
+ }
123
+ for (const KVBinding of KVBindings) {
124
+ const namespace = await _mf.getKVNamespace(KVBinding);
125
+ Reflect.set(bindingsEnv, KVBinding, namespace);
126
+ }
127
+ for (const key in DOBindings) {
128
+ if (Object.prototype.hasOwnProperty.call(DOBindings, key)) {
129
+ const DO = await _mf.getDurableObjectNamespace(key);
130
+ Reflect.set(bindingsEnv, key, DO);
131
+ }
132
+ }
133
+ const mfCache = await _mf.getCaches();
134
+ process.env.PWD = originalPWD;
135
+ const clientLocalsSymbol = Symbol.for('astro.locals');
136
+ Reflect.set(req, clientLocalsSymbol, {
137
+ runtime: {
138
+ env: {
139
+ // default binding for static assets will be dynamic once we support mocking of bindings
140
+ ASSETS: {},
141
+ // this is just a VAR for CF to change build behavior, on dev it should be 0
142
+ CF_PAGES: '0',
143
+ // will be fetched from git dynamically once we support mocking of bindings
144
+ CF_PAGES_BRANCH: 'TBA',
145
+ // will be fetched from git dynamically once we support mocking of bindings
146
+ CF_PAGES_COMMIT_SHA: 'TBA',
147
+ CF_PAGES_URL: `http://${req.headers.host}`,
148
+ ...bindingsEnv,
149
+ ...vars,
150
+ },
151
+ cf: cf,
152
+ waitUntil: (_promise) => {
153
+ return;
154
+ },
155
+ caches: mfCache,
156
+ },
157
+ });
158
+ next();
159
+ }
160
+ catch {
161
+ next();
162
+ }
163
+ });
164
+ }
165
+ },
166
+ 'astro:server:done': async ({ logger }) => {
167
+ if (_mf) {
168
+ logger.info('Cleaning up the Miniflare instance, and shutting down the workerd server.');
169
+ await _mf.dispose();
114
170
  }
115
- }
116
- const mfCache = await _mf.getCaches();
117
- process.env.PWD = originalPWD;
118
- const clientLocalsSymbol = Symbol.for("astro.locals");
119
- Reflect.set(req, clientLocalsSymbol, {
120
- runtime: {
121
- env: {
122
- // default binding for static assets will be dynamic once we support mocking of bindings
123
- ASSETS: {},
124
- // this is just a VAR for CF to change build behavior, on dev it should be 0
125
- CF_PAGES: "0",
126
- // will be fetched from git dynamically once we support mocking of bindings
127
- CF_PAGES_BRANCH: "TBA",
128
- // will be fetched from git dynamically once we support mocking of bindings
129
- CF_PAGES_COMMIT_SHA: "TBA",
130
- CF_PAGES_URL: `http://${req.headers.host}`,
131
- ...bindingsEnv,
132
- ...vars
133
- },
134
- cf,
135
- waitUntil: (_promise) => {
136
- return;
137
- },
138
- caches: mfCache
171
+ },
172
+ 'astro:build:setup': ({ vite, target }) => {
173
+ if (target === 'server') {
174
+ vite.resolve ||= {};
175
+ vite.resolve.alias ||= {};
176
+ const aliases = [
177
+ {
178
+ find: 'react-dom/server',
179
+ replacement: 'react-dom/server.browser',
180
+ },
181
+ ];
182
+ if (Array.isArray(vite.resolve.alias)) {
183
+ vite.resolve.alias = [...vite.resolve.alias, ...aliases];
184
+ }
185
+ else {
186
+ for (const alias of aliases) {
187
+ vite.resolve.alias[alias.find] = alias.replacement;
188
+ }
189
+ }
190
+ vite.ssr ||= {};
191
+ vite.ssr.target = 'webworker';
192
+ // Cloudflare env is only available per request. This isn't feasible for code that access env vars
193
+ // in a global way, so we shim their access as `process.env.*`. We will populate `process.env` later
194
+ // in its fetch handler.
195
+ vite.define = {
196
+ 'process.env': 'process.env',
197
+ ...vite.define,
198
+ };
199
+ }
200
+ },
201
+ 'astro:build:ssr': ({ entryPoints }) => {
202
+ _entryPoints = entryPoints;
203
+ },
204
+ 'astro:build:done': async ({ pages, routes, dir }) => {
205
+ const functionsUrl = new URL('functions/', _config.root);
206
+ const assetsUrl = new URL(_buildConfig.assets, _buildConfig.client);
207
+ if (isModeDirectory) {
208
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
139
209
  }
140
- });
141
- next();
142
- } catch {
143
- next();
144
- }
145
- });
146
- }
147
- },
148
- "astro:server:done": async ({ logger }) => {
149
- if (_mf) {
150
- logger.info("Cleaning up the Miniflare instance, and shutting down the workerd server.");
151
- await _mf.dispose();
152
- }
153
- },
154
- "astro:build:setup": ({ vite, target }) => {
155
- if (target === "server") {
156
- vite.resolve ||= {};
157
- vite.resolve.alias ||= {};
158
- const aliases = [{ find: "react-dom/server", replacement: "react-dom/server.browser" }];
159
- if (Array.isArray(vite.resolve.alias)) {
160
- vite.resolve.alias = [...vite.resolve.alias, ...aliases];
161
- } else {
162
- for (const alias of aliases) {
163
- vite.resolve.alias[alias.find] = alias.replacement;
164
- }
165
- }
166
- vite.ssr ||= {};
167
- vite.ssr.target = "webworker";
168
- vite.define = {
169
- "process.env": "process.env",
170
- ...vite.define
171
- };
172
- }
173
- },
174
- "astro:build:ssr": ({ entryPoints }) => {
175
- _entryPoints = entryPoints;
176
- },
177
- "astro:build:done": async ({ pages, routes, dir }) => {
178
- const functionsUrl = new URL("functions/", _config.root);
179
- const assetsUrl = new URL(_buildConfig.assets, _buildConfig.client);
180
- if (isModeDirectory) {
181
- await fs.promises.mkdir(functionsUrl, { recursive: true });
182
- }
183
- if (isModeDirectory && (_buildConfig.split || functionPerRoute)) {
184
- const entryPointsURL = [..._entryPoints.values()];
185
- const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
186
- const outputUrl = new URL("$astro", _buildConfig.server);
187
- const outputDir = fileURLToPath(outputUrl);
188
- const entryPathsGroupedByDepth = !args.wasmModuleImports ? [entryPaths] : entryPaths.reduce((sum, thisPath) => {
189
- const depthFromRoot = thisPath.split(sep).length;
190
- sum.set(depthFromRoot, (sum.get(depthFromRoot) || []).concat(thisPath));
191
- return sum;
192
- }, /* @__PURE__ */ new Map()).values();
193
- for (const pathsGroup of entryPathsGroupedByDepth) {
194
- const pagesDirname = relative(fileURLToPath(_buildConfig.server), pathsGroup[0]).split(
195
- sep
196
- )[0];
197
- const absolutePagesDirname = fileURLToPath(new URL(pagesDirname, _buildConfig.server));
198
- const urlWithinFunctions = new URL(
199
- relative(absolutePagesDirname, pathsGroup[0]),
200
- functionsUrl
201
- );
202
- const relativePathToAssets = relative(
203
- dirname(fileURLToPath(urlWithinFunctions)),
204
- fileURLToPath(assetsUrl)
205
- );
206
- await esbuild.build({
207
- target: "es2022",
208
- platform: "browser",
209
- conditions: ["workerd", "worker", "browser"],
210
- external: [
211
- "node:assert",
212
- "node:async_hooks",
213
- "node:buffer",
214
- "node:crypto",
215
- "node:diagnostics_channel",
216
- "node:events",
217
- "node:path",
218
- "node:process",
219
- "node:stream",
220
- "node:string_decoder",
221
- "node:util",
222
- "cloudflare:*"
223
- ],
224
- entryPoints: pathsGroup,
225
- outbase: absolutePagesDirname,
226
- outdir: outputDir,
227
- allowOverwrite: true,
228
- format: "esm",
229
- bundle: true,
230
- minify: _config.vite?.build?.minify !== false,
231
- banner: {
232
- js: `globalThis.process = {
210
+ // TODO: remove _buildConfig.split in Astro 4.0
211
+ if (isModeDirectory && (_buildConfig.split || functionPerRoute)) {
212
+ const entryPointsURL = [..._entryPoints.values()];
213
+ const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
214
+ const outputUrl = new URL('$astro', _buildConfig.server);
215
+ const outputDir = fileURLToPath(outputUrl);
216
+ //
217
+ // Sadly, when wasmModuleImports is enabled, this needs to build esbuild for each depth of routes/entrypoints
218
+ // independently so that relative import paths to the assets are the correct depth of '../' traversals
219
+ // This is inefficient, so wasmModuleImports is opt-in. This could potentially be improved in the future by
220
+ // taking advantage of the esbuild "onEnd" hook to rewrite import code per entry point relative to where the final
221
+ // destination of the entrypoint is
222
+ const entryPathsGroupedByDepth = !args.wasmModuleImports
223
+ ? [entryPaths]
224
+ : entryPaths
225
+ .reduce((sum, thisPath) => {
226
+ const depthFromRoot = thisPath.split(sep).length;
227
+ sum.set(depthFromRoot, (sum.get(depthFromRoot) || []).concat(thisPath));
228
+ return sum;
229
+ }, new Map())
230
+ .values();
231
+ for (const pathsGroup of entryPathsGroupedByDepth) {
232
+ // for some reason this exports to "entry.pages" on windows instead of "pages" on unix environments.
233
+ // This deduces the name of the "pages" build directory
234
+ const pagesDirname = relative(fileURLToPath(_buildConfig.server), pathsGroup[0]).split(sep)[0];
235
+ const absolutePagesDirname = fileURLToPath(new URL(pagesDirname, _buildConfig.server));
236
+ const urlWithinFunctions = new URL(relative(absolutePagesDirname, pathsGroup[0]), functionsUrl);
237
+ const relativePathToAssets = relative(dirname(fileURLToPath(urlWithinFunctions)), fileURLToPath(assetsUrl));
238
+ await esbuild.build({
239
+ target: 'es2022',
240
+ platform: 'browser',
241
+ conditions: ['workerd', 'worker', 'browser'],
242
+ external: [
243
+ 'node:assert',
244
+ 'node:async_hooks',
245
+ 'node:buffer',
246
+ 'node:crypto',
247
+ 'node:diagnostics_channel',
248
+ 'node:events',
249
+ 'node:path',
250
+ 'node:process',
251
+ 'node:stream',
252
+ 'node:string_decoder',
253
+ 'node:util',
254
+ 'cloudflare:*',
255
+ ],
256
+ entryPoints: pathsGroup,
257
+ outbase: absolutePagesDirname,
258
+ outdir: outputDir,
259
+ allowOverwrite: true,
260
+ format: 'esm',
261
+ bundle: true,
262
+ minify: _config.vite?.build?.minify !== false,
263
+ banner: {
264
+ js: `globalThis.process = {
233
265
  argv: [],
234
266
  env: {},
235
- };`
236
- },
237
- logOverride: {
238
- "ignored-bare-import": "silent"
239
- },
240
- plugins: !args?.wasmModuleImports ? [] : [rewriteWasmImportPath({ relativePathToAssets })]
241
- });
242
- }
243
- const outputFiles = await glob(`**/*`, {
244
- cwd: outputDir,
245
- filesOnly: true
246
- });
247
- for (const outputFile of outputFiles) {
248
- const path = outputFile.split(sep);
249
- const finalSegments = path.map(
250
- (segment) => segment.replace(/(\_)(\w+)(\_)/g, (_, __, prop) => {
251
- return `[${prop}]`;
252
- }).replace(/(\_\-\-\-)(\w+)(\_)/g, (_, __, prop) => {
253
- return `[[${prop}]]`;
254
- })
255
- );
256
- finalSegments[finalSegments.length - 1] = finalSegments[finalSegments.length - 1].replace("entry.", "").replace(/(.*)\.(\w+)\.(\w+)$/g, (_, fileName, __, newExt) => {
257
- return `${fileName}.${newExt}`;
258
- });
259
- const finalDirPath = finalSegments.slice(0, -1).join(sep);
260
- const finalPath = finalSegments.join(sep);
261
- const newDirUrl = new URL(finalDirPath, functionsUrl);
262
- await fs.promises.mkdir(newDirUrl, { recursive: true });
263
- const oldFileUrl = new URL(`$astro/${outputFile}`, outputUrl);
264
- const newFileUrl = new URL(finalPath, functionsUrl);
265
- await fs.promises.rename(oldFileUrl, newFileUrl);
266
- }
267
- } else {
268
- const entryPath = fileURLToPath(new URL(_buildConfig.serverEntry, _buildConfig.server));
269
- const entryUrl = new URL(_buildConfig.serverEntry, _config.outDir);
270
- const buildPath = fileURLToPath(entryUrl);
271
- const finalBuildUrl = pathToFileURL(buildPath.replace(/\.mjs$/, ".js"));
272
- await esbuild.build({
273
- target: "es2022",
274
- platform: "browser",
275
- conditions: ["workerd", "worker", "browser"],
276
- external: [
277
- "node:assert",
278
- "node:async_hooks",
279
- "node:buffer",
280
- "node:crypto",
281
- "node:diagnostics_channel",
282
- "node:events",
283
- "node:path",
284
- "node:process",
285
- "node:stream",
286
- "node:string_decoder",
287
- "node:util",
288
- "cloudflare:*"
289
- ],
290
- entryPoints: [entryPath],
291
- outfile: buildPath,
292
- allowOverwrite: true,
293
- format: "esm",
294
- bundle: true,
295
- minify: _config.vite?.build?.minify !== false,
296
- banner: {
297
- js: `globalThis.process = {
267
+ };`,
268
+ },
269
+ logOverride: {
270
+ 'ignored-bare-import': 'silent',
271
+ },
272
+ plugins: !args?.wasmModuleImports
273
+ ? []
274
+ : [rewriteWasmImportPath({ relativePathToAssets })],
275
+ });
276
+ }
277
+ const outputFiles = await glob(`**/*`, {
278
+ cwd: outputDir,
279
+ filesOnly: true,
280
+ });
281
+ // move the files into the functions folder
282
+ // & make sure the file names match Cloudflare syntax for routing
283
+ for (const outputFile of outputFiles) {
284
+ const path = outputFile.split(sep);
285
+ const finalSegments = path.map((segment) => segment
286
+ .replace(/(\_)(\w+)(\_)/g, (_, __, prop) => {
287
+ return `[${prop}]`;
288
+ })
289
+ .replace(/(\_\-\-\-)(\w+)(\_)/g, (_, __, prop) => {
290
+ return `[[${prop}]]`;
291
+ }));
292
+ finalSegments[finalSegments.length - 1] = finalSegments[finalSegments.length - 1]
293
+ .replace('entry.', '')
294
+ .replace(/(.*)\.(\w+)\.(\w+)$/g, (_, fileName, __, newExt) => {
295
+ return `${fileName}.${newExt}`;
296
+ });
297
+ const finalDirPath = finalSegments.slice(0, -1).join(sep);
298
+ const finalPath = finalSegments.join(sep);
299
+ const newDirUrl = new URL(finalDirPath, functionsUrl);
300
+ await fs.promises.mkdir(newDirUrl, { recursive: true });
301
+ const oldFileUrl = new URL(`$astro/${outputFile}`, outputUrl);
302
+ const newFileUrl = new URL(finalPath, functionsUrl);
303
+ await fs.promises.rename(oldFileUrl, newFileUrl);
304
+ }
305
+ }
306
+ else {
307
+ const entryPath = fileURLToPath(new URL(_buildConfig.serverEntry, _buildConfig.server));
308
+ const entryUrl = new URL(_buildConfig.serverEntry, _config.outDir);
309
+ const buildPath = fileURLToPath(entryUrl);
310
+ // A URL for the final build path after renaming
311
+ const finalBuildUrl = pathToFileURL(buildPath.replace(/\.mjs$/, '.js'));
312
+ await esbuild.build({
313
+ target: 'es2022',
314
+ platform: 'browser',
315
+ conditions: ['workerd', 'worker', 'browser'],
316
+ external: [
317
+ 'node:assert',
318
+ 'node:async_hooks',
319
+ 'node:buffer',
320
+ 'node:crypto',
321
+ 'node:diagnostics_channel',
322
+ 'node:events',
323
+ 'node:path',
324
+ 'node:process',
325
+ 'node:stream',
326
+ 'node:string_decoder',
327
+ 'node:util',
328
+ 'cloudflare:*',
329
+ ],
330
+ entryPoints: [entryPath],
331
+ outfile: buildPath,
332
+ allowOverwrite: true,
333
+ format: 'esm',
334
+ bundle: true,
335
+ minify: _config.vite?.build?.minify !== false,
336
+ banner: {
337
+ js: `globalThis.process = {
298
338
  argv: [],
299
339
  env: {},
300
- };`
301
- },
302
- logOverride: {
303
- "ignored-bare-import": "silent"
340
+ };`,
341
+ },
342
+ logOverride: {
343
+ 'ignored-bare-import': 'silent',
344
+ },
345
+ plugins: !args?.wasmModuleImports
346
+ ? []
347
+ : [
348
+ rewriteWasmImportPath({
349
+ relativePathToAssets: isModeDirectory
350
+ ? relative(fileURLToPath(functionsUrl), fileURLToPath(assetsUrl))
351
+ : relative(fileURLToPath(_buildConfig.client), fileURLToPath(assetsUrl)),
352
+ }),
353
+ ],
354
+ });
355
+ // Rename to worker.js
356
+ await fs.promises.rename(buildPath, finalBuildUrl);
357
+ if (isModeDirectory) {
358
+ const directoryUrl = new URL('[[path]].js', functionsUrl);
359
+ await fs.promises.rename(finalBuildUrl, directoryUrl);
360
+ }
361
+ }
362
+ // throw the server folder in the bin
363
+ const serverUrl = new URL(_buildConfig.server);
364
+ await fs.promises.rm(serverUrl, { recursive: true, force: true });
365
+ // move cloudflare specific files to the root
366
+ const cloudflareSpecialFiles = ['_headers', '_redirects', '_routes.json'];
367
+ if (_config.base !== '/') {
368
+ for (const file of cloudflareSpecialFiles) {
369
+ try {
370
+ await fs.promises.rename(new URL(file, _buildConfig.client), new URL(file, _config.outDir));
371
+ }
372
+ catch (e) {
373
+ // ignore
374
+ }
375
+ }
376
+ }
377
+ // Add also the worker file so it's excluded from the _routes.json generation
378
+ if (!isModeDirectory) {
379
+ cloudflareSpecialFiles.push('_worker.js');
380
+ }
381
+ const routesExists = await fs.promises
382
+ .stat(new URL('./_routes.json', _config.outDir))
383
+ .then((stat) => stat.isFile())
384
+ .catch(() => false);
385
+ // this creates a _routes.json, in case there is none present to enable
386
+ // cloudflare to handle static files and support _redirects configuration
387
+ if (!routesExists) {
388
+ /**
389
+ * These route types are candiates for being part of the `_routes.json` `include` array.
390
+ */
391
+ const potentialFunctionRouteTypes = ['endpoint', 'page'];
392
+ const functionEndpoints = routes
393
+ // Certain route types, when their prerender option is set to false, run on the server as function invocations
394
+ .filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender)
395
+ .map((route) => {
396
+ const includePattern = '/' +
397
+ route.segments
398
+ .flat()
399
+ .map((segment) => (segment.dynamic ? '*' : segment.content))
400
+ .join('/');
401
+ const regexp = new RegExp('^\\/' +
402
+ route.segments
403
+ .flat()
404
+ .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
405
+ .join('\\/') +
406
+ '$');
407
+ return {
408
+ includePattern,
409
+ regexp,
410
+ };
411
+ });
412
+ const staticPathList = (await glob(`${fileURLToPath(_buildConfig.client)}/**/*`, {
413
+ cwd: fileURLToPath(_config.outDir),
414
+ filesOnly: true,
415
+ dot: true,
416
+ }))
417
+ .filter((file) => cloudflareSpecialFiles.indexOf(file) < 0)
418
+ .map((file) => `/${file.replace(/\\/g, '/')}`);
419
+ for (let page of pages) {
420
+ let pagePath = prependForwardSlash(page.pathname);
421
+ if (_config.base !== '/') {
422
+ const base = _config.base.endsWith('/') ? _config.base.slice(0, -1) : _config.base;
423
+ pagePath = `${base}${pagePath}`;
424
+ }
425
+ staticPathList.push(pagePath);
426
+ }
427
+ const redirectsExists = await fs.promises
428
+ .stat(new URL('./_redirects', _config.outDir))
429
+ .then((stat) => stat.isFile())
430
+ .catch(() => false);
431
+ // convert all redirect source paths into a list of routes
432
+ // and add them to the static path
433
+ if (redirectsExists) {
434
+ const redirects = (await fs.promises.readFile(new URL('./_redirects', _config.outDir), 'utf-8'))
435
+ .split(os.EOL)
436
+ .map((line) => {
437
+ const parts = line.split(' ');
438
+ if (parts.length < 2) {
439
+ return null;
440
+ }
441
+ else {
442
+ // convert /products/:id to /products/*
443
+ return (parts[0]
444
+ .replace(/\/:.*?(?=\/|$)/g, '/*')
445
+ // remove query params as they are not supported by cloudflare
446
+ .replace(/\?.*$/, ''));
447
+ }
448
+ })
449
+ .filter((line, index, arr) => line !== null && arr.indexOf(line) === index);
450
+ if (redirects.length > 0) {
451
+ staticPathList.push(...redirects);
452
+ }
453
+ }
454
+ const redirectRoutes = routes
455
+ .filter((r) => r.type === 'redirect')
456
+ .map((r) => {
457
+ return [r, ''];
458
+ });
459
+ const trueRedirects = createRedirectsFromAstroRoutes({
460
+ config: _config,
461
+ routeToDynamicTargetMap: new Map(Array.from(redirectRoutes)),
462
+ dir,
463
+ });
464
+ if (!trueRedirects.empty()) {
465
+ await fs.promises.appendFile(new URL('./_redirects', _config.outDir), trueRedirects.print());
466
+ }
467
+ staticPathList.push(...routes.filter((r) => r.type === 'redirect').map((r) => r.route));
468
+ const strategy = args?.routes?.strategy ?? 'auto';
469
+ // Strategy `include`: include all function endpoints, and then exclude static paths that would be matched by an include pattern
470
+ const includeStrategy = strategy === 'exclude'
471
+ ? undefined
472
+ : {
473
+ include: deduplicatePatterns(functionEndpoints
474
+ .map((endpoint) => endpoint.includePattern)
475
+ .concat(args?.routes?.include ?? [])),
476
+ exclude: deduplicatePatterns(staticPathList
477
+ .filter((file) => functionEndpoints.some((endpoint) => endpoint.regexp.test(file)))
478
+ .concat(args?.routes?.exclude ?? [])),
479
+ };
480
+ // Cloudflare requires at least one include pattern:
481
+ // https://developers.cloudflare.com/pages/platform/functions/routing/#limits
482
+ // So we add a pattern that we immediately exclude again
483
+ if (includeStrategy?.include.length === 0) {
484
+ includeStrategy.include = ['/'];
485
+ includeStrategy.exclude = ['/'];
486
+ }
487
+ // Strategy `exclude`: include everything, and then exclude all static paths
488
+ const excludeStrategy = strategy === 'include'
489
+ ? undefined
490
+ : {
491
+ include: ['/*'],
492
+ exclude: deduplicatePatterns(staticPathList.concat(args?.routes?.exclude ?? [])),
493
+ };
494
+ const includeStrategyLength = includeStrategy
495
+ ? includeStrategy.include.length + includeStrategy.exclude.length
496
+ : Infinity;
497
+ const excludeStrategyLength = excludeStrategy
498
+ ? excludeStrategy.include.length + excludeStrategy.exclude.length
499
+ : Infinity;
500
+ const winningStrategy = includeStrategyLength <= excludeStrategyLength ? includeStrategy : excludeStrategy;
501
+ await fs.promises.writeFile(new URL('./_routes.json', _config.outDir), JSON.stringify({
502
+ version: 1,
503
+ ...winningStrategy,
504
+ }, null, 2));
505
+ }
304
506
  },
305
- plugins: !args?.wasmModuleImports ? [] : [
306
- rewriteWasmImportPath({
307
- relativePathToAssets: isModeDirectory ? relative(fileURLToPath(functionsUrl), fileURLToPath(assetsUrl)) : relative(fileURLToPath(_buildConfig.client), fileURLToPath(assetsUrl))
308
- })
309
- ]
310
- });
311
- await fs.promises.rename(buildPath, finalBuildUrl);
312
- if (isModeDirectory) {
313
- const directoryUrl = new URL("[[path]].js", functionsUrl);
314
- await fs.promises.rename(finalBuildUrl, directoryUrl);
315
- }
316
- }
317
- const serverUrl = new URL(_buildConfig.server);
318
- await fs.promises.rm(serverUrl, { recursive: true, force: true });
319
- const cloudflareSpecialFiles = ["_headers", "_redirects", "_routes.json"];
320
- if (_config.base !== "/") {
321
- for (const file of cloudflareSpecialFiles) {
322
- try {
323
- await fs.promises.rename(
324
- new URL(file, _buildConfig.client),
325
- new URL(file, _config.outDir)
326
- );
327
- } catch (e) {
328
- }
329
- }
330
- }
331
- if (!isModeDirectory) {
332
- cloudflareSpecialFiles.push("_worker.js");
333
- }
334
- const routesExists = await fs.promises.stat(new URL("./_routes.json", _config.outDir)).then((stat) => stat.isFile()).catch(() => false);
335
- if (!routesExists) {
336
- const potentialFunctionRouteTypes = ["endpoint", "page"];
337
- const functionEndpoints = routes.filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender).map((route) => {
338
- const includePattern = "/" + route.segments.flat().map((segment) => segment.dynamic ? "*" : segment.content).join("/");
339
- const regexp = new RegExp(
340
- "^\\/" + route.segments.flat().map((segment) => segment.dynamic ? "(.*)" : segment.content).join("\\/") + "$"
341
- );
342
- return {
343
- includePattern,
344
- regexp
345
- };
346
- });
347
- const staticPathList = (await glob(`${fileURLToPath(_buildConfig.client)}/**/*`, {
348
- cwd: fileURLToPath(_config.outDir),
349
- filesOnly: true,
350
- dot: true
351
- })).filter((file) => cloudflareSpecialFiles.indexOf(file) < 0).map((file) => `/${file.replace(/\\/g, "/")}`);
352
- for (let page of pages) {
353
- let pagePath = prependForwardSlash(page.pathname);
354
- if (_config.base !== "/") {
355
- const base = _config.base.endsWith("/") ? _config.base.slice(0, -1) : _config.base;
356
- pagePath = `${base}${pagePath}`;
357
- }
358
- staticPathList.push(pagePath);
359
- }
360
- const redirectsExists = await fs.promises.stat(new URL("./_redirects", _config.outDir)).then((stat) => stat.isFile()).catch(() => false);
361
- if (redirectsExists) {
362
- const redirects = (await fs.promises.readFile(new URL("./_redirects", _config.outDir), "utf-8")).split(os.EOL).map((line) => {
363
- const parts = line.split(" ");
364
- if (parts.length < 2) {
365
- return null;
366
- } else {
367
- return parts[0].replace(/\/:.*?(?=\/|$)/g, "/*").replace(/\?.*$/, "");
368
- }
369
- }).filter(
370
- (line, index, arr) => line !== null && arr.indexOf(line) === index
371
- );
372
- if (redirects.length > 0) {
373
- staticPathList.push(...redirects);
374
- }
375
- }
376
- const redirectRoutes = routes.filter((r) => r.type === "redirect").map((r) => {
377
- return [r, ""];
378
- });
379
- const trueRedirects = createRedirectsFromAstroRoutes({
380
- config: _config,
381
- routeToDynamicTargetMap: new Map(Array.from(redirectRoutes)),
382
- dir
383
- });
384
- if (!trueRedirects.empty()) {
385
- await fs.promises.appendFile(
386
- new URL("./_redirects", _config.outDir),
387
- trueRedirects.print()
388
- );
389
- }
390
- staticPathList.push(...routes.filter((r) => r.type === "redirect").map((r) => r.route));
391
- const strategy = args?.routes?.strategy ?? "auto";
392
- const includeStrategy = strategy === "exclude" ? void 0 : {
393
- include: deduplicatePatterns(
394
- functionEndpoints.map((endpoint) => endpoint.includePattern).concat(args?.routes?.include ?? [])
395
- ),
396
- exclude: deduplicatePatterns(
397
- staticPathList.filter(
398
- (file) => functionEndpoints.some((endpoint) => endpoint.regexp.test(file))
399
- ).concat(args?.routes?.exclude ?? [])
400
- )
401
- };
402
- if (includeStrategy?.include.length === 0) {
403
- includeStrategy.include = ["/"];
404
- includeStrategy.exclude = ["/"];
405
- }
406
- const excludeStrategy = strategy === "include" ? void 0 : {
407
- include: ["/*"],
408
- exclude: deduplicatePatterns(staticPathList.concat(args?.routes?.exclude ?? []))
409
- };
410
- const includeStrategyLength = includeStrategy ? includeStrategy.include.length + includeStrategy.exclude.length : Infinity;
411
- const excludeStrategyLength = excludeStrategy ? excludeStrategy.include.length + excludeStrategy.exclude.length : Infinity;
412
- const winningStrategy = includeStrategyLength <= excludeStrategyLength ? includeStrategy : excludeStrategy;
413
- await fs.promises.writeFile(
414
- new URL("./_routes.json", _config.outDir),
415
- JSON.stringify(
416
- {
417
- version: 1,
418
- ...winningStrategy
419
- },
420
- null,
421
- 2
422
- )
423
- );
424
- }
425
- }
426
- }
427
- };
507
+ },
508
+ };
428
509
  }
429
- export {
430
- createIntegration as default
431
- };