summaryrefslogtreecommitdiff
path: root/src/build.ts
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/build.ts131
1 files changed, 106 insertions, 25 deletions
diff --git a/src/build.ts b/src/build.ts
index 51cdc6e56..a66d49ffa 100644
--- a/src/build.ts
+++ b/src/build.ts
@@ -1,6 +1,6 @@
import type { AstroConfig, RuntimeMode } from './@types/astro';
import type { LogOptions } from './logger';
-import type { LoadResult } from './runtime';
+import type { AstroRuntime, LoadResult } from './runtime';
import { existsSync, promises as fsPromises } from 'fs';
import { relative as pathRelative } from 'path';
@@ -13,6 +13,18 @@ import { collectStatics } from './build/static.js';
const { mkdir, readdir, readFile, stat, writeFile } = fsPromises;
+interface PageBuildOptions {
+ astroRoot: URL;
+ dist: URL;
+ filepath: URL;
+ runtime: AstroRuntime;
+ statics: Set<string>;
+}
+
+interface PageResult {
+ statusCode: number;
+}
+
const logging: LogOptions = {
level: 'debug',
dest: defaultLogDestination,
@@ -55,6 +67,78 @@ async function writeResult(result: LoadResult, outPath: URL, encoding: null | 'u
}
}
+/** Collection utility */
+function getPageType(filepath: URL): 'collection' | 'static' {
+ if (/\$[^.]+.astro$/.test(filepath.pathname)) return 'collection';
+ return 'static';
+}
+
+/** Build collection */
+async function buildCollectionPage({ astroRoot, dist, filepath, runtime, statics }: PageBuildOptions): Promise<PageResult> {
+ const rel = pathRelative(fileURLToPath(astroRoot) + '/pages', fileURLToPath(filepath)); // pages/index.astro
+ const pagePath = `/${rel.replace(/\$([^.]+)\.astro$/, '$1')}`;
+ const builtURLs = new Set<string>(); // !important: internal cache that prevents building the same URLs
+
+ /** Recursively build collection URLs */
+ async function loadCollection(url: string): Promise<LoadResult | undefined> {
+ if (builtURLs.has(url)) return; // this stops us from recursively building the same pages over and over
+ const result = await runtime.load(url);
+ builtURLs.add(url);
+ if (result.statusCode === 200) {
+ const outPath = new URL('./' + url + '/index.html', dist);
+ await writeResult(result, outPath, 'utf-8');
+ mergeSet(statics, collectStatics(result.contents.toString('utf-8')));
+ }
+ return result;
+ }
+
+ const result = (await loadCollection(pagePath)) as LoadResult;
+ if (result.statusCode === 200 && !result.collectionInfo) {
+ throw new Error(`[${rel}]: Collection page must export createCollection() function`);
+ }
+
+ // note: for pages that require params (/tag/:tag), we will get a 404 but will still get back collectionInfo that tell us what the URLs should be
+ if (result.collectionInfo) {
+ await Promise.all(
+ [...result.collectionInfo.additionalURLs].map(async (url) => {
+ // for the top set of additional URLs, we render every new URL generated
+ const addlResult = await loadCollection(url);
+ if (addlResult && addlResult.collectionInfo) {
+ // believe it or not, we may still have a few unbuilt pages left. this is our last crawl:
+ await Promise.all([...addlResult.collectionInfo.additionalURLs].map(async (url2) => loadCollection(url2)));
+ }
+ })
+ );
+ }
+
+ return {
+ statusCode: result.statusCode,
+ };
+}
+
+/** Build static page */
+async function buildStaticPage({ astroRoot, dist, filepath, runtime, statics }: PageBuildOptions): Promise<PageResult> {
+ const rel = pathRelative(fileURLToPath(astroRoot) + '/pages', fileURLToPath(filepath)); // pages/index.astro
+ const pagePath = `/${rel.replace(/\.(astro|md)$/, '')}`;
+
+ let relPath = './' + rel.replace(/\.(astro|md)$/, '.html');
+ if (!relPath.endsWith('index.html')) {
+ relPath = relPath.replace(/\.html$/, '/index.html');
+ }
+
+ const outPath = new URL(relPath, dist);
+ const result = await runtime.load(pagePath);
+
+ await writeResult(result, outPath, 'utf-8');
+ if (result.statusCode === 200) {
+ mergeSet(statics, collectStatics(result.contents.toString('utf-8')));
+ }
+
+ return {
+ statusCode: result.statusCode,
+ };
+}
+
/** The primary build action */
export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
const { projectRoot, astroRoot } = astroConfig;
@@ -77,30 +161,27 @@ export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
const statics = new Set<string>();
const collectImportsOptions = { astroConfig, logging, resolve, mode };
- for (const pathname of await allPages(pageRoot)) {
- const filepath = new URL(`file://${pathname}`);
- const rel = pathRelative(astroRoot.pathname + '/pages', filepath.pathname); // pages/index.astro
- const pagePath = `/${rel.replace(/\.(astro|md)/, '')}`;
-
- try {
- let relPath = './' + rel.replace(/\.(astro|md)$/, '.html');
- if (!relPath.endsWith('index.html')) {
- relPath = relPath.replace(/\.html$/, '/index.html');
- }
-
- const outPath = new URL(relPath, dist);
- const result = await runtime.load(pagePath);
-
- await writeResult(result, outPath, 'utf-8');
- if (result.statusCode === 200) {
- mergeSet(statics, collectStatics(result.contents.toString('utf-8')));
- }
- } catch (err) {
- error(logging, 'generate', err);
- return 1;
- }
-
- mergeSet(imports, await collectDynamicImports(filepath, collectImportsOptions));
+ const pages = await allPages(pageRoot);
+
+ try {
+ await Promise.all(
+ pages.map(async (pathname) => {
+ const filepath = new URL(`file://${pathname}`);
+
+ const pageType = getPageType(filepath);
+ const pageOptions: PageBuildOptions = { astroRoot, dist, filepath, runtime, statics };
+ if (pageType === 'collection') {
+ await buildCollectionPage(pageOptions);
+ } else {
+ await buildStaticPage(pageOptions);
+ }
+
+ mergeSet(imports, await collectDynamicImports(filepath, collectImportsOptions));
+ })
+ );
+ } catch (err) {
+ error(logging, 'generate', err);
+ return 1;
}
for (const pathname of await allPages(componentRoot)) {