Skip to content

Commit

Permalink
Chore: remove numbered comments
Browse files Browse the repository at this point in the history
  • Loading branch information
drwpow committed Oct 20, 2021
1 parent 6a981ec commit 2359f5d
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 35 deletions.
37 changes: 26 additions & 11 deletions packages/astro/src/core/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ class AstroBuilder {
async build() {
const timer: Record<string, number> = {}; // keep track of performance timers

// 1. initialize fresh Vite instance
/*
* Setup
* Create the Vite server with production build settings
*/
timer.viteStart = performance.now();
const { logging, origin } = this;
const viteConfig = await createVite(
Expand All @@ -73,12 +76,15 @@ class AstroBuilder {
this.viteServer = viteServer;
debug(logging, 'build', timerMessage('Vite started', timer.viteStart));

// 2. get all routes
/*
* Render pages
* Convert .astro -> .html
*/
timer.renderStart = performance.now();
const assets: Record<string, string> = {}; // additional assets to be written
const allPages: Record<string, RouteData & { paths: string[] }> = {};

// 2a. determine all possible routes first before rendering
// pre-render: determine all possible routes from dynamic pages
await Promise.all(
this.manifest.routes.map(async (route) => {
// static route
Expand All @@ -100,7 +106,7 @@ class AstroBuilder {
})
);

// 2b. after all paths have been determined, render all pages
// render: convert Astro to HTML
const input: InputHTMLOptions[] = [];
await Promise.all(
Object.entries(allPages).map(([component, route]) =>
Expand All @@ -126,7 +132,10 @@ class AstroBuilder {
);
debug(logging, 'build', timerMessage('All pages rendered', timer.renderStart));

// 3. build with Vite
/*
* Production Build
* Use Vite’s build process to generate files
*/
timer.buildStart = performance.now();
await vite.build({
logLevel: 'error',
Expand All @@ -151,7 +160,13 @@ class AstroBuilder {
});
debug(logging, 'build', timerMessage('Vite build finished', timer.buildStart));

// 4. write assets to disk
/*
* Post-build files
* Write other files to disk Vite may not know about.
* TODO: is there a way to handle these as part of the previous step?
*/

// RSS
timer.assetsStart = performance.now();
Object.keys(assets).map((k) => {
if (!assets[k]) return;
Expand All @@ -162,21 +177,21 @@ class AstroBuilder {
});
debug(logging, 'build', timerMessage('Additional assets copied', timer.assetsStart));

// 5. build sitemap
// Sitemap
timer.sitemapStart = performance.now();
if (this.config.buildOptions.sitemap && this.config.buildOptions.site) {
const sitemapStart = performance.now();
const sitemap = generateSitemap(input.map(({ name }) => new URL(`/${name}`, this.config.buildOptions.site).href));
const sitemapPath = new URL('./sitemap.xml', this.config.dist);
await fs.promises.mkdir(new URL('./', sitemapPath), { recursive: true });
await fs.promises.writeFile(sitemapPath, sitemap, 'utf8');
}
debug(logging, 'build', timerMessage('Sitemap built', timer.sitemapStart));

// 6. clean up
/*
* Clean up
* Close the Vite server instance, and print stats
*/
await viteServer.close();

// 7. log output
if (logging.level && levels[logging.level] <= levels['info']) {
await this.printStats({ cwd: this.config.dist, pageCount: input.length });
}
Expand Down
8 changes: 4 additions & 4 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,21 @@ export async function createVite(
await Promise.all(
astroConfig.renderers.map(async (name) => {
const { default: renderer } = await import(name);
// 1. prepare client-side hydration code for browser
// prepare client-side hydration code for browser
if (renderer.client) {
optimizedDeps.add(name + renderer.client.substr(1));
}
// 2. knownEntrypoints and polyfills need to be added to the client
// knownEntrypoints and polyfills need to be added to the client
for (let dep of [...(renderer.knownEntrypoints || []), ...(renderer.polyfills || [])]) {
if (dep[0] === '.') dep = name + dep.substr(1); // if local polyfill, use full path
optimizedDeps.add(dep);
dedupe.add(dep); // we can try and dedupe renderers by default
}
// 3. let renderer inject Vite plugins
// let renderer inject Vite plugins
if (renderer.vitePlugins) {
plugins.push(...renderer.vitePlugins);
}
// 4. mark external packages as external to Vite
// mark external packages as external to Vite
if (renderer.external) {
for (const dep of renderer.external) {
external.add(dep);
Expand Down
16 changes: 10 additions & 6 deletions packages/astro/src/core/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,22 @@ export class AstroDevServer {

/** Start dev server */
async start() {
// 1. profile startup time
const devStart = performance.now();

// 2. create Vite instance
/*
* Setup
* Create the Vite serer in dev mode
*/
const devStart = performance.now(); // profile startup time
this.viteServer = await this.createViteServer();

// 3. add middlewares
// middlewares
this.app.use((req, res, next) => this.handleRequest(req, res, next));
this.app.use(this.viteServer.middlewares);
this.app.use((req, res, next) => this.renderError(req, res, next));

// 4. listen on port (and retry if taken)
/*
* Listen
* Start external connect server and listen on configured port
*/
await new Promise<void>((resolve, reject) => {
const onError = (err: NodeJS.ErrnoException) => {
if (err.code && err.code === 'EADDRINUSE') {
Expand Down
23 changes: 17 additions & 6 deletions packages/astro/src/core/ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,20 @@ async function resolveRenderers(viteServer: ViteDevServer, ids: string[]): Promi
/** use Vite to SSR */
export async function ssr({ astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer }: SSROptions): Promise<string> {
try {
// 1. resolve renderers
/*
* Renderers
* Load all renderers to be used for SSR
*/
// Important this happens before load module in case a renderer provides polyfills.
const renderers = await resolveRenderers(viteServer, astroConfig.renderers);

// 2. load module
/*
* Pre-render
* Load module through Vite and do pre-render work like dynamic routing
*/
const mod = (await viteServer.ssrLoadModule(fileURLToPath(filePath))) as ComponentInstance;

// 3. handle dynamic routes
// handle dynamic routes
let params: Params = {};
let pageProps: Props = {};
if (route && !route.pathname) {
Expand Down Expand Up @@ -110,7 +116,10 @@ export async function ssr({ astroConfig, filePath, logging, mode, origin, pathna
pageProps = { ...matchedStaticPath.props } || {};
}

// 4. render page
/*
* Render
* Convert .astro to .html
*/
const Component = await mod.default;
if (!Component) throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);

Expand Down Expand Up @@ -144,12 +153,14 @@ export async function ssr({ astroConfig, filePath, logging, mode, origin, pathna

let html = await renderPage(result, Component, pageProps, null);

// 5. modify response
/*
* Dev Server
* Apply Vite HMR, Astro HMR, and other dev-only transformations needed from Vite plugins.
*/
if (mode === 'development') {
html = await viteServer.transformIndexHtml(fileURLToPath(filePath), html, pathname);
}

// 6. finish
return html;
} catch (e: any) {
viteServer.ssrFixStacktrace(e);
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/core/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,20 @@ export function codeFrame(src: string, loc: ErrorPayload['err']['loc']): string

const lines = src.replace(/\r\n/g, '\n').split('\n');

// 1. grab 2 lines before, and 3 lines after focused line
// grab 2 lines before, and 3 lines after focused line
const visibleLines = [];
for (let n = -2; n <= 2; n++) {
if (lines[loc.line + n]) visibleLines.push(loc.line + n);
}

// 2. figure out gutter width
// figure out gutter width
let gutterWidth = 0;
for (const lineNo of visibleLines) {
let w = `> ${lineNo}`;
if (w.length > gutterWidth) gutterWidth = w.length;
}

// 3. print lines
// print lines
let output = '';
for (const lineNo of visibleLines) {
const isFocusedLine = lineNo === loc.line - 1;
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ export default function astro({ config, devServer }: AstroPluginOptions): Plugin
let tsResult: TransformResult | undefined;

try {
// 1. Transform from `.astro` to valid `.ts`
// `.astro` -> `.ts`
// use `sourcemap: "inline"` so that the sourcemap is included in the "code" result that we pass to esbuild.
tsResult = await transform(source, {
site: config.buildOptions.site,
sourcefile: id,
sourcemap: 'both',
internalURL: 'astro/internal',
});
// 2. Compile `.ts` to `.js`
// `.ts` -> `.js`
const { code, map } = await esbuild.transform(tsResult.code, { loader: 'ts', sourcemap: 'external', sourcefile: id });

return {
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/vite-plugin-markdown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default function markdown({ config }: AstroPluginOptions): Plugin {
if (id.endsWith('.md')) {
let source = await fs.promises.readFile(id, 'utf8');

// 2. Transform from `.md` to valid `.astro`
// `.md` -> `.astro`
let render = config.markdownOptions.render;
let renderOpts = {};
if (Array.isArray(render)) {
Expand All @@ -46,14 +46,14 @@ ${setup}
astroResult = `${prelude}\n${astroResult}`;
}

// 2. Transform from `.astro` to valid `.ts`
// `.astro` -> `.ts`
let { code: tsResult } = await transform(astroResult, { sourcefile: id, sourcemap: 'inline', internalURL: 'astro/internal' });

tsResult = `\nexport const metadata = ${JSON.stringify(metadata)};
export const frontmatter = ${JSON.stringify(content)};
${tsResult}`;

// 3. Compile `.ts` to `.js`
// `.ts` -> `.js`
const { code, map } = await esbuild.transform(tsResult, { loader: 'ts', sourcemap: 'inline', sourcefile: id });

return {
Expand Down

0 comments on commit 2359f5d

Please sign in to comment.