Skip to content

Commit 9b8a9a4

Browse files
committed
Update and modernize adapter-cloudflare-workers
1 parent f0df782 commit 9b8a9a4

File tree

11 files changed

+283
-152
lines changed

11 files changed

+283
-152
lines changed

.changeset/tidy-paws-rest.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/adapter-cloudflare-workers': patch
3+
---
4+
5+
Update adapter to use modules API and match the standard adapter-cloudflare implementation more closely
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.DS_Store
22
node_modules
3-
target
3+
target
4+
/files

packages/adapter-cloudflare-workers/README.md

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,19 @@ export default {
3333

3434
**You will need [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/install-update) installed on your system**
3535

36-
This adapter expects to find a [wrangler.toml](https://developers.cloudflare.com/workers/platform/sites/configuration) file in the project root. It will determine where to write static assets and the worker based on the `site.bucket` and `site.entry-point` settings.
36+
This adapter expects to find a [wrangler.toml](https://developers.cloudflare.com/workers/platform/sites/configuration) file in the project root. It will determine where to write static assets and the worker based on the `site.bucket` and `build.upload` settings. These values must be set to the following:
3737

38-
Generate this file using `wrangler` from your project directory
38+
```toml
39+
[build.upload]
40+
format = "modules"
41+
dir = "./.svelte-kit/cloudflare"
42+
main = "./_worker.mjs"
43+
44+
[site]
45+
bucket = "./.svelte-kit/cloudflare-bucket"
46+
```
47+
48+
To get started, generate this file using `wrangler` from your project directory
3949

4050
```sh
4151
wrangler init --site my-site-name
@@ -48,24 +58,31 @@ Now you should get some details from Cloudflare. You should get your:
4858

4959
Get them by visiting your [Cloudflare dashboard](https://dash.cloudflare.com) and click on any domain. There, you can scroll down and on the left, you can see your details under **API**.
5060

51-
Then configure your sites build directory and your account-details in the config file:
61+
Then configure your account-details in the config file:
5262

5363
```toml
54-
account_id = 'YOUR ACCOUNT_ID'
55-
zone_id = 'YOUR ZONE_ID' # optional, if you don't specify this a workers.dev subdomain will be used.
56-
site = {bucket = "./build", entry-point = "./workers-site"}
57-
64+
name = "<your-site-name>"
5865
type = "javascript"
66+
account_id = "<your-account-id>"
67+
workers_dev = true
68+
route = ""
69+
zone_id = ""
70+
71+
compatibility_date = "2022-02-09"
5972

6073
[build]
6174
# Assume it's already been built. You can make this "npm run build" to ensure a build before publishing
6275
command = ""
6376

77+
# All values below here are required by adapter-cloudflare-workers and should not change
6478
[build.upload]
65-
format = "service-worker"
66-
```
79+
format = "modules"
80+
dir = "./.svelte-kit/cloudflare"
81+
main = "./_worker.mjs"
6782

68-
It's recommended that you add the `build` and `workers-site` folders (or whichever other folders you specify) to your `.gitignore`.
83+
[site]
84+
bucket = "./.svelte-kit/cloudflare-bucket"
85+
```
6986

7087
Now, log in with wrangler:
7188

packages/adapter-cloudflare-workers/ambient.d.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@ declare module 'MANIFEST' {
66
import { SSRManifest } from '@sveltejs/kit';
77

88
export const manifest: SSRManifest;
9-
export const prerendered: Set<string>;
9+
export const prerendered: Map<string, { file: string }>;
1010
}
1111

12-
declare abstract class FetchEvent extends Event {
13-
readonly request: Request;
14-
respondWith(promise: Response | Promise<Response>): void;
15-
passThroughOnException(): void;
16-
waitUntil(promise: Promise<any>): void;
12+
declare module '__STATIC_CONTENT_MANIFEST' {
13+
const value: string;
14+
export = value;
1715
}

packages/adapter-cloudflare-workers/files/entry.js

Lines changed: 0 additions & 61 deletions
This file was deleted.
Lines changed: 126 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,34 @@
11
import { existsSync, readFileSync, writeFileSync } from 'fs';
22
import { posix } from 'path';
33
import { execSync } from 'child_process';
4-
import esbuild from 'esbuild';
4+
import * as esbuild from 'esbuild';
55
import toml from '@iarna/toml';
66
import { fileURLToPath } from 'url';
77

88
/** @type {import('.')} */
9-
export default function () {
9+
export default function (options = {}) {
1010
return {
1111
name: '@sveltejs/adapter-cloudflare-workers',
12-
1312
async adapt(builder) {
14-
const { site } = validate_config(builder);
15-
16-
// @ts-ignore
17-
const { bucket } = site;
13+
validate_config(builder);
1814

1915
// @ts-ignore
20-
const entrypoint = site['entry-point'] || 'workers-site';
21-
2216
const files = fileURLToPath(new URL('./files', import.meta.url).href);
23-
const tmp = builder.getBuildDirectory('cloudflare-workers-tmp');
17+
const dest = builder.getBuildDirectory('cloudflare');
18+
const bucket = builder.getBuildDirectory('cloudflare-bucket');
19+
const tmp = builder.getBuildDirectory('cloudflare-tmp');
2420

21+
builder.rimraf(dest);
2522
builder.rimraf(bucket);
26-
builder.rimraf(entrypoint);
23+
builder.rimraf(tmp);
24+
25+
builder.mkdirp(tmp);
26+
27+
builder.writeStatic(bucket);
28+
builder.writeClient(bucket);
29+
builder.writePrerendered(bucket);
30+
31+
const relativePath = posix.relative(tmp, builder.getServerDirectory());
2732

2833
builder.log.info('Installing worker dependencies...');
2934
builder.copy(`${files}/_package.json`, `${tmp}/package.json`);
@@ -33,83 +38,136 @@ export default function () {
3338
builder.log.info(stdout.toString());
3439

3540
builder.log.minor('Generating worker...');
36-
const relativePath = posix.relative(tmp, builder.getServerDirectory());
3741

38-
builder.copy(`${files}/entry.js`, `${tmp}/entry.js`, {
42+
writeFileSync(
43+
`${tmp}/manifest.js`,
44+
`export const manifest = ${builder.generateManifest({
45+
relativePath
46+
})};\n\nexport const prerendered = new Map(${JSON.stringify(
47+
Array.from(builder.prerendered.pages.entries())
48+
)});\n`
49+
);
50+
51+
builder.copy(`${files}/worker.js`, `${tmp}/_worker.js`, {
3952
replace: {
4053
SERVER: `${relativePath}/index.js`,
4154
MANIFEST: './manifest.js'
4255
}
4356
});
4457

45-
writeFileSync(
46-
`${tmp}/manifest.js`,
47-
`export const manifest = ${builder.generateManifest({
48-
relativePath
49-
})};\n\nexport const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n`
50-
);
58+
const external = ['__STATIC_CONTENT_MANIFEST'];
59+
60+
if (options.external) {
61+
external.push(...options.external);
62+
}
5163

5264
await esbuild.build({
53-
entryPoints: [`${tmp}/entry.js`],
54-
outfile: `${entrypoint}/index.js`,
55-
bundle: true,
5665
target: 'es2020',
57-
platform: 'browser'
66+
platform: 'browser',
67+
...options,
68+
entryPoints: [`${tmp}/_worker.js`],
69+
external,
70+
outfile: `${dest}/_worker.mjs`,
71+
allowOverwrite: true,
72+
format: 'esm',
73+
bundle: true
5874
});
59-
60-
writeFileSync(`${entrypoint}/package.json`, JSON.stringify({ main: 'index.js' }));
61-
62-
builder.log.minor('Copying assets...');
63-
builder.writeClient(bucket);
64-
builder.writeStatic(bucket);
65-
builder.writePrerendered(bucket);
6675
}
6776
};
6877
}
6978

7079
/** @param {import('@sveltejs/kit').Builder} builder */
7180
function validate_config(builder) {
72-
if (existsSync('wrangler.toml')) {
73-
let wrangler_config;
74-
75-
try {
76-
wrangler_config = toml.parse(readFileSync('wrangler.toml', 'utf-8'));
77-
} catch (err) {
78-
err.message = `Error parsing wrangler.toml: ${err.message}`;
79-
throw err;
80-
}
81+
if (!existsSync('wrangler.toml')) {
82+
builder.log.error(
83+
'Consult https://developers.cloudflare.com/workers/platform/sites/configuration on how to setup your site'
84+
);
85+
86+
builder.log(
87+
`
88+
Sample wrangler.toml:
89+
90+
name = "<your-site-name>"
91+
type = "javascript"
92+
account_id = "<your-account-id>"
93+
workers_dev = true
94+
route = ""
95+
zone_id = ""
96+
97+
compatibility_date = "2022-02-09"
98+
99+
[build]
100+
# Assume it's already been built. You can make this "npm run build" to ensure a build before publishing
101+
command = ""
102+
103+
# All values below here are required by adapter-cloudflare-workers and should not change
104+
[build.upload]
105+
format = "modules"
106+
dir = "./.svelte-kit/cloudflare"
107+
main = "./_worker.mjs"
108+
109+
[site]
110+
bucket = "./.svelte-kit/cloudflare-bucket"`
111+
.replace(/^\t+/gm, '')
112+
.trim()
113+
);
114+
115+
throw new Error('Missing a wrangler.toml file');
116+
}
117+
118+
let wrangler_config;
119+
120+
try {
121+
wrangler_config = toml.parse(readFileSync('wrangler.toml', 'utf-8'));
122+
} catch (err) {
123+
err.message = `Error parsing wrangler.toml: ${err.message}`;
124+
throw err;
125+
}
126+
127+
// @ts-ignore
128+
if (!wrangler_config.site || wrangler_config.site.bucket !== './.svelte-kit/cloudflare-bucket') {
129+
throw new Error(
130+
'You must specify site.bucket in wrangler.toml, and it must equal "./.svelte-kit/cloudflare-bucket"'
131+
);
132+
}
81133

134+
// @ts-ignore
135+
if (
82136
// @ts-ignore
83-
if (!wrangler_config.site || !wrangler_config.site.bucket) {
84-
throw new Error(
85-
'You must specify site.bucket in wrangler.toml. Consult https://developers.cloudflare.com/workers/platform/sites/configuration'
86-
);
87-
}
137+
!wrangler_config.build ||
138+
// @ts-ignore
139+
!wrangler_config.build.upload ||
140+
// @ts-ignore
141+
wrangler_config.build.upload.format !== 'modules'
142+
) {
143+
throw new Error(
144+
'You must specify build.upload.format in wrangler.toml, and it must equal "modules"'
145+
);
146+
}
88147

89-
return wrangler_config;
148+
if (
149+
// @ts-ignore
150+
!wrangler_config.build ||
151+
// @ts-ignore
152+
!wrangler_config.build.upload ||
153+
// @ts-ignore
154+
wrangler_config.build.upload.dir !== './.svelte-kit/cloudflare'
155+
) {
156+
throw new Error(
157+
'You must specify build.upload.dir in wrangler.toml, and it must equal "./.svelte-kit/cloudflare"'
158+
);
90159
}
91160

92-
builder.log.error(
93-
'Consult https://developers.cloudflare.com/workers/platform/sites/configuration on how to setup your site'
94-
);
95-
96-
builder.log(
97-
`
98-
Sample wrangler.toml:
99-
100-
name = "<your-site-name>"
101-
type = "javascript"
102-
account_id = "<your-account-id>"
103-
workers_dev = true
104-
route = ""
105-
zone_id = ""
106-
107-
[site]
108-
bucket = "./.cloudflare/assets"
109-
entry-point = "./.cloudflare/worker"`
110-
.replace(/^\t+/gm, '')
111-
.trim()
112-
);
113-
114-
throw new Error('Missing a wrangler.toml file');
161+
if (
162+
// @ts-ignore
163+
!wrangler_config.build ||
164+
// @ts-ignore
165+
!wrangler_config.build.upload ||
166+
// @ts-ignore
167+
wrangler_config.build.upload.main !== './_worker.mjs'
168+
) {
169+
throw new Error(
170+
'You must specify build.upload.main in wrangler.toml, and it must equal "./_worker.mjs"'
171+
);
172+
}
115173
}

0 commit comments

Comments
 (0)