@astrojs/cloudflare 7.3.0 → 7.3.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.
package/README.md CHANGED
@@ -25,57 +25,57 @@ npm install @astrojs/cloudflare
25
25
 
26
26
  2. Add the following to your `astro.config.mjs` file:
27
27
 
28
- ```js ins={3, 6-7}
29
- // astro.config.mjs
30
- import { defineConfig } from 'astro/config';
31
- import cloudflare from '@astrojs/cloudflare';
32
-
33
- export default defineConfig({
34
- output: 'server',
35
- adapter: cloudflare(),
36
- });
28
+ ```diff lang="js"
29
+ // astro.config.mjs
30
+ import { defineConfig } from 'astro/config';
31
+ + import cloudflare from '@astrojs/cloudflare';
32
+
33
+ export default defineConfig({
34
+ + output: 'server',
35
+ + adapter: cloudflare(),
36
+ });
37
37
  ```
38
38
 
39
39
  ## Options
40
40
 
41
- ### Mode
41
+ ### `mode`
42
42
 
43
43
  `mode: "advanced" | "directory"`
44
44
 
45
45
  default `"advanced"`
46
46
 
47
- Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root. For most projects the adapter default of `advanced` will be sufficient; the `dist` folder will contain your compiled project.
47
+ This configuration option defines how your Astro project is deployed to Cloudflare Pages.
48
48
 
49
- #### `mode:directory`
49
+ - `advanced` mode picks up the `_worker.js` file in the `dist` folder
50
+ - `directory` mode picks up the files in the `functions` folder, by default only one `[[path]].js` file is generated
50
51
 
51
- Switching to directory mode allows you to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) or write custom code to enable logging.
52
+ Switching to directory mode allows you to add additional files manually such as [Cloudflare Pages Plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/), [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/) or custom functions using [Cloudflare Pages Functions Routing](https://developers.cloudflare.com/pages/platform/functions/routing/).
52
53
 
53
- ```ts
54
+ ```js
54
55
  // astro.config.mjs
55
56
  export default defineConfig({
56
57
  adapter: cloudflare({ mode: 'directory' }),
57
58
  });
58
59
  ```
59
60
 
60
- In `directory` mode, the adapter will compile the client-side part of your app the same way as in `advanced` mode by default, but moves the worker script into a `functions` folder in the project root. In this case, the adapter will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middleware which can be checked into version control.
61
+ To compile a separate bundle for each page, set the `functionPerRoute` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing files with identical names in the `functions` folder, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
61
62
 
62
- To instead compile a separate bundle for each page, set the `functionPerPath` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing `functions` files with identical names, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
63
+ ```diff lang="js"
64
+ // astro.config.mjs
65
+ import {defineConfig} from "astro/config";
66
+ import cloudflare from '@astrojs/cloudflare';
63
67
 
64
- ```diff
65
- import {defineConfig} from "astro/config";
66
- import cloudflare from '@astrojs/cloudflare';
67
-
68
- export default defineConfig({
69
- adapter: cloudflare({
70
- mode: 'directory',
71
- + functionPerRoute: true
68
+ export default defineConfig({
69
+ adapter: cloudflare({
70
+ mode: 'directory',
71
+ + functionPerRoute: true
72
72
  })
73
- })
73
+ })
74
74
  ```
75
75
 
76
- Note that this adapter does not support using [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro will bundle the [Astro middleware](https://docs.astro.build/en/guides/middleware/) into each page.
76
+ This adapter doesn't support the [`edgeMiddleware`](https://docs.astro.build/en/reference/adapter-reference/#edgemiddleware) option.
77
77
 
78
- ### routes.strategy
78
+ ### `routes.strategy`
79
79
 
80
80
  `routes.strategy: "auto" | "include" | "exclude"`
81
81
 
@@ -129,7 +129,7 @@ There are three options available:
129
129
  }
130
130
  ```
131
131
 
132
- ### routes.include
132
+ ### `routes.include`
133
133
 
134
134
  `routes.include: string[]`
135
135
 
@@ -137,7 +137,7 @@ default `[]`
137
137
 
138
138
  If you want to use the automatic `_routes.json` generation, but want to include additional routes (e.g. when having custom functions in the `functions` folder), you can use the `routes.include` option to add additional routes to the `include` array.
139
139
 
140
- ### routes.exclude
140
+ ### `routes.exclude`
141
141
 
142
142
  `routes.exclude: string[]`
143
143
 
@@ -147,41 +147,86 @@ If you want to use the automatic `_routes.json` generation, but want to exclude
147
147
 
148
148
  The following example automatically generates `_routes.json` while including and excluding additional routes. Note that that is only necessary if you have custom functions in the `functions` folder that are not handled by Astro.
149
149
 
150
- ```diff
150
+ ```diff lang="js"
151
+ // astro.config.mjs
152
+ export default defineConfig({
153
+ adapter: cloudflare({
154
+ mode: 'directory',
155
+ + routes: {
156
+ + strategy: 'include',
157
+ + include: ['/users/*'], // handled by custom function: functions/users/[id].js
158
+ + exclude: ['/users/faq'], // handled by static page: pages/users/faq.astro
159
+ + },
160
+ }),
161
+ });
162
+ ```
163
+
164
+ ### `wasmModuleImports`
165
+
166
+ `wasmModuleImports: boolean`
167
+
168
+ default: `false`
169
+
170
+ Whether or not to import `.wasm` files [directly as ES modules](https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration) using the `.wasm?module` import syntax.
171
+
172
+ Add `wasmModuleImports: true` to `astro.config.mjs` to enable this functionality in both the Cloudflare build and the Astro dev server. [Read more](#use-wasm-modules)
173
+
174
+ ```diff lang="js"
151
175
  // astro.config.mjs
176
+ import {defineConfig} from "astro/config";
177
+ import cloudflare from '@astrojs/cloudflare';
178
+
152
179
  export default defineConfig({
153
180
  adapter: cloudflare({
154
- mode: 'directory',
155
- + routes: {
156
- + strategy: 'include',
157
- + include: ['/users/*'], // handled by custom function: functions/users/[id].js
158
- + exclude: ['/users/faq'], // handled by static page: pages/users/faq.astro
159
- + },
181
+ + wasmModuleImports: true
160
182
  }),
161
- });
183
+ output: 'server'
184
+ })
162
185
  ```
163
186
 
164
- ## Enabling Preview
187
+ ### `runtime`
165
188
 
166
- In order for preview to work you must install `wrangler`
189
+ `runtime: "off" | "local" | "remote"`
167
190
 
168
- ```sh
169
- pnpm install wrangler --save-dev
170
- ```
191
+ default `"off"`
192
+
193
+ Determines whether and how the Cloudflare Runtime is added to `astro dev`.
194
+
195
+ The Cloudflare Runtime includes [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Read more about [accessing the Cloudflare Runtime](#access-to-the-cloudflare-runtime).
196
+
197
+ - `local`: uses bindings mocking and locally static placeholdes
198
+ - `remote`: uses remote bindings and a live fetched cf object
199
+ - `off`: no access to the Cloudflare runtime using `astro dev`. You can alternatively use [Preview with Wrangler](#preview-with-wrangler)
200
+
201
+ ```diff lang="js"
202
+ // astro.config.mjs
203
+ import { defineConfig } from 'astro/config';
204
+ import cloudflare from '@astrojs/cloudflare';
171
205
 
172
- It's then possible to update the preview script in your `package.json` to `"preview": "wrangler pages dev ./dist"`. This will allow you to run your entire application locally with [Wrangler](https://github.com/cloudflare/wrangler2), which supports secrets, environment variables, KV namespaces, Durable Objects and [all other supported Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/#adding-bindings).
206
+ export default defineConfig({
207
+ output: 'server',
208
+ adapter: cloudflare({
209
+ + runtime: 'local',
210
+ }),
211
+ });
212
+ ```
173
213
 
174
- ## Access to the Cloudflare runtime
214
+ ## Cloudflare runtime
175
215
 
176
- You can access all the Cloudflare bindings and environment variables from Astro components and API routes through `Astro.locals`.
216
+ Gives you access to [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables).
177
217
 
178
- If you're inside an `.astro` file, you access the runtime using the `Astro.locals` global:
218
+ You can access the runtime from Astro components through `Astro.locals` inside any .astro` file.
179
219
 
180
220
  ```astro
181
- const env = Astro.locals.runtime.env;
221
+ ---
222
+ // src/pages/index.astro
223
+ const runtime = Astro.locals.runtime;
224
+ ---
225
+
226
+ <pre>{JSON.stringify(runtime.env)}</pre>
182
227
  ```
183
228
 
184
- From an endpoint:
229
+ You can access the runtime from API endpoints through `context.locals`:
185
230
 
186
231
  ```js
187
232
  // src/pages/api/someFile.js
@@ -192,21 +237,24 @@ export function GET(context) {
192
237
  }
193
238
  ```
194
239
 
195
- Depending on your adapter mode (advanced = worker, directory = pages), the runtime object will look a little different due to differences in the Cloudflare API.
240
+ ### Typing
196
241
 
197
- If you're using the `advanced` runtime, you can type the `runtime` object as following:
242
+ If you have configured `mode: advanced`, you can type the `runtime` object using `AdvancedRuntime`:
198
243
 
199
244
  ```ts
200
245
  // src/env.d.ts
201
246
  /// <reference types="astro/client" />
202
- import type { AdvancedRuntime } from '@astrojs/cloudflare';
203
247
 
248
+ type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
204
249
  type ENV = {
205
250
  SERVER_URL: string;
251
+ KV_BINDING: KVNamespace;
206
252
  };
207
253
 
254
+ type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
255
+
208
256
  declare namespace App {
209
- interface Locals extends AdvancedRuntime<ENV> {
257
+ interface Locals extends Runtime {
210
258
  user: {
211
259
  name: string;
212
260
  surname: string;
@@ -215,19 +263,22 @@ declare namespace App {
215
263
  }
216
264
  ```
217
265
 
218
- If you're using the `directory` runtime, you can type the `runtime` object as following:
266
+ If you have configured `mode: directory`, you can type the `runtime` object using `DirectoryRuntime`:
219
267
 
220
268
  ```ts
221
269
  // src/env.d.ts
222
270
  /// <reference types="astro/client" />
223
- import type { DirectoryRuntime } from '@astrojs/cloudflare';
224
271
 
272
+ type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
225
273
  type ENV = {
226
274
  SERVER_URL: string;
275
+ KV_BINDING: KVNamespace;
227
276
  };
228
277
 
278
+ type Runtime = import('@astrojs/cloudflare').DirectoryRuntime<ENV>;
279
+
229
280
  declare namespace App {
230
- interface Locals extends DirectoryRuntime<ENV> {
281
+ interface Locals extends Runtime {
231
282
  user: {
232
283
  name: string;
233
284
  surname: string;
@@ -236,75 +287,30 @@ declare namespace App {
236
287
  }
237
288
  ```
238
289
 
239
- ### Environment Variables
290
+ ## Platform
240
291
 
241
- See Cloudflare's documentation for [working with environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables).
292
+ ### Headers
242
293
 
243
- ```js
244
- // pages/[id].json.js
245
-
246
- export function GET({ params }) {
247
- // Access environment variables per request inside a function
248
- const serverUrl = import.meta.env.SERVER_URL;
249
- const result = await fetch(serverUrl + "/user/" + params.id);
250
- return {
251
- body: await result.text(),
252
- };
253
- }
254
- ```
255
-
256
- ### `cloudflare.runtime`
257
-
258
- `runtime: "off" | "local" | "remote"`
259
- default `"off"`
260
-
261
- This optional flag enables the Astro dev server to populate environment variables and the Cloudflare Request Object, avoiding the need for Wrangler.
262
-
263
- - `local`: environment variables are available, but the request object is populated from a static placeholder value.
264
- - `remote`: environment variables and the live, fetched request object are available.
265
- - `off`: the Astro dev server will populate neither environment variables nor the request object. Use Wrangler to access Cloudflare bindings and environment variables.
266
-
267
- ```js
268
- // astro.config.mjs
269
- import { defineConfig } from 'astro/config';
270
- import cloudflare from '@astrojs/cloudflare';
271
-
272
- export default defineConfig({
273
- output: 'server',
274
- adapter: cloudflare({
275
- runtime: 'off' | 'local' | 'remote',
276
- }),
277
- });
278
- ```
294
+ You can attach [custom headers](https://developers.cloudflare.com/pages/platform/headers/) to your responses by adding a `_headers` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
279
295
 
280
- ## Wasm module imports
296
+ ### Redirects
281
297
 
282
- `wasmModuleImports: boolean`
298
+ You can declare [custom redirects](https://developers.cloudflare.com/pages/platform/redirects/) using Cloudflare Pages. This allows you to redirect requests to a different URL. You can add a `_redirects` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
283
299
 
284
- default: `false`
285
-
286
- Whether or not to import `.wasm` files [directly as ES modules](https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration).
300
+ ### Routes
287
301
 
288
- Add `wasmModuleImports: true` to `astro.config.mjs` to enable in both the Cloudflare build and the Astro dev server.
302
+ You can define which routes are invoking functions and which are static assets, using [Cloudflare routing](https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes) via a `_routes.json` file. This file is automatically generated by Astro.
289
303
 
290
- ```diff
291
- // astro.config.mjs
292
- import {defineConfig} from "astro/config";
293
- import cloudflare from '@astrojs/cloudflare';
304
+ #### Custom `_routes.json`
294
305
 
295
- export default defineConfig({
296
- adapter: cloudflare({
297
- + wasmModuleImports: true
298
- }),
299
- output: 'server'
300
- })
301
- ```
306
+ By default, `@astrojs/cloudflare` will generate a `_routes.json` file with `include` and `exclude` rules based on your applications's dynamic and static routes.
307
+ This will enable Cloudflare to serve files and process static redirects without a function invocation. Creating a custom `_routes.json` will override this automatic optimization. See [Cloudflare's documentation on creating a custom `routes.json`](https://developers.cloudflare.com/pages/platform/functions/routing/#create-a-_routesjson-file) for more details.
302
308
 
303
- Once enabled, you can import a web assembly module in Astro with a `.wasm?module` import.
309
+ ## Use Wasm modules
304
310
 
305
311
  The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together.
306
312
 
307
- ```javascript
313
+ ```js
308
314
  // pages/add/[a]/[b].js
309
315
  import mod from '../util/add.wasm?module';
310
316
 
@@ -320,17 +326,6 @@ export async function GET(context) {
320
326
 
321
327
  While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library.
322
328
 
323
- ## Headers, Redirects and function invocation routes
324
-
325
- Cloudflare has support for adding custom [headers](https://developers.cloudflare.com/pages/platform/headers/), configuring static [redirects](https://developers.cloudflare.com/pages/platform/redirects/) and defining which routes should [invoke functions](https://developers.cloudflare.com/pages/platform/functions/routing/#function-invocation-routes). Cloudflare looks for `_headers`, `_redirects`, and `_routes.json` files in your build output directory to configure these features. This means they should be placed in your Astro project’s `public/` directory.
326
-
327
- ### Custom `_routes.json`
328
-
329
- By default, `@astrojs/cloudflare` will generate a `_routes.json` file with `include` and `exclude` rules based on your applications's dynamic and static routes.
330
- This will enable Cloudflare to serve files and process static redirects without a function invocation. Creating a custom `_routes.json` will override this automatic optimization and, if not configured manually, cause function invocations that will count against the request limits of your Cloudflare plan.
331
-
332
- See [Cloudflare's documentation](https://developers.cloudflare.com/pages/platform/functions/routing/#create-a-_routesjson-file) for more details.
333
-
334
329
  ## Node.js compatibility
335
330
 
336
331
  Astro's Cloudflare adapter allows you to use any Node.js runtime API supported by Cloudflare:
@@ -354,33 +349,43 @@ export const prerender = false;
354
349
  import { Buffer } from 'node:buffer';
355
350
  ```
356
351
 
357
- Additionally, you'll need to enable the Compatibility Flag in Cloudflare. The configuration for this flag may vary based on where you deploy your Astro site.
352
+ Additionally, you'll need to enable the Compatibility Flag in Cloudflare. The configuration for this flag may vary based on where you deploy your Astro site. For detailed guidance, please refer to the [Cloudflare documentation on enabling Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs).
358
353
 
359
- For detailed guidance, please refer to the [Cloudflare documentation](https://developers.cloudflare.com/workers/runtime-apis/nodejs).
354
+ ## Preview with Wrangler
360
355
 
361
- ## Troubleshooting
356
+ To use [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) to run your application locally, update the preview script:
362
357
 
363
- For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
358
+ ```json
359
+ //package.json
360
+ "preview": "wrangler pages dev ./dist"
361
+ ```
364
362
 
365
- You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
363
+ [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) gives you access to [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Getting hot reloading or the astro dev server to work with Wrangler might require custom setup. See [community examples](https://github.com/withastro/roadmap/discussions/590).
366
364
 
367
365
  ### Meaningful error messages
368
366
 
369
- Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add `vite.build.minify = false` setting to your `astro.config.js`
367
+ Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add `vite.build.minify = false` setting to your `astro.config.mjs`.
370
368
 
371
- ```js
372
- export default defineConfig({
373
- adapter: cloudflare(),
374
- output: 'server',
369
+ ```diff lang="js"
370
+ // astro.config.mjs
371
+ export default defineConfig({
372
+ adapter: cloudflare(),
373
+ output: 'server',
375
374
 
376
- vite: {
377
- build: {
378
- minify: false,
379
- },
380
- },
381
- });
375
+ + vite: {
376
+ + build: {
377
+ + minify: false,
378
+ + },
379
+ + },
380
+ });
382
381
  ```
383
382
 
383
+ ## Troubleshooting
384
+
385
+ For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
386
+
387
+ You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
388
+
384
389
  ## Contributing
385
390
 
386
391
  This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
@@ -1,5 +1,5 @@
1
1
  import { App } from "astro/app";
2
- import { getProcessEnvProxy, isNode } from "./util.js";
2
+ import { getProcessEnvProxy, isNode } from "../util.js";
3
3
  if (!isNode) {
4
4
  process.env = getProcessEnvProxy();
5
5
  }
@@ -9,6 +9,6 @@ export interface DirectoryRuntime<T extends object = object> {
9
9
  };
10
10
  }
11
11
  export declare function createExports(manifest: SSRManifest): {
12
- onRequest: (context: EventContext<unknown, string, unknown>) => Promise<import("@cloudflare/workers-types").Response | Response>;
12
+ onRequest: (context: EventContext<unknown, string, unknown>) => Promise<Response | import("@cloudflare/workers-types").Response>;
13
13
  manifest: SSRManifest;
14
14
  };
@@ -1,5 +1,5 @@
1
1
  import { App } from "astro/app";
2
- import { getProcessEnvProxy, isNode } from "./util.js";
2
+ import { getProcessEnvProxy, isNode } from "../util.js";
3
3
  if (!isNode) {
4
4
  process.env = getProcessEnvProxy();
5
5
  }
@@ -0,0 +1,5 @@
1
+ import type { AstroAdapter } from 'astro';
2
+ export declare function getAdapter({ isModeDirectory, functionPerRoute, }: {
3
+ isModeDirectory: boolean;
4
+ functionPerRoute: boolean;
5
+ }): AstroAdapter;
@@ -0,0 +1,36 @@
1
+ function getAdapter({
2
+ isModeDirectory,
3
+ functionPerRoute
4
+ }) {
5
+ const astroFeatures = {
6
+ hybridOutput: "stable",
7
+ staticOutput: "unsupported",
8
+ serverOutput: "stable",
9
+ assets: {
10
+ supportKind: "stable",
11
+ isSharpCompatible: false,
12
+ isSquooshCompatible: false
13
+ }
14
+ };
15
+ if (isModeDirectory) {
16
+ return {
17
+ name: "@astrojs/cloudflare",
18
+ serverEntrypoint: "@astrojs/cloudflare/entrypoints/server.directory.js",
19
+ exports: ["onRequest", "manifest"],
20
+ adapterFeatures: {
21
+ functionPerRoute,
22
+ edgeMiddleware: false
23
+ },
24
+ supportedAstroFeatures: astroFeatures
25
+ };
26
+ }
27
+ return {
28
+ name: "@astrojs/cloudflare",
29
+ serverEntrypoint: "@astrojs/cloudflare/entrypoints/server.advanced.js",
30
+ exports: ["default"],
31
+ supportedAstroFeatures: astroFeatures
32
+ };
33
+ }
34
+ export {
35
+ getAdapter
36
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { AstroAdapter, AstroIntegration } from 'astro';
2
- export type { AdvancedRuntime } from './server.advanced.js';
3
- export type { DirectoryRuntime } from './server.directory.js';
1
+ import type { AstroIntegration } from 'astro';
2
+ export type { AdvancedRuntime } from './entrypoints/server.advanced.js';
3
+ export type { DirectoryRuntime } from './entrypoints/server.directory.js';
4
4
  type Options = {
5
5
  mode?: 'directory' | 'advanced';
6
6
  functionPerRoute?: boolean;
@@ -25,8 +25,4 @@ type Options = {
25
25
  runtime?: 'off' | 'local' | 'remote';
26
26
  wasmModuleImports?: boolean;
27
27
  };
28
- export declare function getAdapter({ isModeDirectory, functionPerRoute, }: {
29
- isModeDirectory: boolean;
30
- functionPerRoute: boolean;
31
- }): AstroAdapter;
32
28
  export default function createIntegration(args?: Options): AstroIntegration;
package/dist/index.js CHANGED
@@ -6,11 +6,16 @@ import { AstroError } from "astro/errors";
6
6
  import esbuild from "esbuild";
7
7
  import * as fs from "node:fs";
8
8
  import * as os from "node:os";
9
- import { basename, dirname, relative, sep } from "node:path";
9
+ import { dirname, relative, sep } from "node:path";
10
10
  import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  import glob from "tiny-glob";
12
- import { getEnvVars } from "./parser.js";
13
- import { wasmModuleLoader } from "./wasm-module-loader.js";
12
+ import { getAdapter } from "./getAdapter.js";
13
+ import { deduplicatePatterns } from "./utils/deduplicatePatterns.js";
14
+ import { getCFObject } from "./utils/getCFObject.js";
15
+ import { getEnvVars } from "./utils/parser.js";
16
+ import { prependForwardSlash } from "./utils/prependForwardSlash.js";
17
+ import { rewriteWasmImportPath } from "./utils/rewriteWasmImportPath.js";
18
+ import { wasmModuleLoader } from "./utils/wasm-module-loader.js";
14
19
  class StorageFactory {
15
20
  storages = /* @__PURE__ */ new Map();
16
21
  storage(namespace) {
@@ -21,119 +26,11 @@ class StorageFactory {
21
26
  return storage;
22
27
  }
23
28
  }
24
- function getAdapter({
25
- isModeDirectory,
26
- functionPerRoute
27
- }) {
28
- return isModeDirectory ? {
29
- name: "@astrojs/cloudflare",
30
- serverEntrypoint: "@astrojs/cloudflare/server.directory.js",
31
- exports: ["onRequest", "manifest"],
32
- adapterFeatures: {
33
- functionPerRoute,
34
- edgeMiddleware: false
35
- },
36
- supportedAstroFeatures: {
37
- hybridOutput: "stable",
38
- staticOutput: "unsupported",
39
- serverOutput: "stable",
40
- assets: {
41
- supportKind: "stable",
42
- isSharpCompatible: false,
43
- isSquooshCompatible: false
44
- }
45
- }
46
- } : {
47
- name: "@astrojs/cloudflare",
48
- serverEntrypoint: "@astrojs/cloudflare/server.advanced.js",
49
- exports: ["default"],
50
- supportedAstroFeatures: {
51
- hybridOutput: "stable",
52
- staticOutput: "unsupported",
53
- serverOutput: "stable",
54
- assets: {
55
- supportKind: "stable",
56
- isSharpCompatible: false,
57
- isSquooshCompatible: false
58
- }
59
- }
60
- };
61
- }
62
- async function getCFObject(runtimeMode) {
63
- const CF_ENDPOINT = "https://workers.cloudflare.com/cf.json";
64
- const CF_FALLBACK = {
65
- asOrganization: "",
66
- asn: 395747,
67
- colo: "DFW",
68
- city: "Austin",
69
- region: "Texas",
70
- regionCode: "TX",
71
- metroCode: "635",
72
- postalCode: "78701",
73
- country: "US",
74
- continent: "NA",
75
- timezone: "America/Chicago",
76
- latitude: "30.27130",
77
- longitude: "-97.74260",
78
- clientTcpRtt: 0,
79
- httpProtocol: "HTTP/1.1",
80
- requestPriority: "weight=192;exclusive=0",
81
- tlsCipher: "AEAD-AES128-GCM-SHA256",
82
- tlsVersion: "TLSv1.3",
83
- tlsClientAuth: {
84
- certPresented: "0",
85
- certVerified: "NONE",
86
- certRevoked: "0",
87
- certIssuerDN: "",
88
- certSubjectDN: "",
89
- certIssuerDNRFC2253: "",
90
- certSubjectDNRFC2253: "",
91
- certIssuerDNLegacy: "",
92
- certSubjectDNLegacy: "",
93
- certSerial: "",
94
- certIssuerSerial: "",
95
- certSKI: "",
96
- certIssuerSKI: "",
97
- certFingerprintSHA1: "",
98
- certFingerprintSHA256: "",
99
- certNotBefore: "",
100
- certNotAfter: ""
101
- },
102
- edgeRequestKeepAliveStatus: 0,
103
- hostMetadata: void 0,
104
- clientTrustScore: 99,
105
- botManagement: {
106
- corporateProxy: false,
107
- verifiedBot: false,
108
- ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
109
- staticResource: false,
110
- detectionIds: [],
111
- score: 99
112
- }
113
- };
114
- if (runtimeMode === "local") {
115
- return CF_FALLBACK;
116
- } else if (runtimeMode === "remote") {
117
- try {
118
- const res = await fetch(CF_ENDPOINT);
119
- const cfText = await res.text();
120
- const storedCf = JSON.parse(cfText);
121
- return storedCf;
122
- } catch (e) {
123
- return CF_FALLBACK;
124
- }
125
- }
126
- }
127
- const SHIM = `globalThis.process = {
128
- argv: [],
129
- env: {},
130
- };`;
131
- const SERVER_BUILD_FOLDER = "/$server_build/";
132
- const potentialFunctionRouteTypes = ["endpoint", "page"];
133
29
  function createIntegration(args) {
134
30
  let _config;
135
31
  let _buildConfig;
136
32
  let _entryPoints = /* @__PURE__ */ new Map();
33
+ const SERVER_BUILD_FOLDER = "/$server_build/";
137
34
  const isModeDirectory = args?.mode === "directory";
138
35
  const functionPerRoute = args?.functionPerRoute ?? false;
139
36
  const runtimeMode = args?.runtime ?? "off";
@@ -163,12 +60,12 @@ function createIntegration(args) {
163
60
  setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
164
61
  _config = config;
165
62
  _buildConfig = config.build;
166
- if (config.output === "static") {
63
+ if (_config.output === "static") {
167
64
  throw new AstroError(
168
65
  '[@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.'
169
66
  );
170
67
  }
171
- if (config.base === SERVER_BUILD_FOLDER) {
68
+ if (_config.base === SERVER_BUILD_FOLDER) {
172
69
  throw new AstroError(
173
70
  '[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.'
174
71
  );
@@ -290,7 +187,10 @@ function createIntegration(args) {
290
187
  bundle: true,
291
188
  minify: _config.vite?.build?.minify !== false,
292
189
  banner: {
293
- js: SHIM
190
+ js: `globalThis.process = {
191
+ argv: [],
192
+ env: {},
193
+ };`
294
194
  },
295
195
  logOverride: {
296
196
  "ignored-bare-import": "silent"
@@ -350,7 +250,10 @@ function createIntegration(args) {
350
250
  bundle: true,
351
251
  minify: _config.vite?.build?.minify !== false,
352
252
  banner: {
353
- js: SHIM
253
+ js: `globalThis.process = {
254
+ argv: [],
255
+ env: {},
256
+ };`
354
257
  },
355
258
  logOverride: {
356
259
  "ignored-bare-import": "silent"
@@ -386,6 +289,7 @@ function createIntegration(args) {
386
289
  }
387
290
  const routesExists = await fs.promises.stat(new URL("./_routes.json", _config.outDir)).then((stat) => stat.isFile()).catch(() => false);
388
291
  if (!routesExists) {
292
+ const potentialFunctionRouteTypes = ["endpoint", "page"];
389
293
  const functionEndpoints = routes.filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender).map((route) => {
390
294
  const includePattern = "/" + route.segments.flat().map((segment) => segment.dynamic ? "*" : segment.content).join("/");
391
295
  const regexp = new RegExp(
@@ -398,7 +302,8 @@ function createIntegration(args) {
398
302
  });
399
303
  const staticPathList = (await glob(`${fileURLToPath(_buildConfig.client)}/**/*`, {
400
304
  cwd: fileURLToPath(_config.outDir),
401
- filesOnly: true
305
+ filesOnly: true,
306
+ dot: true
402
307
  })).filter((file) => cloudflareSpecialFiles.indexOf(file) < 0).map((file) => `/${file.replace(/\\/g, "/")}`);
403
308
  for (let page of pages) {
404
309
  let pagePath = prependForwardSlash(page.pathname);
@@ -477,43 +382,6 @@ function createIntegration(args) {
477
382
  }
478
383
  };
479
384
  }
480
- function prependForwardSlash(path) {
481
- return path[0] === "/" ? path : "/" + path;
482
- }
483
- function deduplicatePatterns(patterns) {
484
- const openPatterns = [];
485
- return [...new Set(patterns)].sort((a, b) => a.length - b.length).filter((pattern) => {
486
- if (openPatterns.some((p) => p.test(pattern))) {
487
- return false;
488
- }
489
- if (pattern.endsWith("*")) {
490
- openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, ".*")}`));
491
- }
492
- return true;
493
- });
494
- }
495
- function rewriteWasmImportPath({
496
- relativePathToAssets
497
- }) {
498
- return {
499
- name: "wasm-loader",
500
- setup(build) {
501
- build.onResolve({ filter: /.*\.wasm.mjs$/ }, (args) => {
502
- const updatedPath = [
503
- relativePathToAssets.replaceAll("\\", "/"),
504
- basename(args.path).replace(/\.mjs$/, "")
505
- ].join("/");
506
- return {
507
- path: updatedPath,
508
- // change the reference to the changed module
509
- external: true
510
- // mark it as external in the bundle
511
- };
512
- });
513
- }
514
- };
515
- }
516
385
  export {
517
- createIntegration as default,
518
- getAdapter
386
+ createIntegration as default
519
387
  };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Remove duplicates and redundant patterns from an `include` or `exclude` list.
3
+ * Otherwise Cloudflare will throw an error on deployment. Plus, it saves more entries.
4
+ * E.g. `['/foo/*', '/foo/*', '/foo/bar'] => ['/foo/*']`
5
+ * @param patterns a list of `include` or `exclude` patterns
6
+ * @returns a deduplicated list of patterns
7
+ */
8
+ export declare function deduplicatePatterns(patterns: string[]): string[];
@@ -0,0 +1,15 @@
1
+ function deduplicatePatterns(patterns) {
2
+ const openPatterns = [];
3
+ return [...new Set(patterns)].sort((a, b) => a.length - b.length).filter((pattern) => {
4
+ if (openPatterns.some((p) => p.test(pattern))) {
5
+ return false;
6
+ }
7
+ if (pattern.endsWith("*")) {
8
+ openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, ".*")}`));
9
+ }
10
+ return true;
11
+ });
12
+ }
13
+ export {
14
+ deduplicatePatterns
15
+ };
@@ -0,0 +1,2 @@
1
+ import type { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental';
2
+ export declare function getCFObject(runtimeMode: string): Promise<IncomingRequestCfProperties | void>;
@@ -0,0 +1,68 @@
1
+ async function getCFObject(runtimeMode) {
2
+ const CF_ENDPOINT = "https://workers.cloudflare.com/cf.json";
3
+ const CF_FALLBACK = {
4
+ asOrganization: "",
5
+ asn: 395747,
6
+ colo: "DFW",
7
+ city: "Austin",
8
+ region: "Texas",
9
+ regionCode: "TX",
10
+ metroCode: "635",
11
+ postalCode: "78701",
12
+ country: "US",
13
+ continent: "NA",
14
+ timezone: "America/Chicago",
15
+ latitude: "30.27130",
16
+ longitude: "-97.74260",
17
+ clientTcpRtt: 0,
18
+ httpProtocol: "HTTP/1.1",
19
+ requestPriority: "weight=192;exclusive=0",
20
+ tlsCipher: "AEAD-AES128-GCM-SHA256",
21
+ tlsVersion: "TLSv1.3",
22
+ tlsClientAuth: {
23
+ certPresented: "0",
24
+ certVerified: "NONE",
25
+ certRevoked: "0",
26
+ certIssuerDN: "",
27
+ certSubjectDN: "",
28
+ certIssuerDNRFC2253: "",
29
+ certSubjectDNRFC2253: "",
30
+ certIssuerDNLegacy: "",
31
+ certSubjectDNLegacy: "",
32
+ certSerial: "",
33
+ certIssuerSerial: "",
34
+ certSKI: "",
35
+ certIssuerSKI: "",
36
+ certFingerprintSHA1: "",
37
+ certFingerprintSHA256: "",
38
+ certNotBefore: "",
39
+ certNotAfter: ""
40
+ },
41
+ edgeRequestKeepAliveStatus: 0,
42
+ hostMetadata: void 0,
43
+ clientTrustScore: 99,
44
+ botManagement: {
45
+ corporateProxy: false,
46
+ verifiedBot: false,
47
+ ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
48
+ staticResource: false,
49
+ detectionIds: [],
50
+ score: 99
51
+ }
52
+ };
53
+ if (runtimeMode === "local") {
54
+ return CF_FALLBACK;
55
+ } else if (runtimeMode === "remote") {
56
+ try {
57
+ const res = await fetch(CF_ENDPOINT);
58
+ const cfText = await res.text();
59
+ const storedCf = JSON.parse(cfText);
60
+ return storedCf;
61
+ } catch (e) {
62
+ return CF_FALLBACK;
63
+ }
64
+ }
65
+ }
66
+ export {
67
+ getCFObject
68
+ };
@@ -0,0 +1 @@
1
+ export declare function prependForwardSlash(path: string): string;
@@ -0,0 +1,6 @@
1
+ function prependForwardSlash(path) {
2
+ return path[0] === "/" ? path : "/" + path;
3
+ }
4
+ export {
5
+ prependForwardSlash
6
+ };
@@ -0,0 +1,8 @@
1
+ import esbuild from 'esbuild';
2
+ /**
3
+ *
4
+ * @param relativePathToAssets - relative path from the final location for the current esbuild output bundle, to the assets directory.
5
+ */
6
+ export declare function rewriteWasmImportPath({ relativePathToAssets, }: {
7
+ relativePathToAssets: string;
8
+ }): esbuild.Plugin;
@@ -0,0 +1,25 @@
1
+ import esbuild from "esbuild";
2
+ import { basename } from "node:path";
3
+ function rewriteWasmImportPath({
4
+ relativePathToAssets
5
+ }) {
6
+ return {
7
+ name: "wasm-loader",
8
+ setup(build) {
9
+ build.onResolve({ filter: /.*\.wasm.mjs$/ }, (args) => {
10
+ const updatedPath = [
11
+ relativePathToAssets.replaceAll("\\", "/"),
12
+ basename(args.path).replace(/\.mjs$/, "")
13
+ ].join("/");
14
+ return {
15
+ path: updatedPath,
16
+ external: true
17
+ // mark it as external in the bundle
18
+ };
19
+ });
20
+ }
21
+ };
22
+ }
23
+ export {
24
+ rewriteWasmImportPath
25
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astrojs/cloudflare",
3
3
  "description": "Deploy your site to Cloudflare Workers/Pages",
4
- "version": "7.3.0",
4
+ "version": "7.3.1",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
7
7
  "author": "withastro",
@@ -19,17 +19,12 @@
19
19
  "homepage": "https://docs.astro.build/en/guides/integrations-guide/cloudflare/",
20
20
  "exports": {
21
21
  ".": "./dist/index.js",
22
- "./runtime": {
23
- "types": "./runtime.d.ts",
24
- "default": "./dist/runtime.js"
25
- },
26
- "./server.advanced.js": "./dist/server.advanced.js",
27
- "./server.directory.js": "./dist/server.directory.js",
22
+ "./entrypoints/server.advanced.js": "./dist/entrypoints/server.advanced.js",
23
+ "./entrypoints/server.directory.js": "./dist/entrypoints/server.directory.js",
28
24
  "./package.json": "./package.json"
29
25
  },
30
26
  "files": [
31
- "dist",
32
- "runtime.d.ts"
27
+ "dist"
33
28
  ],
34
29
  "dependencies": {
35
30
  "@cloudflare/workers-types": "^4.20230821.0",
@@ -45,7 +40,7 @@
45
40
  "@astrojs/underscore-redirects": "0.3.0"
46
41
  },
47
42
  "peerDependencies": {
48
- "astro": "^3.1.3"
43
+ "astro": "^3.2.0"
49
44
  },
50
45
  "devDependencies": {
51
46
  "@types/iarna__toml": "^2.0.2",
@@ -53,7 +48,7 @@
53
48
  "cheerio": "1.0.0-rc.12",
54
49
  "mocha": "^10.2.0",
55
50
  "wrangler": "^3.5.1",
56
- "astro": "3.1.3",
51
+ "astro": "3.2.0",
57
52
  "astro-scripts": "0.0.14"
58
53
  },
59
54
  "scripts": {
File without changes
File without changes