Skip to content
This repository has been archived by the owner on Feb 10, 2025. It is now read-only.

chore: update adapters to better support astro v5 #454

Merged
merged 21 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { AstroConfig, AstroIntegration, IntegrationRouteData } from 'astro';
import type {
AstroConfig,
AstroIntegration,
IntegrationResolvedRoute,
IntegrationRouteData,
} from 'astro';
import type { PluginOption } from 'vite';

import { createReadStream } from 'node:fs';
Expand All @@ -21,6 +26,7 @@ import { createGetEnv } from './utils/env.js';
import { createRoutesFile, getParts } from './utils/generate-routes-json.js';
import { setImageConfig } from './utils/image-config.js';

export type IntegrationResolvedRouteWithDistUrl = IntegrationResolvedRoute & { distURL?: URL[] };
export type { Runtime } from './entrypoints/server.js';

export type Options = {
Expand Down Expand Up @@ -92,6 +98,8 @@ export default function createIntegration(args?: Options): AstroIntegration {
args?.cloudflareModules ?? true
);

let _routes: IntegrationResolvedRouteWithDistUrl[];

return {
name: '@astrojs/cloudflare',
hooks: {
Expand Down Expand Up @@ -137,6 +145,9 @@ export default function createIntegration(args?: Options): AstroIntegration {
order: 'pre',
});
},
'astro:routes:resolved': ({ routes }) => {
_routes = routes;
},
'astro:config:done': ({ setAdapter, config, buildOutput, logger }) => {
if (buildOutput === 'static') {
logger.warn(
Expand Down Expand Up @@ -266,7 +277,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
vite.build.rollupOptions.output ||= {};
}
},
'astro:build:done': async ({ pages, routes, dir, logger }) => {
'astro:build:done': async ({ pages, dir, logger, assets }) => {
await cloudflareModulePlugin.afterBuildCompleted(_config);
const PLATFORM_FILES = ['_headers', '_redirects', '_routes.json'];
if (_config.base !== '/') {
Expand All @@ -291,7 +302,7 @@ export default function createIntegration(args?: Options): AstroIntegration {
redirectsExists = false;
}

const redirects: IntegrationRouteData['segments'][] = [];
const redirects: IntegrationResolvedRoute['segments'][] = [];
if (redirectsExists) {
const rl = createInterface({
input: createReadStream(new URL('./_redirects', _config.outDir)),
Expand Down Expand Up @@ -327,10 +338,16 @@ export default function createIntegration(args?: Options): AstroIntegration {
}

if (!routesExists) {
for (const route of _routes) {
const distURL = assets.get(route.pattern);
if (distURL) {
Object.assign(route, { distURL });
}
}
await createRoutesFile(
_config,
logger,
routes,
_routes,
pages,
redirects,
args?.routes?.extend?.include,
Expand All @@ -339,8 +356,22 @@ export default function createIntegration(args?: Options): AstroIntegration {
}

const redirectRoutes: [IntegrationRouteData, string][] = [];
for (const route of routes) {
if (route.type === 'redirect') redirectRoutes.push([route, '']);
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([
{
pattern: route.patternRegex,
component: route.entrypoint,
prerender: route.isPrerendered,
route: route.pattern,
generate: route.generate,
params: route.params,
segments: route.segments,
type: route.type,
},
'',
]);
}

const trueRedirects = createRedirectsFromAstroRoutes({
Expand Down
18 changes: 11 additions & 7 deletions packages/cloudflare/src/utils/generate-routes-json.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { AstroConfig, AstroIntegrationLogger, IntegrationRouteData, RoutePart } from 'astro';
import type { AstroConfig, AstroIntegrationLogger, RoutePart } from 'astro';
import type { IntegrationResolvedRouteWithDistUrl } from '../index.js';

import { existsSync } from 'node:fs';
import { writeFile } from 'node:fs/promises';
Expand Down Expand Up @@ -63,7 +64,10 @@ async function writeRoutesFileToOutDir(
}
}

function segmentsToCfSyntax(segments: IntegrationRouteData['segments'], _config: AstroConfig) {
function segmentsToCfSyntax(
segments: IntegrationResolvedRouteWithDistUrl['segments'],
_config: AstroConfig
) {
const pathSegments = [];
if (removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)).length > 0) {
pathSegments.push(removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)));
Expand Down Expand Up @@ -163,11 +167,11 @@ class PathTrie {
export async function createRoutesFile(
_config: AstroConfig,
logger: AstroIntegrationLogger,
routes: IntegrationRouteData[],
routes: IntegrationResolvedRouteWithDistUrl[],
pages: {
pathname: string;
}[],
redirects: IntegrationRouteData['segments'][],
redirects: IntegrationResolvedRouteWithDistUrl['segments'][],
includeExtends:
| {
pattern: string;
Expand Down Expand Up @@ -223,17 +227,17 @@ export async function createRoutesFile(
let hasPrerendered404 = false;
for (const route of routes) {
const convertedPath = segmentsToCfSyntax(route.segments, _config);
if (route.pathname === '/404' && route.prerender === true) hasPrerendered404 = true;
if (route.pathname === '/404' && route.isPrerendered === true) hasPrerendered404 = true;

// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (route.type) {
case 'page':
if (route.prerender === false) includePaths.push(convertedPath);
if (route.isPrerendered === false) includePaths.push(convertedPath);

break;

case 'endpoint':
if (route.prerender === false) includePaths.push(convertedPath);
if (route.isPrerendered === false) includePaths.push(convertedPath);
else excludePaths.push(convertedPath);

break;
Expand Down
Loading