astro/packages/integrations/cloudflare/src/server.directory.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

66 lines
1.6 KiB
TypeScript
Raw Normal View History

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';
import { App } from 'astro/app';
import { getProcessEnvProxy, isNode } from './util.js';
2023-01-26 17:45:39 +00:00
if (!isNode) {
process.env = getProcessEnvProxy();
}
export function createExports(manifest: SSRManifest) {
const app = new App(manifest);
const onRequest = async ({
request,
next,
...runtimeEnv
}: {
request: Request & CFRequest;
next: (request: Request) => void;
waitUntil: EventContext<unknown, any, unknown>['waitUntil'];
} & Record<string, unknown>) => {
process.env = runtimeEnv.env as any;
const { pathname } = new URL(request.url);
// static assets fallback, in case default _routes.json is not used
if (manifest.assets.has(pathname)) {
return next(request);
}
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')
);
Reflect.set(request, Symbol.for('runtime'), {
...runtimeEnv,
waitUntil: (promise: Promise<any>) => {
runtimeEnv.waitUntil(promise);
},
name: 'cloudflare',
next,
caches,
cf: request.cf,
});
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)) {
response.headers.append('Set-Cookie', setCookieHeader);
}
}
return response;
}
return new Response(null, {
status: 404,
statusText: 'Not found',
});
};
return { onRequest, manifest };
}