@astrojs/cloudflare 0.0.0-imgcache-20220929145446

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.
@@ -0,0 +1,5 @@
1
+ @astrojs/cloudflare:build: cache hit, replaying output fcf442d05d9892bf
2
+ @astrojs/cloudflare:build: 
3
+ @astrojs/cloudflare:build: > @astrojs/cloudflare@0.0.0-imgcache-20220929145446 build /home/runner/work/astro/astro/packages/integrations/cloudflare
4
+ @astrojs/cloudflare:build: > astro-scripts build "src/**/*.ts" && tsc
5
+ @astrojs/cloudflare:build: 
package/CHANGELOG.md ADDED
@@ -0,0 +1,161 @@
1
+ # @astrojs/cloudflare
2
+
3
+ ## 0.0.0-imgcache-20220929145446
4
+
5
+ ### Minor Changes
6
+
7
+ - [#4876](https://github.com/withastro/astro/pull/4876) [`d3091f89e`](https://github.com/withastro/astro/commit/d3091f89e92fcfe1ad48daca74055d54b1c853a3) Thanks [@matthewp](https://github.com/matthewp)! - Adds the Astro.cookies API
8
+
9
+ `Astro.cookies` is a new API for manipulating cookies in Astro components and API routes.
10
+
11
+ In Astro components, the new `Astro.cookies` object is a map-like object that allows you to get, set, delete, and check for a cookie's existence (`has`):
12
+
13
+ ```astro
14
+ ---
15
+ type Prefs = {
16
+ darkMode: boolean;
17
+ };
18
+
19
+ Astro.cookies.set<Prefs>(
20
+ 'prefs',
21
+ { darkMode: true },
22
+ {
23
+ expires: '1 month',
24
+ }
25
+ );
26
+
27
+ const prefs = Astro.cookies.get<Prefs>('prefs').json();
28
+ ---
29
+
30
+ <body data-theme={prefs.darkMode ? 'dark' : 'light'}></body>
31
+ ```
32
+
33
+ Once you've set a cookie with Astro.cookies it will automatically be included in the outgoing response.
34
+
35
+ This API is also available with the same functionality in API routes:
36
+
37
+ ```js
38
+ export function post({ cookies }) {
39
+ cookies.set('loggedIn', false);
40
+
41
+ return new Response(null, {
42
+ status: 302,
43
+ headers: {
44
+ Location: '/login',
45
+ },
46
+ });
47
+ }
48
+ ```
49
+
50
+ See [the RFC](https://github.com/withastro/rfcs/blob/main/proposals/0025-cookie-management.md) to learn more.
51
+
52
+ ## 2.0.0
53
+
54
+ ### Major Changes
55
+
56
+ - [#4815](https://github.com/withastro/astro/pull/4815) [`ce0b92ba7`](https://github.com/withastro/astro/commit/ce0b92ba73072c0f0143829a53f870155ad4c7ff) Thanks [@AirBorne04](https://github.com/AirBorne04)! - adjusted esbuild config to work with worker environment (fixing solid js ssr)
57
+
58
+ ## 1.0.2
59
+
60
+ ### Patch Changes
61
+
62
+ - [#4558](https://github.com/withastro/astro/pull/4558) [`742966456`](https://github.com/withastro/astro/commit/7429664566f05ecebf6d57906f950627e62e690c) Thanks [@tony-sull](https://github.com/tony-sull)! - Adding the `withastro` keyword to include the adapters on the [Integrations Catalog](https://astro.build/integrations)
63
+
64
+ ## 1.0.1
65
+
66
+ ### Patch Changes
67
+
68
+ - [#4232](https://github.com/withastro/astro/pull/4232) [`bfbd32588`](https://github.com/withastro/astro/commit/bfbd32588f7e2c0a9e43cd1a571a0dc9c5f7e645) Thanks [@Ekwuno](https://github.com/Ekwuno)! - Update README
69
+
70
+ ## 1.0.0
71
+
72
+ ### Major Changes
73
+
74
+ - [`04ad44563`](https://github.com/withastro/astro/commit/04ad445632c67bdd60c1704e1e0dcbcaa27b9308) - > Astro v1.0 is out! Read the [official announcement post](https://astro.build/blog/astro-1/).
75
+
76
+ **No breaking changes**. This package is now officially stable and compatible with `astro@1.0.0`!
77
+
78
+ ## 0.5.0
79
+
80
+ ### Minor Changes
81
+
82
+ - [#3806](https://github.com/withastro/astro/pull/3806) [`f4c571bdb`](https://github.com/withastro/astro/commit/f4c571bdb0bbcd0dfed68a484dfbfe274f8a5f45) Thanks [@nrgnrg](https://github.com/nrgnrg)! - add support for compiling functions to a functions directory rather than `_worker.js`
83
+
84
+ ## 0.4.0
85
+
86
+ ### Minor Changes
87
+
88
+ - [#4068](https://github.com/withastro/astro/pull/4068) [`54b33d50f`](https://github.com/withastro/astro/commit/54b33d50fdb995ac056461be7e2128d911624f2d) Thanks [@matthewp](https://github.com/matthewp)! - Add explicit errors when omitting output config
89
+
90
+ ### Patch Changes
91
+
92
+ - [#4072](https://github.com/withastro/astro/pull/4072) [`a198028b0`](https://github.com/withastro/astro/commit/a198028b04234d0b8dcb0b6bcb47c5831d7a15f9) Thanks [@matthewp](https://github.com/matthewp)! - Fixes Cloudflare throwing an error for process
93
+
94
+ ## 0.3.0
95
+
96
+ ### Minor Changes
97
+
98
+ - [#4015](https://github.com/withastro/astro/pull/4015) [`6fd161d76`](https://github.com/withastro/astro/commit/6fd161d7691cbf9d3ffa4646e46059dfd0940010) Thanks [@matthewp](https://github.com/matthewp)! - New `output` configuration option
99
+
100
+ This change introduces a new "output target" configuration option (`output`). Setting the output target lets you decide the format of your final build, either:
101
+
102
+ - `"static"` (default): A static site. Your final build will be a collection of static assets (HTML, CSS, JS) that you can deploy to any static site host.
103
+ - `"server"`: A dynamic server application. Your final build will be an application that will run in a hosted server environment, generating HTML dynamically for different requests.
104
+
105
+ If `output` is omitted from your config, the default value `"static"` will be used.
106
+
107
+ When using the `"server"` output target, you must also include a runtime adapter via the `adapter` configuration. An adapter will _adapt_ your final build to run on the deployed platform of your choice (Netlify, Vercel, Node.js, Deno, etc).
108
+
109
+ To migrate: No action is required for most users. If you currently define an `adapter`, you will need to also add `output: 'server'` to your config file to make it explicit that you are building a server. Here is an example of what that change would look like for someone deploying to Netlify:
110
+
111
+ ```diff
112
+ import { defineConfig } from 'astro/config';
113
+ import netlify from '@astrojs/netlify/functions';
114
+
115
+ export default defineConfig({
116
+ adapter: netlify(),
117
+ + output: 'server',
118
+ });
119
+ ```
120
+
121
+ * [#4018](https://github.com/withastro/astro/pull/4018) [`0cc6ede36`](https://github.com/withastro/astro/commit/0cc6ede362996b9faba57481a790d6eb7fba2045) Thanks [@okikio](https://github.com/okikio)! - Support for 404 and 500 pages in SSR
122
+
123
+ - [#3973](https://github.com/withastro/astro/pull/3973) [`5a23483ef`](https://github.com/withastro/astro/commit/5a23483efb3ba614b05a00064f84415620605204) Thanks [@matthewp](https://github.com/matthewp)! - Adds support for Astro.clientAddress
124
+
125
+ The new `Astro.clientAddress` property allows you to get the IP address of the requested user.
126
+
127
+ ```astro
128
+
129
+ ```
130
+
131
+ This property is only available when building for SSR, and only if the adapter you are using supports providing the IP address. If you attempt to access the property in a SSG app it will throw an error.
132
+
133
+ ## 0.2.4
134
+
135
+ ### Patch Changes
136
+
137
+ - [#3885](https://github.com/withastro/astro/pull/3885) [`bf5d1cc1e`](https://github.com/withastro/astro/commit/bf5d1cc1e71da38a14658c615e9481f2145cc6e7) Thanks [@delucis](https://github.com/delucis)! - Integration README fixes
138
+
139
+ ## 0.2.3
140
+
141
+ ### Patch Changes
142
+
143
+ - [#3854](https://github.com/withastro/astro/pull/3854) [`b012ee55`](https://github.com/withastro/astro/commit/b012ee55b107dea0730286263b27d83e530fad5d) Thanks [@bholmesdev](https://github.com/bholmesdev)! - [astro add] Support adapters and third party packages
144
+
145
+ ## 0.2.2
146
+
147
+ ### Patch Changes
148
+
149
+ - [#3777](https://github.com/withastro/astro/pull/3777) [`976e1f17`](https://github.com/withastro/astro/commit/976e1f175a95ea39f737b8575e4fdf3c3d89e1ee) Thanks [@tony-sull](https://github.com/tony-sull)! - Disables HTTP streaming in Cloudflare Pages deployments
150
+
151
+ ## 0.2.1
152
+
153
+ ### Patch Changes
154
+
155
+ - [#3695](https://github.com/withastro/astro/pull/3695) [`0d667d0e`](https://github.com/withastro/astro/commit/0d667d0e572d76d4c819816ddf51ed14b43e2551) Thanks [@nrgnrg](https://github.com/nrgnrg)! - fix custom 404 pages not rendering
156
+
157
+ ## 0.2.0
158
+
159
+ ### Minor Changes
160
+
161
+ - [#3600](https://github.com/withastro/astro/pull/3600) [`7f423581`](https://github.com/withastro/astro/commit/7f423581411648c9a69b68918ff930581f12cf16) Thanks [@nrgnrg](https://github.com/nrgnrg)! - add SSR adaptor for Cloudflare Pages functions
package/LICENSE ADDED
@@ -0,0 +1,61 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Fred K. Schott
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+
24
+ """
25
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
26
+
27
+ Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
28
+
29
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
30
+
31
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
32
+
33
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34
+ """
35
+
36
+
37
+ """
38
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
39
+
40
+ MIT License
41
+
42
+ Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
43
+
44
+ Permission is hereby granted, free of charge, to any person obtaining a copy
45
+ of this software and associated documentation files (the "Software"), to deal
46
+ in the Software without restriction, including without limitation the rights
47
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
48
+ copies of the Software, and to permit persons to whom the Software is
49
+ furnished to do so, subject to the following conditions:
50
+
51
+ The above copyright notice and this permission notice shall be included in all
52
+ copies or substantial portions of the Software.
53
+
54
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
55
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
56
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
57
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
58
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
59
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
60
+ SOFTWARE.
61
+ """
package/README.md ADDED
@@ -0,0 +1,104 @@
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
+ ```js title="astro.config.mjs" ins={2, 5-6}
29
+ import { defineConfig } from 'astro/config';
30
+ import cloudflare from '@astrojs/cloudflare';
31
+
32
+ export default defineConfig({
33
+ output: 'server',
34
+ adapter: cloudflare()
35
+ });
36
+ ```
37
+
38
+ ## Options
39
+
40
+
41
+ ### Mode
42
+
43
+ `mode: "advanced" | "directory"`
44
+
45
+ default `"advanced"`
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.
48
+
49
+ For most projects the adaptor default of `advanced` will be sufficiant, when in this mode the `dist` folder will contain your compiled project. However if you'd like to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) for example to enable logging, you'll need to use directory mode.
50
+
51
+ In directory mode the adaptor will compile the client side part of you app the same way, but it will move the worker script into a `functions` folder in the project root. The adaptor 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.
52
+
53
+ ```ts
54
+ // directory mode
55
+ export default defineConfig({
56
+ adapter: cloudflare({ mode: "directory" }),
57
+ });
58
+
59
+ ```
60
+
61
+ ## Enabling Preview
62
+
63
+ In order for preview to work you must install `wrangler`
64
+
65
+ ```sh
66
+ $ pnpm install wrangler --save-dev
67
+ ```
68
+
69
+ It's then possible to update the preview script in your `package.json` to `"preview": "wrangler pages dev ./dist"`.This will allow you 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).
70
+
71
+ ## Streams
72
+
73
+ Some integrations such as [React](https://github.com/withastro/astro/tree/main/packages/integrations/react) rely on web streams. Currently Cloudflare Pages functions are in beta and don't support the `streams_enable_constructors` feature flag.
74
+
75
+ In order to work around this:
76
+ - install the `"web-streams-polyfill"` package
77
+ - add `import "web-streams-polyfill/es2018";` to the top of the front matter of every page which requires streams, such as server rendering a React component.
78
+
79
+ ## Environment Variables
80
+
81
+ As Cloudflare Pages Functions [provides environment variables differently](https://developers.cloudflare.com/pages/platform/functions/#adding-environment-variables-locally), private environment variables needs to be set through [`vite.define`](https://vitejs.dev/config/shared-options.html#define) to work in builds.
82
+
83
+ ```js
84
+ // astro.config.mjs
85
+ export default {
86
+ vite: {
87
+ define: {
88
+ 'process.env.MY_SECRET': JSON.stringify(process.env.MY_SECRET),
89
+ },
90
+ },
91
+ }
92
+ ```
93
+
94
+ ## Troubleshooting
95
+
96
+ For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
97
+
98
+ You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
99
+
100
+ ## Contributing
101
+
102
+ This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
103
+
104
+ [astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
@@ -0,0 +1,7 @@
1
+ import type { AstroAdapter, AstroIntegration } from 'astro';
2
+ declare type Options = {
3
+ mode: 'directory' | 'advanced';
4
+ };
5
+ export declare function getAdapter(isModeDirectory: boolean): AstroAdapter;
6
+ export default function createIntegration(args?: Options): AstroIntegration;
7
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ import esbuild from "esbuild";
2
+ import * as fs from "fs";
3
+ import { fileURLToPath } from "url";
4
+ function getAdapter(isModeDirectory) {
5
+ return isModeDirectory ? {
6
+ name: "@astrojs/cloudflare",
7
+ serverEntrypoint: "@astrojs/cloudflare/server.directory.js",
8
+ exports: ["onRequest"]
9
+ } : {
10
+ name: "@astrojs/cloudflare",
11
+ serverEntrypoint: "@astrojs/cloudflare/server.advanced.js",
12
+ exports: ["default"]
13
+ };
14
+ }
15
+ const SHIM = `globalThis.process = {
16
+ argv: [],
17
+ env: {},
18
+ };`;
19
+ function createIntegration(args) {
20
+ let _config;
21
+ let _buildConfig;
22
+ const isModeDirectory = (args == null ? void 0 : args.mode) === "directory";
23
+ return {
24
+ name: "@astrojs/cloudflare",
25
+ hooks: {
26
+ "astro:config:done": ({ setAdapter, config }) => {
27
+ setAdapter(getAdapter(isModeDirectory));
28
+ _config = config;
29
+ if (config.output === "static") {
30
+ throw new Error(`
31
+ [@astrojs/cloudflare] \`output: "server"\` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.
32
+
33
+ `);
34
+ }
35
+ },
36
+ "astro:build:start": ({ buildConfig }) => {
37
+ _buildConfig = buildConfig;
38
+ buildConfig.client = new URL("./static/", _config.outDir);
39
+ buildConfig.serverEntry = "_worker.js";
40
+ buildConfig.server = new URL("./", _config.outDir);
41
+ },
42
+ "astro:build:setup": ({ vite, target }) => {
43
+ if (target === "server") {
44
+ vite.resolve = vite.resolve || {};
45
+ vite.resolve.alias = vite.resolve.alias || {};
46
+ const aliases = [{ find: "react-dom/server", replacement: "react-dom/server.browser" }];
47
+ if (Array.isArray(vite.resolve.alias)) {
48
+ vite.resolve.alias = [...vite.resolve.alias, ...aliases];
49
+ } else {
50
+ for (const alias of aliases) {
51
+ vite.resolve.alias[alias.find] = alias.replacement;
52
+ }
53
+ }
54
+ vite.ssr = {
55
+ ...vite.ssr,
56
+ target: "webworker"
57
+ };
58
+ }
59
+ },
60
+ "astro:build:done": async () => {
61
+ const entryUrl = new URL(_buildConfig.serverEntry, _buildConfig.server);
62
+ const pkg = fileURLToPath(entryUrl);
63
+ await esbuild.build({
64
+ target: "es2020",
65
+ platform: "neutral",
66
+ mainFields: ["main", "module"],
67
+ conditions: ["worker", "node"],
68
+ entryPoints: [pkg],
69
+ outfile: pkg,
70
+ allowOverwrite: true,
71
+ format: "esm",
72
+ bundle: true,
73
+ minify: true,
74
+ banner: {
75
+ js: SHIM
76
+ }
77
+ });
78
+ const chunksUrl = new URL("./chunks", _buildConfig.server);
79
+ await fs.promises.rm(chunksUrl, { recursive: true, force: true });
80
+ if (isModeDirectory) {
81
+ const functionsUrl = new URL(`file://${process.cwd()}/functions/`);
82
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
83
+ const directoryUrl = new URL("[[path]].js", functionsUrl);
84
+ await fs.promises.rename(entryUrl, directoryUrl);
85
+ }
86
+ }
87
+ }
88
+ };
89
+ }
90
+ export {
91
+ createIntegration as default,
92
+ getAdapter
93
+ };
@@ -0,0 +1,13 @@
1
+ import './shim.js';
2
+ import type { SSRManifest } from 'astro';
3
+ declare type Env = {
4
+ ASSETS: {
5
+ fetch: (req: Request) => Promise<Response>;
6
+ };
7
+ };
8
+ export declare function createExports(manifest: SSRManifest): {
9
+ default: {
10
+ fetch: (request: Request, env: Env) => Promise<Response>;
11
+ };
12
+ };
13
+ export {};
@@ -0,0 +1,35 @@
1
+ import "./shim.js";
2
+ import { App } from "astro/app";
3
+ function createExports(manifest) {
4
+ const app = new App(manifest, false);
5
+ const fetch = async (request, env) => {
6
+ const { origin, pathname } = new URL(request.url);
7
+ if (manifest.assets.has(pathname)) {
8
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
9
+ return env.ASSETS.fetch(assetRequest);
10
+ }
11
+ let routeData = app.match(request, { matchNotFound: true });
12
+ if (routeData) {
13
+ Reflect.set(
14
+ request,
15
+ Symbol.for("astro.clientAddress"),
16
+ request.headers.get("cf-connecting-ip")
17
+ );
18
+ let response = await app.render(request, routeData);
19
+ if (app.setCookieHeaders) {
20
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
21
+ response.headers.append("Set-Cookie", setCookieHeader);
22
+ }
23
+ }
24
+ return response;
25
+ }
26
+ return new Response(null, {
27
+ status: 404,
28
+ statusText: "Not found"
29
+ });
30
+ };
31
+ return { default: { fetch } };
32
+ }
33
+ export {
34
+ createExports
35
+ };
@@ -0,0 +1,8 @@
1
+ import './shim.js';
2
+ import type { SSRManifest } from 'astro';
3
+ export declare function createExports(manifest: SSRManifest): {
4
+ onRequest: ({ request, next, }: {
5
+ request: Request;
6
+ next: (request: Request) => void;
7
+ }) => Promise<void | Response>;
8
+ };
@@ -0,0 +1,38 @@
1
+ import "./shim.js";
2
+ import { App } from "astro/app";
3
+ function createExports(manifest) {
4
+ const app = new App(manifest, false);
5
+ const onRequest = async ({
6
+ request,
7
+ next
8
+ }) => {
9
+ const { origin, pathname } = new URL(request.url);
10
+ if (manifest.assets.has(pathname)) {
11
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
12
+ return next(assetRequest);
13
+ }
14
+ let routeData = app.match(request, { matchNotFound: true });
15
+ if (routeData) {
16
+ Reflect.set(
17
+ request,
18
+ Symbol.for("astro.clientAddress"),
19
+ request.headers.get("cf-connecting-ip")
20
+ );
21
+ let response = await app.render(request, routeData);
22
+ if (app.setCookieHeaders) {
23
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
24
+ response.headers.append("Set-Cookie", setCookieHeader);
25
+ }
26
+ }
27
+ return response;
28
+ }
29
+ return new Response(null, {
30
+ status: 404,
31
+ statusText: "Not found"
32
+ });
33
+ };
34
+ return { onRequest };
35
+ }
36
+ export {
37
+ createExports
38
+ };
package/dist/shim.d.ts ADDED
File without changes
package/dist/shim.js ADDED
@@ -0,0 +1,4 @@
1
+ globalThis.process = {
2
+ argv: [],
3
+ env: {}
4
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@astrojs/cloudflare",
3
+ "description": "Deploy your site to cloudflare pages functions",
4
+ "version": "0.0.0-imgcache-20220929145446",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "author": "withastro",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/withastro/astro.git",
12
+ "directory": "packages/integrations/cloudflare"
13
+ },
14
+ "keywords": [
15
+ "withastro",
16
+ "astro-adapter"
17
+ ],
18
+ "bugs": "https://github.com/withastro/astro/issues",
19
+ "homepage": "https://docs.astro.build/en/guides/integrations-guide/cloudflare/",
20
+ "exports": {
21
+ ".": "./dist/index.js",
22
+ "./server.advanced.js": "./dist/server.advanced.js",
23
+ "./server.directory.js": "./dist/server.directory.js",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "dependencies": {
27
+ "esbuild": "^0.14.42"
28
+ },
29
+ "devDependencies": {
30
+ "astro": "0.0.0-imgcache-20220929145446",
31
+ "astro-scripts": "0.0.8",
32
+ "chai": "^4.3.6",
33
+ "cheerio": "^1.0.0-rc.11",
34
+ "mocha": "^9.2.2",
35
+ "wrangler": "^2.0.23"
36
+ },
37
+ "scripts": {
38
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc",
39
+ "build:ci": "astro-scripts build \"src/**/*.ts\"",
40
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
41
+ "test": "mocha --exit --timeout 30000 test/"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { AstroAdapter, AstroConfig, AstroIntegration, BuildConfig } from 'astro';
2
+ import esbuild from 'esbuild';
3
+ import * as fs from 'fs';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ type Options = {
7
+ mode: 'directory' | 'advanced';
8
+ };
9
+
10
+ export function getAdapter(isModeDirectory: boolean): AstroAdapter {
11
+ return isModeDirectory
12
+ ? {
13
+ name: '@astrojs/cloudflare',
14
+ serverEntrypoint: '@astrojs/cloudflare/server.directory.js',
15
+ exports: ['onRequest'],
16
+ }
17
+ : {
18
+ name: '@astrojs/cloudflare',
19
+ serverEntrypoint: '@astrojs/cloudflare/server.advanced.js',
20
+ exports: ['default'],
21
+ };
22
+ }
23
+
24
+ const SHIM = `globalThis.process = {
25
+ argv: [],
26
+ env: {},
27
+ };`;
28
+
29
+ export default function createIntegration(args?: Options): AstroIntegration {
30
+ let _config: AstroConfig;
31
+ let _buildConfig: BuildConfig;
32
+ const isModeDirectory = args?.mode === 'directory';
33
+
34
+ return {
35
+ name: '@astrojs/cloudflare',
36
+ hooks: {
37
+ 'astro:config:done': ({ setAdapter, config }) => {
38
+ setAdapter(getAdapter(isModeDirectory));
39
+ _config = config;
40
+
41
+ if (config.output === 'static') {
42
+ throw new Error(`
43
+ [@astrojs/cloudflare] \`output: "server"\` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.
44
+
45
+ `);
46
+ }
47
+ },
48
+ 'astro:build:start': ({ buildConfig }) => {
49
+ _buildConfig = buildConfig;
50
+ buildConfig.client = new URL('./static/', _config.outDir);
51
+ buildConfig.serverEntry = '_worker.js';
52
+ buildConfig.server = new URL('./', _config.outDir);
53
+ },
54
+ 'astro:build:setup': ({ vite, target }) => {
55
+ if (target === 'server') {
56
+ vite.resolve = vite.resolve || {};
57
+ vite.resolve.alias = vite.resolve.alias || {};
58
+
59
+ const aliases = [{ find: 'react-dom/server', replacement: 'react-dom/server.browser' }];
60
+
61
+ if (Array.isArray(vite.resolve.alias)) {
62
+ vite.resolve.alias = [...vite.resolve.alias, ...aliases];
63
+ } else {
64
+ for (const alias of aliases) {
65
+ (vite.resolve.alias as Record<string, string>)[alias.find] = alias.replacement;
66
+ }
67
+ }
68
+
69
+ vite.ssr = {
70
+ ...vite.ssr,
71
+ target: 'webworker',
72
+ };
73
+ }
74
+ },
75
+ 'astro:build:done': async () => {
76
+ const entryUrl = new URL(_buildConfig.serverEntry, _buildConfig.server);
77
+ const pkg = fileURLToPath(entryUrl);
78
+ await esbuild.build({
79
+ target: 'es2020',
80
+ platform: 'neutral',
81
+ mainFields: ['main', 'module'],
82
+ conditions: ['worker', 'node'],
83
+ entryPoints: [pkg],
84
+ outfile: pkg,
85
+ allowOverwrite: true,
86
+ format: 'esm',
87
+ bundle: true,
88
+ minify: true,
89
+ banner: {
90
+ js: SHIM,
91
+ },
92
+ });
93
+
94
+ // throw the server folder in the bin
95
+ const chunksUrl = new URL('./chunks', _buildConfig.server);
96
+ await fs.promises.rm(chunksUrl, { recursive: true, force: true });
97
+
98
+ if (isModeDirectory) {
99
+ const functionsUrl = new URL(`file://${process.cwd()}/functions/`);
100
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
101
+ const directoryUrl = new URL('[[path]].js', functionsUrl);
102
+ await fs.promises.rename(entryUrl, directoryUrl);
103
+ }
104
+ },
105
+ },
106
+ };
107
+ }
@@ -0,0 +1,47 @@
1
+ import './shim.js';
2
+
3
+ import type { SSRManifest } from 'astro';
4
+ import { App } from 'astro/app';
5
+
6
+ type Env = {
7
+ ASSETS: { fetch: (req: Request) => Promise<Response> };
8
+ };
9
+
10
+ export function createExports(manifest: SSRManifest) {
11
+ const app = new App(manifest, false);
12
+
13
+ const fetch = async (request: Request, env: Env) => {
14
+ const { origin, pathname } = new URL(request.url);
15
+
16
+ // static assets
17
+ if (manifest.assets.has(pathname)) {
18
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
19
+ return env.ASSETS.fetch(assetRequest);
20
+ }
21
+
22
+ let routeData = app.match(request, { matchNotFound: true });
23
+ if (routeData) {
24
+ Reflect.set(
25
+ request,
26
+ Symbol.for('astro.clientAddress'),
27
+ request.headers.get('cf-connecting-ip')
28
+ );
29
+ let response = await app.render(request, routeData);
30
+
31
+ if (app.setCookieHeaders) {
32
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
33
+ response.headers.append('Set-Cookie', setCookieHeader);
34
+ }
35
+ }
36
+
37
+ return response;
38
+ }
39
+
40
+ return new Response(null, {
41
+ status: 404,
42
+ statusText: 'Not found',
43
+ });
44
+ };
45
+
46
+ return { default: { fetch } };
47
+ }
@@ -0,0 +1,49 @@
1
+ import './shim.js';
2
+
3
+ import type { SSRManifest } from 'astro';
4
+ import { App } from 'astro/app';
5
+
6
+ export function createExports(manifest: SSRManifest) {
7
+ const app = new App(manifest, false);
8
+
9
+ const onRequest = async ({
10
+ request,
11
+ next,
12
+ }: {
13
+ request: Request;
14
+ next: (request: Request) => void;
15
+ }) => {
16
+ const { origin, pathname } = new URL(request.url);
17
+
18
+ // static assets
19
+ if (manifest.assets.has(pathname)) {
20
+ const assetRequest = new Request(`${origin}/static${pathname}`, request);
21
+ return next(assetRequest);
22
+ }
23
+
24
+ let routeData = app.match(request, { matchNotFound: true });
25
+ if (routeData) {
26
+ Reflect.set(
27
+ request,
28
+ Symbol.for('astro.clientAddress'),
29
+ request.headers.get('cf-connecting-ip')
30
+ );
31
+ let response = await app.render(request, routeData);
32
+
33
+ if (app.setCookieHeaders) {
34
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
35
+ response.headers.append('Set-Cookie', setCookieHeader);
36
+ }
37
+ }
38
+
39
+ return response;
40
+ }
41
+
42
+ return new Response(null, {
43
+ status: 404,
44
+ statusText: 'Not found',
45
+ });
46
+ };
47
+
48
+ return { onRequest };
49
+ }
package/src/shim.ts ADDED
@@ -0,0 +1,4 @@
1
+ (globalThis as any).process = {
2
+ argv: [],
3
+ env: {},
4
+ };
@@ -0,0 +1,31 @@
1
+ import { loadFixture, runCLI } from './test-utils.js';
2
+ import { expect } from 'chai';
3
+ import * as cheerio from 'cheerio';
4
+
5
+ describe.skip('Basic app', () => {
6
+ /** @type {import('./test-utils').Fixture} */
7
+ let fixture;
8
+
9
+ before(async () => {
10
+ fixture = await loadFixture({
11
+ root: './fixtures/basics/',
12
+ });
13
+ await fixture.build();
14
+ });
15
+
16
+ it('can render', async () => {
17
+ const { ready, stop } = runCLI('./fixtures/basics/', { silent: true });
18
+
19
+ try {
20
+ await ready;
21
+
22
+ let res = await fetch(`http://localhost:8787/`);
23
+ expect(res.status).to.equal(200);
24
+ let html = await res.text();
25
+ let $ = cheerio.load(html);
26
+ expect($('h1').text()).to.equal('Testing');
27
+ } finally {
28
+ stop();
29
+ }
30
+ });
31
+ });
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'astro/config';
2
+ import cloudflare from '@astrojs/cloudflare';
3
+
4
+ export default defineConfig({
5
+ adapter: cloudflare(),
6
+ output: 'server',
7
+ });
@@ -0,0 +1,17 @@
1
+ #!/bin/sh
2
+ basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3
+
4
+ case `uname` in
5
+ *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
6
+ esac
7
+
8
+ if [ -z "$NODE_PATH" ]; then
9
+ export NODE_PATH="/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
10
+ else
11
+ export NODE_PATH="$NODE_PATH:/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
12
+ fi
13
+ if [ -x "$basedir/node" ]; then
14
+ exec "$basedir/node" "$basedir/../../../../../../../astro/astro.js" "$@"
15
+ else
16
+ exec node "$basedir/../../../../../../../astro/astro.js" "$@"
17
+ fi
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@test/astro-cloudflare-basics",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@astrojs/cloudflare": "workspace:*",
7
+ "astro": "workspace:*"
8
+ }
9
+ }
@@ -0,0 +1,8 @@
1
+ <html>
2
+ <head>
3
+ <title>Testing</title>
4
+ </head>
5
+ <body>
6
+ <h1>Testing</h1>
7
+ </body>
8
+ </html>
@@ -0,0 +1,6 @@
1
+ import { defineConfig } from 'astro/config';
2
+ import cloudflare from '@astrojs/cloudflare';
3
+
4
+ export default defineConfig({
5
+ adapter: cloudflare()
6
+ });
@@ -0,0 +1,17 @@
1
+ #!/bin/sh
2
+ basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3
+
4
+ case `uname` in
5
+ *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
6
+ esac
7
+
8
+ if [ -z "$NODE_PATH" ]; then
9
+ export NODE_PATH="/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
10
+ else
11
+ export NODE_PATH="$NODE_PATH:/home/runner/work/astro/astro/node_modules/.pnpm/node_modules"
12
+ fi
13
+ if [ -x "$basedir/node" ]; then
14
+ exec "$basedir/node" "$basedir/../../../../../../../astro/astro.js" "$@"
15
+ else
16
+ exec node "$basedir/../../../../../../../astro/astro.js" "$@"
17
+ fi
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@test/astro-cloudflare-no-output",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@astrojs/cloudflare": "workspace:*",
7
+ "astro": "workspace:*"
8
+ }
9
+ }
@@ -0,0 +1,24 @@
1
+ import { loadFixture } from './test-utils.js';
2
+ import { expect } from 'chai';
3
+
4
+ describe('Missing output config', () => {
5
+ /** @type {import('./test-utils').Fixture} */
6
+ let fixture;
7
+
8
+ before(async () => {
9
+ fixture = await loadFixture({
10
+ root: './fixtures/no-output/',
11
+ });
12
+ });
13
+
14
+ it('throws during the build', async () => {
15
+ let error = undefined;
16
+ try {
17
+ await fixture.build();
18
+ } catch (err) {
19
+ error = err;
20
+ }
21
+ expect(error).to.not.be.equal(undefined);
22
+ expect(error.message).to.include(`output: "server"`);
23
+ });
24
+ });
@@ -0,0 +1,62 @@
1
+ import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
2
+ import { spawn } from 'child_process';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ export { fixLineEndings } from '../../../astro/test/test-utils.js';
6
+
7
+ export function loadFixture(config) {
8
+ if (config?.root) {
9
+ config.root = new URL(config.root, import.meta.url);
10
+ }
11
+ return baseLoadFixture(config);
12
+ }
13
+
14
+ const wranglerPath = fileURLToPath(
15
+ new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url)
16
+ );
17
+
18
+ export function runCLI(basePath, { silent }) {
19
+ const script = fileURLToPath(new URL(`${basePath}/dist/_worker.js`, import.meta.url));
20
+ const p = spawn('node', [wranglerPath, 'dev', '-l', script]);
21
+
22
+ p.stderr.setEncoding('utf-8');
23
+ p.stdout.setEncoding('utf-8');
24
+
25
+ const timeout = 10000;
26
+
27
+ const ready = new Promise(async (resolve, reject) => {
28
+ const failed = setTimeout(
29
+ () => reject(new Error(`Timed out starting the wrangler CLI`)),
30
+ timeout
31
+ );
32
+
33
+ (async function () {
34
+ for (const msg of p.stderr) {
35
+ if (!silent) {
36
+ // eslint-disable-next-line
37
+ console.error(msg);
38
+ }
39
+ }
40
+ })();
41
+
42
+ for await (const msg of p.stdout) {
43
+ if (!silent) {
44
+ // eslint-disable-next-line
45
+ console.log(msg);
46
+ }
47
+ if (msg.includes(`Listening on`)) {
48
+ break;
49
+ }
50
+ }
51
+
52
+ clearTimeout(failed);
53
+ resolve();
54
+ });
55
+
56
+ return {
57
+ ready,
58
+ stop() {
59
+ p.kill();
60
+ },
61
+ };
62
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "include": ["src"],
4
+ "compilerOptions": {
5
+ "allowJs": true,
6
+ "module": "ES2020",
7
+ "outDir": "./dist",
8
+ "target": "ES2020"
9
+ }
10
+ }