Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(next): astro:routes:resolved #12329

Merged
merged 29 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
621d2d2
feat: work on astro:routes:resolved
florian-lefebvre Oct 28, 2024
fbb04e9
feat: work on jsdoc
florian-lefebvre Oct 29, 2024
98e77c9
feat: support origin
florian-lefebvre Oct 29, 2024
96f560b
misc
florian-lefebvre Oct 29, 2024
65f5b60
feat: add test
florian-lefebvre Oct 29, 2024
75a84dc
feat: add changeset
florian-lefebvre Oct 29, 2024
3a3b083
Update packages/astro/src/types/public/integrations.ts
florian-lefebvre Nov 1, 2024
ec16abf
feat: rename property
florian-lefebvre Nov 1, 2024
ce0fc54
Merge branch 'next' into feat/routes-resolved
florian-lefebvre Nov 1, 2024
7e26fa4
feat: handle partial manifest updates in dev
florian-lefebvre Nov 1, 2024
319b405
Merge branch 'next' into feat/routes-resolved
florian-lefebvre Nov 13, 2024
db92a98
feat: include more properties and rename origin things
florian-lefebvre Nov 13, 2024
fc4e42c
feat: update origin
florian-lefebvre Nov 13, 2024
ebb12f9
feat: deprecate properties instead of whole object
florian-lefebvre Nov 13, 2024
b377e0f
Update packages/astro/src/types/public/internal.ts
florian-lefebvre Nov 13, 2024
33b1165
feat: update test
florian-lefebvre Nov 13, 2024
5576af9
feat: work on test
florian-lefebvre Nov 13, 2024
46be686
feat: new assets
florian-lefebvre Nov 14, 2024
c9dcd7c
fix: test
florian-lefebvre Nov 14, 2024
24600f0
fix: take dev routes into account
florian-lefebvre Nov 14, 2024
ea9abf4
Merge branch 'next' into feat/routes-resolved
florian-lefebvre Nov 14, 2024
93a69e2
Update packages/astro/src/vite-plugin-astro-server/plugin.ts
florian-lefebvre Nov 15, 2024
e837aff
feat: address review
florian-lefebvre Nov 15, 2024
7db88f9
Merge branch 'next' into feat/routes-resolved
florian-lefebvre Nov 18, 2024
12088d0
fix: check and calls
florian-lefebvre Nov 18, 2024
e1f53d5
feat: address reviews
florian-lefebvre Nov 19, 2024
539d40f
Apply suggestions from code review
florian-lefebvre Nov 19, 2024
846c3a7
fix: normalize paths
florian-lefebvre Nov 20, 2024
cd62268
Merge branch 'next' into feat/routes-resolved
florian-lefebvre Nov 20, 2024
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
11 changes: 9 additions & 2 deletions .changeset/giant-ravens-look.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
'astro': minor
---

Adds a new `astro:routes:resolved` hook to the Integration API, and deprecates `routes` passed to `astro:build:done`
Adds a new `astro:routes:resolved` hook to the Integration API. Makes updates to the `astro:build:done` hook by deprecating `routes` and adding a new `assets` map
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

When building an integration, you can now get access to routes inside the `astro:routes:resolved` hook:

Expand All @@ -21,7 +21,7 @@ const integration = () => {

This hook runs before `astro:config:done`, and whenever a route changes in development.

`routes` from `astro:build:done` is now deprecated. We recommend you use the new hook instead:
The `routes` array from `astro:build:done` are now deprecated. Any useful property is made available on `astro:routes:resolved`, except for `distURL`. Instead, you can use the newly exposed `assets` map::
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

```diff
const integration = () => {
Expand All @@ -34,7 +34,14 @@ const integration = () => {
+ },
'astro:build:done': ({
- routes
+ assets
}) => {
+ for (const route of routes) {
+ const distURL = assets.get(route.pattern)
+ if (distURL) {
+ Object.assign(route, { distURL })
+ }
+ }
console.log(routes)
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/actions/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export default function astroIntegrationActionsRouteHandler({
hooks: {
async 'astro:config:setup'(params) {
settings.injectedRoutes.push({
pattern: '/_actions/[...path]',
pattern: ACTION_RPC_ROUTE_PATTERN,
entrypoint: 'astro/actions/runtime/route.js',
prerender: false,
origin: 'core',
origin: 'internal',
});

params.addMiddleware({
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/assets/endpoint/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,6 @@ function getImageEndpointData(
pathname: settings.config.image.endpoint.route,
prerender: false,
fallbackRoutes: [],
origin: 'core',
origin: 'internal',
};
}
2 changes: 1 addition & 1 deletion packages/astro/src/container/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ export class experimental_AstroContainer {
type,
fallbackRoutes: [],
isIndex: false,
origin: 'user',
origin: 'internal',
};
}

Expand Down
4 changes: 3 additions & 1 deletion packages/astro/src/core/dev/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as vite from 'vite';
import {
runHookConfigDone,
runHookConfigSetup,
runHookRoutesResolved,
runHookServerDone,
runHookServerStart,
} from '../../integrations/hooks.js';
Expand Down Expand Up @@ -83,10 +84,11 @@ export async function createContainer({
.filter(Boolean) as string[];

// Create the route manifest already outside of Vite so that `runHookConfigDone` can use it to inform integrations of the build output
let manifest = await createRouteManifest({ settings, fsMod: fs }, logger);
let manifest = await createRouteManifest({ settings, fsMod: fs }, logger, { dev: true });
const devSSRManifest = createDevelopmentManifest(settings);

manifest = injectDefaultDevRoutes(settings, devSSRManifest, manifest);
await runHookRoutesResolved({ settings, logger, routes: manifest.routes });

await runHookConfigDone({ settings, logger, command: 'dev' });

Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/routing/astro-designed-error-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const DEFAULT_404_ROUTE: RouteData = {
route: '/404',
fallbackRoutes: [],
isIndex: false,
origin: 'core',
origin: 'internal',
};

export const DEFAULT_500_ROUTE: RouteData = {
Expand All @@ -30,7 +30,7 @@ export const DEFAULT_500_ROUTE: RouteData = {
route: '/500',
fallbackRoutes: [],
isIndex: false,
origin: 'core',
origin: 'internal',
};

export function ensure404Route(manifest: ManifestData) {
Expand Down
9 changes: 6 additions & 3 deletions packages/astro/src/core/routing/manifest/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ function createFileBasedRoutes(
prerender,
fallbackRoutes: [],
distURL: [],
origin: 'user',
origin: 'project',
});
}
}
Expand Down Expand Up @@ -392,7 +392,7 @@ function createRedirectRoutes(
redirectRoute: routeMap.get(destination),
fallbackRoutes: [],
distURL: [],
origin: 'user',
origin: 'project',
});
}

Expand Down Expand Up @@ -484,6 +484,7 @@ function detectRouteCollision(a: RouteData, b: RouteData, _config: AstroConfig,
export async function createRouteManifest(
params: CreateRouteManifestParams,
logger: Logger,
{ dev = false }: { dev?: boolean } = {},
): Promise<ManifestData> {
const { settings } = params;
const { config } = settings;
Expand Down Expand Up @@ -731,7 +732,9 @@ export async function createRouteManifest(
}
}

await runHookRoutesResolved({ routes, settings, logger });
if (!dev) {
await runHookRoutesResolved({ routes, settings, logger });
}

return {
routes,
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/server-islands/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function getServerIslandRouteData(config: ConfigFields) {
isIndex: false,
fallbackRoutes: [],
route: SERVER_ISLAND_ROUTE,
origin: 'core',
origin: 'internal',
};
return route;
}
Expand Down
16 changes: 14 additions & 2 deletions packages/astro/src/integrations/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export async function runHookConfigSetup({
);
injectRoute.entrypoint = injectRoute.entryPoint as string;
}
updatedSettings.injectedRoutes.push({ ...injectRoute, origin: 'integration' });
updatedSettings.injectedRoutes.push({ ...injectRoute, origin: 'external' });
},
addWatchFile: (path) => {
updatedSettings.watchFiles.push(path instanceof URL ? fileURLToPath(path) : path);
Expand Down Expand Up @@ -601,6 +601,9 @@ export async function runHookBuildDone({ settings, pages, routes, logging }: Run
pages: pages.map((p) => ({ pathname: p })),
dir,
routes: integrationRoutes,
assets: new Map(
routes.filter((r) => r.distURL !== undefined).map((r) => [r.route, r.distURL!]),
),
logger,
}),
logger: logging,
Expand Down Expand Up @@ -674,11 +677,20 @@ export async function runHookRoutesResolved({

function toIntegrationResolvedRoute(route: RouteData): IntegrationResolvedRoute {
return {
prerendered: route.prerender,
isPrerendered: route.prerender,
entrypoint: route.component,
pattern: route.route,
params: route.params,
origin: route.origin,
generate: route.generate,
patternRegex: route.pattern,
segments: route.segments,
type: route.type,
pathname: route.pathname,
redirect: route.redirect,
redirectRoute: route.redirectRoute
? toIntegrationResolvedRoute(route.redirectRoute)
: undefined,
};
}

Expand Down
41 changes: 25 additions & 16 deletions packages/astro/src/types/public/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,16 +217,17 @@ export interface BaseIntegrationHooks {
'astro:build:done': (options: {
pages: { pathname: string }[];
dir: URL;
/** @deprecated Use `routes` from `astro:routes:resolved` instead */
/** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */
routes: IntegrationRouteData[];
assets: Map<string, URL[]>;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:route:setup': (options: {
route: RouteOptions;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
'astro:routes:resolved': (options: {
routes: Array<IntegrationResolvedRoute>;
routes: IntegrationResolvedRoute[];
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
}
Expand All @@ -242,6 +243,7 @@ export interface AstroIntegration {

/**
* A smaller version of the {@link RouteData} that is used in the integrations.
* @deprecated Use {@link IntegrationResolvedRoute}
*/
export type IntegrationRouteData = Omit<
RouteData,
Expand All @@ -253,33 +255,40 @@ export type IntegrationRouteData = Omit<
redirectRoute?: IntegrationRouteData;
};

export interface IntegrationResolvedRoute {
export interface IntegrationResolvedRoute
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The discussion was marked as resolved because of commits, but we need to figure out the renaming of some fields

extends Omit<
RouteData,
| 'isIndex'
| 'fallbackRoutes'
| 'redirectRoute'
| 'route'
| 'pattern'
| 'component'
| 'prerender'
| 'distURL'
> {
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
/**
* The current **pattern** of the route. For example:
* - `src/pages/index.astro` has a pattern of `/`
* - `src/pages/blog/[...slug].astro` has a pattern of `/blog/[...slug]`
* - `src/pages/site/[blog]/[...slug].astro` has a pattern of `/site/[blog]/[...slug]`
* {@link RouteData.route}
*/
pattern: RouteData['route'];

/**
* Source component URL
* {@link RouteData.pattern}
*/
entrypoint: RouteData['component'];
patternRegex: RouteData['pattern'];

/**
* Whether the route is prerendered or not
* {@link RouteData.component}
*/
prerendered: RouteData['prerender'];
entrypoint: RouteData['component'];

/**
* Dynamic and spread route params
* ex. "/pages/[lang]/[...slug].astro" will output the params ['lang', '...slug']
* {@link RouteData.prerender}
*/
params: RouteData['params'];
isPrerendered: RouteData['prerender'];

/**
* Whether the route comes from Astro core, an integration or the user's project
* {@link RouteData.redirectRoute}
*/
origin: RouteData['origin'];
redirectRoute?: IntegrationResolvedRoute;
}
4 changes: 3 additions & 1 deletion packages/astro/src/types/public/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export interface RouteData {
/**
* Whether the route comes from Astro core, an integration or the user's project
*/
origin: 'core' | 'integration' | 'user';
origin: 'internal' | 'external' | 'project';
}

/**
Expand Down Expand Up @@ -290,6 +290,8 @@ export interface SSRMetadata {

export type SSRError = Error & ViteErrorPayload['err'];

// `origin` is set within the hook, but the user doesn't have access to this property. That's why
// we need an intermediary interface
export interface InternalInjectedRoute {
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
pattern: string;
entrypoint: string | URL;
Expand Down
37 changes: 30 additions & 7 deletions packages/astro/src/vite-plugin-astro-server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import { recordServerError } from './error.js';
import { DevPipeline } from './pipeline.js';
import { handleRequest } from './request.js';
import { setRouteError } from './server-state.js';
import { fileURLToPath } from 'node:url';
import { getRoutePrerenderOption } from '../core/routing/manifest/prerender.js';
import { runHookRoutesResolved } from '../integrations/hooks.js';

export interface AstroPluginOptions {
settings: AstroSettings;
Expand Down Expand Up @@ -51,13 +54,33 @@ export default function createVitePluginAstroServer({
const localStorage = new AsyncLocalStorage();

/** rebuild the route cache + manifest */
async function rebuildManifest() {
async function rebuildManifest(path: string | null = null) {
pipeline.clearRouteCache();
routeManifest = injectDefaultDevRoutes(
settings,
devSSRManifest,
await createRouteManifest({ settings, fsMod }, logger), // TODO: Handle partial updates to the manifest
);

// If a route changes, we check if it's part of the manifest and check for its prerender value
if (path !== null) {
const route = routeManifest.routes.find((r) => path.endsWith(r.component));
if (!route) {
return;
}
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
if (route.type !== 'page' && route.type !== 'endpoint') return;

const routePath = fileURLToPath(new URL(route.component, settings.config.root));
if (!fsMod.existsSync(routePath)) {
// Route was renamed so it does not exist anymore
return;
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
}
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
const content = await fsMod.promises.readFile(routePath, 'utf-8');
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
await getRoutePrerenderOption(content, route, settings, logger);
} else {
routeManifest = injectDefaultDevRoutes(
settings,
devSSRManifest,
await createRouteManifest({ settings, fsMod }, logger, { dev: true }),
);
}
await runHookRoutesResolved({ routes: routeManifest.routes, settings, logger });

warnMissingAdapter(logger, settings);
pipeline.manifest.checkOrigin =
settings.config.security.checkOrigin && settings.buildOutput === 'server';
Expand All @@ -67,7 +90,7 @@ export default function createVitePluginAstroServer({
// Rebuild route manifest on file change
viteServer.watcher.on('add', rebuildManifest.bind(null));
viteServer.watcher.on('unlink', rebuildManifest.bind(null));
viteServer.watcher.on('change', rebuildManifest.bind(null));
viteServer.watcher.on('change', rebuildManifest);

function handleUnhandledRejection(rejection: any) {
const error = new AstroError({
Expand Down
Loading
Loading