2023-06-20 10:26:55 +00:00
|
|
|
import type { EventContext, Request as CFRequest } from '@cloudflare/workers-types';
|
2023-06-13 20:37:42 +00:00
|
|
|
import type { SSRManifest } from 'astro';
|
2022-06-16 14:12:25 +00:00
|
|
|
import { App } from 'astro/app';
|
2023-01-26 17:43:39 +00:00
|
|
|
import { getProcessEnvProxy, isNode } from './util.js';
|
2022-11-08 13:54:49 +00:00
|
|
|
|
2023-01-26 17:45:39 +00:00
|
|
|
if (!isNode) {
|
2023-01-26 17:43:39 +00:00
|
|
|
process.env = getProcessEnvProxy();
|
|
|
|
}
|
2022-06-16 14:12:25 +00:00
|
|
|
|
|
|
|
export function createExports(manifest: SSRManifest) {
|
2023-01-26 13:44:09 +00:00
|
|
|
const app = new App(manifest);
|
2022-08-08 17:10:48 +00:00
|
|
|
|
|
|
|
const onRequest = async ({
|
|
|
|
request,
|
|
|
|
next,
|
2022-10-26 13:46:25 +00:00
|
|
|
...runtimeEnv
|
2022-08-08 17:10:48 +00:00
|
|
|
}: {
|
2023-06-13 20:34:44 +00:00
|
|
|
request: Request & CFRequest;
|
2022-08-08 17:10:48 +00:00
|
|
|
next: (request: Request) => void;
|
2023-06-20 10:24:32 +00:00
|
|
|
waitUntil: EventContext<unknown, any, unknown>['waitUntil'];
|
2022-10-26 13:46:25 +00:00
|
|
|
} & Record<string, unknown>) => {
|
2022-11-08 13:54:49 +00:00
|
|
|
process.env = runtimeEnv.env as any;
|
|
|
|
|
2022-11-21 13:31:21 +00:00
|
|
|
const { pathname } = new URL(request.url);
|
|
|
|
// static assets fallback, in case default _routes.json is not used
|
2022-06-16 14:12:25 +00:00
|
|
|
if (manifest.assets.has(pathname)) {
|
2022-11-21 13:31:21 +00:00
|
|
|
return next(request);
|
2022-06-16 14:12:25 +00:00
|
|
|
}
|
|
|
|
|
2022-07-22 20:30:17 +00:00
|
|
|
let routeData = app.match(request, { matchNotFound: true });
|
|
|
|
if (routeData) {
|
2022-07-19 20:11:53 +00:00
|
|
|
Reflect.set(
|
|
|
|
request,
|
|
|
|
Symbol.for('astro.clientAddress'),
|
|
|
|
request.headers.get('cf-connecting-ip')
|
|
|
|
);
|
2022-10-26 13:46:25 +00:00
|
|
|
Reflect.set(request, Symbol.for('runtime'), {
|
|
|
|
...runtimeEnv,
|
2023-06-20 10:24:32 +00:00
|
|
|
waitUntil: (promise: Promise<any>) => {
|
|
|
|
runtimeEnv.waitUntil(promise);
|
|
|
|
},
|
2022-10-26 13:46:25 +00:00
|
|
|
name: 'cloudflare',
|
|
|
|
next,
|
2023-06-13 20:34:44 +00:00
|
|
|
caches,
|
|
|
|
cf: request.cf,
|
2022-10-26 13:46:25 +00:00
|
|
|
});
|
2022-09-28 20:55:27 +00:00
|
|
|
let response = await app.render(request, routeData);
|
|
|
|
|
2022-09-28 20:57:35 +00:00
|
|
|
if (app.setCookieHeaders) {
|
|
|
|
for (const setCookieHeader of app.setCookieHeaders(response)) {
|
2022-09-28 20:55:27 +00:00
|
|
|
response.headers.append('Set-Cookie', setCookieHeader);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
2022-06-24 19:30:47 +00:00
|
|
|
}
|
|
|
|
|
2022-06-16 14:12:25 +00:00
|
|
|
return new Response(null, {
|
|
|
|
status: 404,
|
|
|
|
statusText: 'Not found',
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2023-06-30 09:09:21 +00:00
|
|
|
return { onRequest, manifest };
|
2022-06-16 14:12:25 +00:00
|
|
|
}
|