-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
index.js
241 lines (207 loc) · 6.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { writeFileSync } from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as esbuild from 'esbuild';
import { getPlatformProxy } from 'wrangler';
// list from https://developers.cloudflare.com/workers/runtime-apis/nodejs/
const compatible_node_modules = [
'assert',
'async_hooks',
'buffer',
'crypto',
'diagnostics_channel',
'events',
'path',
'process',
'stream',
'string_decoder',
'util'
];
/** @type {import('./index.js').default} */
export default function (options = {}) {
return {
name: '@sveltejs/adapter-cloudflare',
async adapt(builder) {
const files = fileURLToPath(new URL('./files', import.meta.url).href);
const dest = builder.getBuildDirectory('cloudflare');
const tmp = builder.getBuildDirectory('cloudflare-tmp');
builder.rimraf(dest);
builder.rimraf(tmp);
builder.mkdirp(dest);
builder.mkdirp(tmp);
// generate plaintext 404.html first which can then be overridden by prerendering, if the user defined such a page
const fallback = path.join(dest, '404.html');
if (options.fallback === 'spa') {
await builder.generateFallback(fallback);
} else {
writeFileSync(fallback, 'Not Found');
}
const dest_dir = `${dest}${builder.config.kit.paths.base}`;
const written_files = builder.writeClient(dest_dir);
builder.writePrerendered(dest_dir);
const relativePath = path.posix.relative(tmp, builder.getServerDirectory());
writeFileSync(
`${tmp}/manifest.js`,
`export const manifest = ${builder.generateManifest({ relativePath })};\n\n` +
`export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n\n` +
`export const app_path = ${JSON.stringify(builder.getAppPath())};\n`
);
writeFileSync(
`${dest}/_routes.json`,
JSON.stringify(get_routes_json(builder, written_files, options.routes ?? {}), null, '\t')
);
writeFileSync(`${dest}/_headers`, generate_headers(builder.getAppPath()), { flag: 'a' });
builder.copy(`${files}/worker.js`, `${tmp}/_worker.js`, {
replace: {
SERVER: `${relativePath}/index.js`,
MANIFEST: './manifest.js'
}
});
const external = ['cloudflare:*', ...compatible_node_modules.map((id) => `node:${id}`)];
try {
const result = await esbuild.build({
platform: 'browser',
// https://github.com/cloudflare/workers-sdk/blob/a12b2786ce745f24475174bcec994ad691e65b0f/packages/wrangler/src/deployment-bundle/bundle.ts#L35-L36
conditions: ['workerd', 'worker', 'browser'],
sourcemap: 'linked',
target: 'es2022',
entryPoints: [`${tmp}/_worker.js`],
outfile: `${dest}/_worker.js`,
allowOverwrite: true,
format: 'esm',
bundle: true,
loader: {
'.wasm': 'copy'
},
external,
alias: Object.fromEntries(compatible_node_modules.map((id) => [id, `node:${id}`])),
logLevel: 'silent'
});
if (result.warnings.length > 0) {
const formatted = await esbuild.formatMessages(result.warnings, {
kind: 'warning',
color: true
});
console.error(formatted.join('\n'));
}
} catch (error) {
for (const e of error.errors) {
for (const node of e.notes) {
const match =
/The package "(.+)" wasn't found on the file system but is built into node/.exec(
node.text
);
if (match) {
node.text = `Cannot use "${match[1]}" when deploying to Cloudflare.`;
}
}
}
const formatted = await esbuild.formatMessages(error.errors, {
kind: 'error',
color: true
});
console.error(formatted.join('\n'));
throw new Error(
`Bundling with esbuild failed with ${error.errors.length} ${
error.errors.length === 1 ? 'error' : 'errors'
}`
);
}
},
async emulate() {
const proxy = await getPlatformProxy();
const platform = /** @type {App.Platform} */ ({
env: proxy.env,
context: proxy.ctx,
caches: proxy.caches,
cf: proxy.cf
});
/** @type {Record<string, any>} */
const env = {};
const prerender_platform = /** @type {App.Platform} */ (/** @type {unknown} */ ({ env }));
for (const key in proxy.env) {
Object.defineProperty(env, key, {
get: () => {
throw new Error(`Cannot access platform.env.${key} in a prerenderable route`);
}
});
}
return {
platform: ({ prerender }) => {
return prerender ? prerender_platform : platform;
}
};
}
};
}
/**
* @param {import('@sveltejs/kit').Builder} builder
* @param {string[]} assets
* @param {import('./index.js').AdapterOptions['routes']} routes
* @returns {import('./index.js').RoutesJSONSpec}
*/
function get_routes_json(builder, assets, { include = ['/*'], exclude = ['<all>'] }) {
if (!Array.isArray(include) || !Array.isArray(exclude)) {
throw new Error('routes.include and routes.exclude must be arrays');
}
if (include.length === 0) {
throw new Error('routes.include must contain at least one route');
}
if (include.length > 100) {
throw new Error('routes.include must contain 100 or fewer routes');
}
exclude = exclude
.flatMap((rule) => (rule === '<all>' ? ['<build>', '<files>', '<prerendered>'] : rule))
.flatMap((rule) => {
if (rule === '<build>') {
return `/${builder.getAppPath()}/*`;
}
if (rule === '<files>') {
return assets
.filter(
(file) =>
!(
file.startsWith(`${builder.config.kit.appDir}/`) ||
file === '_headers' ||
file === '_redirects'
)
)
.map((file) => `/${file}`);
}
if (rule === '<prerendered>') {
const prerendered = [];
for (const path of builder.prerendered.paths) {
if (!builder.prerendered.redirects.has(path)) {
prerendered.push(path);
}
}
return prerendered;
}
return rule;
});
const excess = include.length + exclude.length - 100;
if (excess > 0) {
const message = `Function includes/excludes exceeds _routes.json limits (see https://developers.cloudflare.com/pages/platform/functions/routing/#limits). Dropping ${excess} exclude rules — this will cause unnecessary function invocations.`;
builder.log.warn(message);
exclude.length -= excess;
}
return {
version: 1,
description: 'Generated by @sveltejs/adapter-cloudflare',
include,
exclude
};
}
/** @param {string} app_dir */
function generate_headers(app_dir) {
return `
# === START AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
/${app_dir}/*
X-Robots-Tag: noindex
Cache-Control: no-cache
/${app_dir}/immutable/*
! Cache-Control
Cache-Control: public, immutable, max-age=31536000
# === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
`.trimEnd();
}