@astrojs/cloudflare 0.0.0-cf-assets-20231021193132

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 ADDED
@@ -0,0 +1,412 @@
1
+ # @astrojs/cloudflare
2
+
3
+ An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Javascript and deploy to Cloudflare Pages.
4
+
5
+ ## Install
6
+
7
+ Add the Cloudflare adapter to enable SSR in your Astro project with the following `astro add` command. This will install the adapter and make the appropriate changes to your `astro.config.mjs` file in one step.
8
+
9
+ ```sh
10
+ # Using NPM
11
+ npx astro add cloudflare
12
+ # Using Yarn
13
+ yarn astro add cloudflare
14
+ # Using PNPM
15
+ pnpm astro add cloudflare
16
+ ```
17
+
18
+ If you prefer to install the adapter manually instead, complete the following two steps:
19
+
20
+ 1. Add the Cloudflare adapter to your project's dependencies using your preferred package manager. If you’re using npm or aren’t sure, run this in the terminal:
21
+
22
+ ```bash
23
+ npm install @astrojs/cloudflare
24
+ ```
25
+
26
+ 2. Add the following to your `astro.config.mjs` file:
27
+
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
+ ```
38
+
39
+ ## Options
40
+
41
+ ### `mode`
42
+
43
+ `mode: "advanced" | "directory"`
44
+
45
+ default `"advanced"`
46
+
47
+ This configuration option defines how your Astro project is deployed to Cloudflare Pages.
48
+
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
51
+
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/).
53
+
54
+ ```js
55
+ // astro.config.mjs
56
+ export default defineConfig({
57
+ adapter: cloudflare({ mode: 'directory' }),
58
+ });
59
+ ```
60
+
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.
62
+
63
+ ```diff lang="js"
64
+ // astro.config.mjs
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
72
+ })
73
+ })
74
+ ```
75
+
76
+ This adapter doesn't support the [`edgeMiddleware`](https://docs.astro.build/en/reference/adapter-reference/#edgemiddleware) option.
77
+
78
+ ### `routes.strategy`
79
+
80
+ `routes.strategy: "auto" | "include" | "exclude"`
81
+
82
+ default `"auto"`
83
+
84
+ Determines how `routes.json` will be generated if no [custom `_routes.json`](#custom-_routesjson) is provided.
85
+
86
+ There are three options available:
87
+
88
+ - **`"auto"` (default):** Will automatically select the strategy that generates the fewest entries. This should almost always be sufficient, so choose this option unless you have a specific reason not to.
89
+
90
+ - **`include`:** Pages and endpoints that are not pre-rendered are listed as `include` entries, telling Cloudflare to invoke these routes as functions. `exclude` entries are only used to resolve conflicts. Usually the best strategy when your website has mostly static pages and only a few dynamic pages or endpoints.
91
+
92
+ Example: For `src/pages/index.astro` (static), `src/pages/company.astro` (static), `src/pages/users/faq.astro` (static) and `/src/pages/users/[id].astro` (SSR) this will produce the following `_routes.json`:
93
+
94
+ ```json
95
+ {
96
+ "version": 1,
97
+ "include": [
98
+ "/_image", // Astro's image endpoint
99
+ "/users/*" // Dynamic route
100
+ ],
101
+ "exclude": [
102
+ // Static routes that needs to be exempted from the dynamic wildcard route above
103
+ "/users/faq/",
104
+ "/users/faq/index.html"
105
+ ]
106
+ }
107
+ ```
108
+
109
+ - **`exclude`:** Pre-rendered pages are listed as `exclude` entries (telling Cloudflare to handle these routes as static assets). Usually the best strategy when your website has mostly dynamic pages or endpoints and only a few static pages.
110
+
111
+ Example: For the same pages as in the previous example this will produce the following `_routes.json`:
112
+
113
+ ```json
114
+ {
115
+ "version": 1,
116
+ "include": [
117
+ "/*" // Handle everything as function except the routes below
118
+ ],
119
+ "exclude": [
120
+ // All static assets
121
+ "/",
122
+ "/company/",
123
+ "/index.html",
124
+ "/users/faq/",
125
+ "/favicon.png",
126
+ "/company/index.html",
127
+ "/users/faq/index.html"
128
+ ]
129
+ }
130
+ ```
131
+
132
+ ### `routes.include`
133
+
134
+ `routes.include: string[]`
135
+
136
+ default `[]`
137
+
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
+
140
+ ### `routes.exclude`
141
+
142
+ `routes.exclude: string[]`
143
+
144
+ default `[]`
145
+
146
+ If you want to use the automatic `_routes.json` generation, but want to exclude additional routes, you can use the `routes.exclude` option to add additional routes to the `exclude` array.
147
+
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
+
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 about [using Wasm modules](#use-wasm-modules).
173
+
174
+ ```diff lang="js"
175
+ // astro.config.mjs
176
+ import {defineConfig} from "astro/config";
177
+ import cloudflare from '@astrojs/cloudflare';
178
+
179
+ export default defineConfig({
180
+ adapter: cloudflare({
181
+ + wasmModuleImports: true
182
+ }),
183
+ output: 'server'
184
+ })
185
+ ```
186
+
187
+ ### `runtime`
188
+
189
+ `runtime: { mode: "off" | "local", persistTo: string }`
190
+
191
+ default `{ mode: 'off', persistTo: '' }`
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](#cloudflare-runtime).
196
+
197
+ The `mode` property defines how the runtime is added to `astro dev`:
198
+
199
+ - `local`: uses bindings mocking and locally static placeholders
200
+ - `off`: no access to the Cloudflare runtime using `astro dev`. You can alternatively use [Preview with Wrangler](#preview-with-wrangler)
201
+
202
+ The `persistTo` property defines where the local runtime is persisted to when using `mode: local`. This value is a directory relative to your `astro dev` execution path.
203
+
204
+ The default value is set to `.wrangler/state/v3` to match the default path Wrangler uses. This means both tools are able to access and use the local state.
205
+
206
+ Whichever directory is set in `persistTo`, `.wrangler` or your custom value, must be added to `.gitignore`.
207
+
208
+ ```diff lang="js"
209
+ // astro.config.mjs
210
+ import { defineConfig } from 'astro/config';
211
+ import cloudflare from '@astrojs/cloudflare';
212
+
213
+ export default defineConfig({
214
+ output: 'server',
215
+ adapter: cloudflare({
216
+ + runtime: { mode: 'local' },
217
+ }),
218
+ });
219
+ ```
220
+
221
+ ## Cloudflare runtime
222
+
223
+ Gives you access to [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings).
224
+
225
+ Currently supported bindings:
226
+
227
+ - [Cloudflare D1](https://developers.cloudflare.com/d1/)
228
+ - [Cloudflare R2](https://developers.cloudflare.com/r2/)
229
+ - [Cloudflare Workers KV](https://developers.cloudflare.com/kv/)
230
+ - [Cloudflare Durable Objects](https://developers.cloudflare.com/durable-objects/)
231
+
232
+ You can access the runtime from Astro components through `Astro.locals` inside any `.astro` file.
233
+
234
+ ```astro
235
+ ---
236
+ // src/pages/index.astro
237
+ const runtime = Astro.locals.runtime;
238
+ ---
239
+
240
+ <pre>{JSON.stringify(runtime.env)}</pre>
241
+ ```
242
+
243
+ You can access the runtime from API endpoints through `context.locals`:
244
+
245
+ ```js
246
+ // src/pages/api/someFile.js
247
+ export function GET(context) {
248
+ const runtime = context.locals.runtime;
249
+
250
+ return new Response('Some body');
251
+ }
252
+ ```
253
+
254
+ ### Typing
255
+
256
+ If you have configured `mode: advanced`, you can type the `runtime` object using `AdvancedRuntime`:
257
+
258
+ ```ts
259
+ // src/env.d.ts
260
+ /// <reference types="astro/client" />
261
+
262
+ type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
263
+ type ENV = {
264
+ SERVER_URL: string;
265
+ KV_BINDING: KVNamespace;
266
+ };
267
+
268
+ type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
269
+
270
+ declare namespace App {
271
+ interface Locals extends Runtime {
272
+ user: {
273
+ name: string;
274
+ surname: string;
275
+ };
276
+ }
277
+ }
278
+ ```
279
+
280
+ If you have configured `mode: directory`, you can type the `runtime` object using `DirectoryRuntime`:
281
+
282
+ ```ts
283
+ // src/env.d.ts
284
+ /// <reference types="astro/client" />
285
+
286
+ type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
287
+ type ENV = {
288
+ SERVER_URL: string;
289
+ KV_BINDING: KVNamespace;
290
+ };
291
+
292
+ type Runtime = import('@astrojs/cloudflare').DirectoryRuntime<ENV>;
293
+
294
+ declare namespace App {
295
+ interface Locals extends Runtime {
296
+ user: {
297
+ name: string;
298
+ surname: string;
299
+ };
300
+ }
301
+ }
302
+ ```
303
+
304
+ ## Platform
305
+
306
+ ### Headers
307
+
308
+ 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.
309
+
310
+ ### Redirects
311
+
312
+ 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.
313
+
314
+ ### Routes
315
+
316
+ 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.
317
+
318
+ #### Custom `_routes.json`
319
+
320
+ By default, `@astrojs/cloudflare` will generate a `_routes.json` file with `include` and `exclude` rules based on your applications's dynamic and static routes.
321
+ 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.
322
+
323
+ ## Use Wasm modules
324
+
325
+ The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together.
326
+
327
+ ```js
328
+ // pages/add/[a]/[b].js
329
+ import mod from '../util/add.wasm?module';
330
+
331
+ // instantiate ahead of time to share module
332
+ const addModule: any = new WebAssembly.Instance(mod);
333
+
334
+ export async function GET(context) {
335
+ const a = Number.parseInt(context.params.a);
336
+ const b = Number.parseInt(context.params.b);
337
+ return new Response(`${addModule.exports.add(a, b)}`);
338
+ }
339
+ ```
340
+
341
+ 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.
342
+
343
+ ## Node.js compatibility
344
+
345
+ Astro's Cloudflare adapter allows you to use any Node.js runtime API supported by Cloudflare:
346
+
347
+ - assert
348
+ - AsyncLocalStorage
349
+ - Buffer
350
+ - Crypto
351
+ - Diagnostics Channel
352
+ - EventEmitter
353
+ - path
354
+ - process
355
+ - Streams
356
+ - StringDecoder
357
+ - util
358
+
359
+ To use these APIs, your page or endpoint must be server-side rendered (not pre-rendered) and must use the the `import {} from 'node:*'` import syntax.
360
+
361
+ ```js
362
+ // pages/api/endpoint.js
363
+ export const prerender = false;
364
+ import { Buffer } from 'node:buffer';
365
+ ```
366
+
367
+ 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).
368
+
369
+ ## Cloudflare module support
370
+
371
+ All Cloudflare namespaced packages (e.g. `cloudflare:sockets`) are allowlisted for use. Note that the package `cloudflare:sockets` does not work locally without using Wrangler dev mode.
372
+
373
+ ## Preview with Wrangler
374
+
375
+ To use [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) to run your application locally, update the preview script:
376
+
377
+ ```json
378
+ //package.json
379
+ "preview": "wrangler pages dev ./dist"
380
+ ```
381
+
382
+ [`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).
383
+
384
+ ### Meaningful error messages
385
+
386
+ 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`.
387
+
388
+ ```diff lang="js"
389
+ // astro.config.mjs
390
+ export default defineConfig({
391
+ adapter: cloudflare(),
392
+ output: 'server',
393
+
394
+ + vite: {
395
+ + build: {
396
+ + minify: false,
397
+ + },
398
+ + },
399
+ });
400
+ ```
401
+
402
+ ## Troubleshooting
403
+
404
+ For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
405
+
406
+ You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
407
+
408
+ ## Contributing
409
+
410
+ This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
411
+
412
+ [astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
@@ -0,0 +1,6 @@
1
+ import type { ExternalImageService } from 'astro';
2
+ export declare function matchPort(url: URL, port?: string): boolean;
3
+ export declare function matchProtocol(url: URL, protocol?: string): boolean;
4
+ export declare function matchPathname(url: URL, pathname?: string, allowWildcard?: boolean): boolean;
5
+ declare const service: ExternalImageService;
6
+ export default service;