Skip to content

Commit

Permalink
refactor: astro route data
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed Aug 28, 2024
1 parent c7a2ded commit 204827b
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/ten-walls-tap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': major
---

ff
6 changes: 5 additions & 1 deletion packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,11 @@ async function generatePath(

const outFolder = getOutFolder(config, pathname, route);
const outFile = getOutFile(config, outFolder, pathname, route);
route.distURL = outFile;
if (route.distURL) {
route.distURL.push(outFile);
} else {
route.distURL = [outFile];
}

await fs.promises.mkdir(outFolder, { recursive: true });
await fs.promises.writeFile(outFile, body);
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/core/routing/manifest/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ function createFileBasedRoutes(
pathname: pathname || undefined,
prerender,
fallbackRoutes: [],
distURL: []
});
}
}
Expand Down Expand Up @@ -322,6 +323,7 @@ function createInjectedRoutes({ settings, cwd }: CreateRouteManifestParams): Rou
pathname: pathname || void 0,
prerender: prerenderInjected ?? prerender,
fallbackRoutes: [],
distURL: []
});
}

Expand Down Expand Up @@ -390,6 +392,7 @@ function createRedirectRoutes(
redirect: to,
redirectRoute: routeMap.get(destination),
fallbackRoutes: [],
distURL: []
});
}

Expand Down
31 changes: 27 additions & 4 deletions packages/astro/src/integrations/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type { ContentEntryType, DataEntryType } from '../types/public/content.js
import type {
AstroIntegration,
AstroRenderer,
HookParameters,
HookParameters, IntegrationRouteData,
RouteOptions,
} from '../types/public/integrations.js';
import type { RouteData } from '../types/public/internal.js';
Expand Down Expand Up @@ -501,14 +501,19 @@ export async function runHookBuildSsr({
entryPoints,
middlewareEntryPoint,
}: RunHookBuildSsr) {

const entryPointsMap = new Map();
for (const [key, value] of entryPoints) {
entryPointsMap.set(toIntegrationRouteData(key), value);
}
for (const integration of config.integrations) {
if (integration?.hooks?.['astro:build:ssr']) {
await withTakingALongTimeMsg({
name: integration.name,
hookName: 'astro:build:ssr',
hookResult: integration.hooks['astro:build:ssr']({
manifest,
entryPoints,
entryPoints: entryPointsMap,
middlewareEntryPoint,
logger: getLogger(integration, logger),
}),
Expand Down Expand Up @@ -559,7 +564,7 @@ export async function runHookBuildDone({
}: RunHookBuildDone) {
const dir = isServerLikeOutput(config) ? config.build.client : config.outDir;
await fsMod.promises.mkdir(dir, { recursive: true });

const integrationRoutes = routes.map(toIntegrationRouteData);
for (const integration of config.integrations) {
if (integration?.hooks?.['astro:build:done']) {
const logger = getLogger(integration, logging);
Expand All @@ -570,7 +575,7 @@ export async function runHookBuildDone({
hookResult: integration.hooks['astro:build:done']({
pages: pages.map((p) => ({ pathname: p })),
dir,
routes,
routes: integrationRoutes,
logger,
cacheManifest,
}),
Expand Down Expand Up @@ -620,3 +625,21 @@ export async function runHookRouteSetup({
);
}
}


function toIntegrationRouteData(route:RouteData): IntegrationRouteData {
return {
route: route.route,
component: route.component,
generate: route.generate,
params: route.params,
pathname: route.pathname,
segments: route.segments,
prerender: route.prerender,
redirect: route.redirect,
redirectRoute: route.redirectRoute,
type: route.type,
pattern: route.pattern,
distURL: route.distURL
};
}
11 changes: 8 additions & 3 deletions packages/astro/src/types/public/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import type { AstroIntegrationLogger } from '../../core/logger/core.js';
import type { getToolbarServerCommunicationHelpers } from '../../integrations/hooks.js';
import type { DeepPartial } from '../../type-utils.js';
import type { AstroConfig } from './config.js';
import type { RouteData } from './internal.js';
import type { DevToolbarAppEntry } from './toolbar.js';
import type {RouteData} from "./internal.js";

export interface RouteOptions {
/**
Expand Down Expand Up @@ -199,7 +199,7 @@ export interface BaseIntegrationHooks {
* This maps a {@link RouteData} to an {@link URL}, this URL represents
* the physical file you should import.
*/
entryPoints: Map<RouteData, URL>;
entryPoints: Map<IntegrationRouteData, URL>;
/**
* File path of the emitted middleware
*/
Expand All @@ -221,7 +221,7 @@ export interface BaseIntegrationHooks {
'astro:build:done': (options: {
pages: { pathname: string }[];
dir: URL;
routes: RouteData[];
routes: IntegrationRouteData[];
logger: AstroIntegrationLogger;
cacheManifest: boolean;
}) => void | Promise<void>;
Expand All @@ -239,3 +239,8 @@ export interface AstroIntegration {
[K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K];
} & Partial<Record<string, unknown>>;
}

/**
* A smaller version of the {@link RouteData} that is used in the integrations.
*/
export type IntegrationRouteData = Omit<RouteData, 'isIndex' | 'fallbackRoutes'>;
67 changes: 65 additions & 2 deletions packages/astro/src/types/public/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,24 +36,87 @@ export interface SSRLoadedRendererValue {
renderHydrationScript?: () => string;
}

/**
* It contains the information about a route
*/
export interface RouteData {
/**
* The current **pattern** of the route,
*/
route: string;
/**
* The file system path of the component that crated this route
*/
component: string;
/**
* TBD
* @param data
*/
generate: (data?: any) => string;
/**
* The parameters of the route. For example, for `[date]/[slug].astro`, the params are `['date', 'slug']`
*/
params: string[];
/**
* The path name of the route.
*/
pathname?: string;
// expose the real path name on SSG
distURL?: URL;
/**
* The paths of the physical files emitted by this route.
*/
distURL?: URL[];
/**
* A regular expression that represents this route. Use this expression to match a string to this route:
*
* ## Example
*
* ```js
* if (route.pattern.test('/blog')) {
* // do something
* }
* ```
*/
pattern: RegExp;
/**
* A broken down version of the route. For example, for `/site/[blog]/[...slug].astro`, the segments are:
*
* 1. `{ content: 'site', dynamic: false, spread: false }`
* 2. `{ content: 'blog', dynamic: true, spread: false }`
* 3. `{ content: '...slug', dynamic: true, spread: true }`
*/
segments: RoutePart[][];
/**
* The type of the route. It can be:
* - `page`: a route that lives in the file system, usually an Astro component
* - `endpoint`: a route that lives in the file system, usually a JS file that exposes endpoints methods
* - `redirect`: a route points to another route that lives in the file system
* - `fallback`: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware
*/
type: RouteType;
/**
* Whether the route is prerendered or not
*/
prerender: boolean;
/**
* The route to redirect to. It holds information regarding the status code and its destination.
*/
redirect?: RedirectConfig;
/**
* The {@link RouteData} to redirect to. It's present when `RouteData.type` is `redirect`.
*/
redirectRoute?: RouteData;
/**
* A list of {@link RouteData} to fallback to. They are present when `i18n.fallback` has a list of locales.
*/
fallbackRoutes: RouteData[];

/**
* If this route is the index
*/
isIndex: boolean;
}


/**
* - page: a route that lives in the file system, usually an Astro component
* - endpoint: a route that lives in the file system, usually a JS file that exposes endpoints methods
Expand Down

0 comments on commit 204827b

Please sign in to comment.