-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathindex.ts
394 lines (361 loc) · 13 KB
/
index.ts
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import type {
AstroConfig,
AstroIntegration,
HookParameters,
IntegrationResolvedRoute,
IntegrationRouteData,
} from 'astro';
import type { PluginOption } from 'vite';
import { createReadStream } from 'node:fs';
import { appendFile, rename, stat } from 'node:fs/promises';
import { createInterface } from 'node:readline/promises';
import {
appendForwardSlash,
prependForwardSlash,
removeLeadingForwardSlash,
} from '@astrojs/internal-helpers/path';
import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
import { AstroError } from 'astro/errors';
import { defaultClientConditions } from 'vite';
import { type GetPlatformProxyOptions, getPlatformProxy } from 'wrangler';
import {
type CloudflareModulePluginExtra,
cloudflareModuleLoader,
} from './utils/cloudflare-module-loader.js';
import { createGetEnv } from './utils/env.js';
import { createRoutesFile, getParts } from './utils/generate-routes-json.js';
import { setImageConfig } from './utils/image-config.js';
export type { Runtime } from './entrypoints/server.js';
export type Options = {
/** Options for handling images. */
imageService?: 'passthrough' | 'cloudflare' | 'compile' | 'custom';
/** Configuration for `_routes.json` generation. A _routes.json file controls when your Function is invoked. This file will include three different properties:
*
* - version: Defines the version of the schema. Currently there is only one version of the schema (version 1), however, we may add more in the future and aim to be backwards compatible.
* - include: Defines routes that will be invoked by Functions. Accepts wildcard behavior.
* - exclude: Defines routes that will not be invoked by Functions. Accepts wildcard behavior. `exclude` always take priority over `include`.
*
* Wildcards match any number of path segments (slashes). For example, `/users/*` will match everything after the `/users/` path.
*
*/
routes?: {
/** Extend `_routes.json` */
extend: {
/** Paths which should be routed to the SSR function */
include?: {
/** Generally this is in pathname format, but does support wildcards, e.g. `/users`, `/products/*` */
pattern: string;
}[];
/** Paths which should be routed as static assets */
exclude?: {
/** Generally this is in pathname format, but does support wildcards, e.g. `/static`, `/assets/*`, `/images/avatar.jpg` */
pattern: string;
}[];
};
};
/**
* Proxy configuration for the platform.
*/
platformProxy?: GetPlatformProxyOptions & {
/** Toggle the proxy. Default `undefined`, which equals to `true`. */
enabled?: boolean;
};
/**
* Allow bundling cloudflare worker specific file types as importable modules. Defaults to true.
* When enabled, allows imports of '.wasm', '.bin', and '.txt' file types
*
* See https://developers.cloudflare.com/pages/functions/module-support/
* for reference on how these file types are exported
*/
cloudflareModules?: boolean;
};
function wrapWithSlashes(path: string): string {
return prependForwardSlash(appendForwardSlash(path));
}
function setProcessEnv(config: AstroConfig, env: Record<string, unknown>) {
const getEnv = createGetEnv(env);
if (config.env?.schema) {
for (const key of Object.keys(config.env.schema)) {
const value = getEnv(key);
if (value !== undefined) {
process.env[key] = value;
}
}
}
}
function resolvedRouteToRouteData(
assets: HookParameters<'astro:build:done'>['assets'],
route: IntegrationResolvedRoute
): IntegrationRouteData {
return {
pattern: route.patternRegex,
component: route.entrypoint,
prerender: route.isPrerendered,
route: route.pattern,
generate: route.generate,
params: route.params,
segments: route.segments,
type: route.type,
pathname: route.pathname,
redirect: route.redirect,
distURL: assets.get(route.pattern),
redirectRoute: route.redirectRoute
? resolvedRouteToRouteData(assets, route.redirectRoute)
: undefined,
};
}
export default function createIntegration(args?: Options): AstroIntegration {
let _config: AstroConfig;
let finalBuildOutput: HookParameters<'astro:config:done'>['buildOutput'];
const cloudflareModulePlugin: PluginOption & CloudflareModulePluginExtra = cloudflareModuleLoader(
args?.cloudflareModules ?? true
);
let _routes: IntegrationResolvedRoute[];
return {
name: '@astrojs/cloudflare',
hooks: {
'astro:config:setup': ({
command,
config,
updateConfig,
logger,
addWatchFile,
addMiddleware,
}) => {
updateConfig({
build: {
client: new URL(`.${wrapWithSlashes(config.base)}`, config.outDir),
server: new URL('./_worker.js/', config.outDir),
serverEntry: 'index.js',
redirects: false,
},
vite: {
plugins: [
// https://developers.cloudflare.com/pages/functions/module-support/
// Allows imports of '.wasm', '.bin', and '.txt' file types
cloudflareModulePlugin,
{
name: 'vite:cf-imports',
enforce: 'pre',
resolveId(source) {
if (source.startsWith('cloudflare:')) {
return { id: source, external: true };
}
return null;
},
},
],
},
image: setImageConfig(args?.imageService ?? 'compile', config.image, command, logger),
});
if (args?.platformProxy?.configPath) {
addWatchFile(new URL(args.platformProxy.configPath, config.root));
} else {
addWatchFile(new URL('./wrangler.toml', config.root));
addWatchFile(new URL('./wrangler.json', config.root));
addWatchFile(new URL('./wrangler.jsonc', config.root));
}
addMiddleware({
entrypoint: '@astrojs/cloudflare/entrypoints/middleware.js',
order: 'pre',
});
},
'astro:routes:resolved': ({ routes }) => {
_routes = routes;
},
'astro:config:done': ({ setAdapter, config, buildOutput, logger }) => {
if (buildOutput === 'static') {
logger.warn(
'[@astrojs/cloudflare] This adapter is intended to be used with server rendered pages, which this project does not contain any of. As such, this adapter is unnecessary.'
);
}
_config = config;
finalBuildOutput = buildOutput;
setAdapter({
name: '@astrojs/cloudflare',
serverEntrypoint: '@astrojs/cloudflare/entrypoints/server.js',
exports: ['default'],
adapterFeatures: {
edgeMiddleware: false,
buildOutput: 'server',
},
supportedAstroFeatures: {
serverOutput: 'stable',
hybridOutput: 'stable',
staticOutput: 'unsupported',
i18nDomains: 'experimental',
sharpImageService: {
support: 'limited',
message:
'Cloudflare does not support sharp. You can use the `compile` image service to compile images at build time. It will not work for any on-demand rendered images.',
},
envGetSecret: 'stable',
},
});
},
'astro:server:setup': async ({ server }) => {
if ((args?.platformProxy?.enabled ?? true) === true) {
const platformProxy = await getPlatformProxy(args?.platformProxy);
setProcessEnv(_config, platformProxy.env);
const clientLocalsSymbol = Symbol.for('astro.locals');
server.middlewares.use(async function middleware(req, res, next) {
Reflect.set(req, clientLocalsSymbol, {
runtime: {
env: platformProxy.env,
cf: platformProxy.cf,
caches: platformProxy.caches,
ctx: {
waitUntil: (promise: Promise<any>) => platformProxy.ctx.waitUntil(promise),
// Currently not available: https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions
passThroughOnException: () => {
throw new AstroError(
'`passThroughOnException` is currently not available in Cloudflare Pages. See https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions.'
);
},
},
},
});
next();
});
}
},
'astro:build:setup': ({ vite, target }) => {
if (target === 'server') {
vite.resolve ||= {};
vite.resolve.alias ||= {};
const aliases = [
{
find: 'react-dom/server',
replacement: 'react-dom/server.browser',
},
];
if (Array.isArray(vite.resolve.alias)) {
vite.resolve.alias = [...vite.resolve.alias, ...aliases];
} else {
for (const alias of aliases) {
(vite.resolve.alias as Record<string, string>)[alias.find] = alias.replacement;
}
}
// Support `workerd` and `worker` conditions for the ssr environment
// (previously supported in esbuild instead: https://github.com/withastro/astro/pull/7092)
vite.ssr ||= {};
vite.ssr.resolve ||= {};
vite.ssr.resolve.conditions ||= [...defaultClientConditions];
vite.ssr.resolve.conditions.push('workerd', 'worker');
vite.ssr.target = 'webworker';
vite.ssr.noExternal = true;
if (typeof _config.vite.ssr?.external === 'undefined') vite.ssr.external = [];
if (typeof _config.vite.ssr?.external === 'boolean')
vite.ssr.external = _config.vite.ssr?.external;
if (Array.isArray(_config.vite.ssr?.external))
// `@astrojs/vue` sets `@vue/server-renderer` to external
// https://github.com/withastro/astro/blob/e648c5575a8774af739231cfa9fc27a32086aa5f/packages/integrations/vue/src/index.ts#L119
// the cloudflare adapter needs to get all dependencies inlined, we use `noExternal` for that, but any `external` config overrides that
// therefore we need to remove `@vue/server-renderer` from the external config again
vite.ssr.external = _config.vite.ssr?.external.filter(
(entry) => entry !== '@vue/server-renderer'
);
vite.build ||= {};
vite.build.rollupOptions ||= {};
vite.build.rollupOptions.output ||= {};
// @ts-expect-error
vite.build.rollupOptions.output.banner ||=
'globalThis.process ??= {}; globalThis.process.env ??= {};';
vite.build.rollupOptions.external = _config.vite.build?.rollupOptions?.external ?? [];
// Cloudflare env is only available per request. This isn't feasible for code that access env vars
// in a global way, so we shim their access as `process.env.*`. This is not the recommended way for users to access environment variables. But we'll add this for compatibility for chosen variables. Mainly to support `@astrojs/db`
vite.define = {
'process.env': 'process.env',
...vite.define,
};
}
},
'astro:build:done': async ({ pages, dir, logger, assets }) => {
await cloudflareModulePlugin.afterBuildCompleted(_config);
const PLATFORM_FILES = ['_headers', '_redirects', '_routes.json'];
if (_config.base !== '/') {
for (const file of PLATFORM_FILES) {
try {
await rename(new URL(file, _config.build.client), new URL(file, _config.outDir));
} catch (e) {
logger.error(
`There was an error moving ${file} to the root of the output directory.`
);
}
}
}
let redirectsExists = false;
try {
const redirectsStat = await stat(new URL('./_redirects', _config.outDir));
if (redirectsStat.isFile()) {
redirectsExists = true;
}
} catch (error) {
redirectsExists = false;
}
const redirects: IntegrationResolvedRoute['segments'][] = [];
if (redirectsExists) {
const rl = createInterface({
input: createReadStream(new URL('./_redirects', _config.outDir)),
crlfDelay: Number.POSITIVE_INFINITY,
});
for await (const line of rl) {
const parts = line.split(' ');
if (parts.length >= 2) {
const p = removeLeadingForwardSlash(parts[0])
.split('/')
.filter(Boolean)
.map((s: string) => {
const syntax = s
.replace(/\/:.*?(?=\/|$)/g, '/*')
// remove query params as they are not supported by cloudflare
.replace(/\?.*$/, '');
return getParts(syntax);
});
redirects.push(p);
}
}
}
let routesExists = false;
try {
const routesStat = await stat(new URL('./_routes.json', _config.outDir));
if (routesStat.isFile()) {
routesExists = true;
}
} catch (error) {
routesExists = false;
}
if (!routesExists) {
await createRoutesFile(
_config,
logger,
_routes,
pages,
redirects,
args?.routes?.extend?.include,
args?.routes?.extend?.exclude
);
}
const redirectRoutes: [IntegrationRouteData, string][] = [];
for (const route of _routes) {
// TODO: Replace workaround after upstream @astrojs/underscore-redirects is changed, to support new IntegrationResolvedRoute type
if (route.type === 'redirect')
redirectRoutes.push([resolvedRouteToRouteData(assets, route), '']);
}
const trueRedirects = createRedirectsFromAstroRoutes({
config: _config,
routeToDynamicTargetMap: new Map(Array.from(redirectRoutes)),
dir,
buildOutput: finalBuildOutput,
});
if (!trueRedirects.empty()) {
try {
await appendFile(new URL('./_redirects', _config.outDir), trueRedirects.print());
} catch (error) {
logger.error('Failed to write _redirects file');
}
}
},
},
};
}