0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

[ci] npm run format

This commit is contained in:
matthewp 2021-03-30 13:24:54 +00:00 committed by GitHub Actions
parent a79f7d4077
commit dbd764bdeb
4 changed files with 43 additions and 41 deletions

View file

@ -4,7 +4,7 @@ import type { LoadResult } from './runtime';
import { existsSync, promises as fsPromises } from 'fs'; import { existsSync, promises as fsPromises } from 'fs';
import { relative as pathRelative } from 'path'; import { relative as pathRelative } from 'path';
import {fdir} from 'fdir'; import { fdir } from 'fdir';
import { defaultLogDestination, error } from './logger.js'; import { defaultLogDestination, error } from './logger.js';
import { createRuntime } from './runtime.js'; import { createRuntime } from './runtime.js';
import { bundle, collectDynamicImports } from './build/bundle.js'; import { bundle, collectDynamicImports } from './build/bundle.js';
@ -31,14 +31,16 @@ async function* recurseFiles(root: URL): AsyncGenerator<URL, void, unknown> {
} }
async function allPages(root: URL) { async function allPages(root: URL) {
const api = new fdir().filter(p => /\.(astro|md)$/.test(p)) const api = new fdir()
.withFullPaths().crawl(root.pathname); .filter((p) => /\.(astro|md)$/.test(p))
.withFullPaths()
.crawl(root.pathname);
const files = await api.withPromise(); const files = await api.withPromise();
return files as string[]; return files as string[];
} }
function mergeSet(a: Set<string>, b: Set<string>) { function mergeSet(a: Set<string>, b: Set<string>) {
for(let str of b) { for (let str of b) {
a.add(str); a.add(str);
} }
return a; return a;
@ -51,7 +53,7 @@ async function writeFilep(outPath: URL, bytes: string | Buffer, encoding: 'utf-8
} }
async function writeResult(result: LoadResult, outPath: URL, encoding: null | 'utf-8') { async function writeResult(result: LoadResult, outPath: URL, encoding: null | 'utf-8') {
if(result.statusCode !== 200) { if (result.statusCode !== 200) {
error(logging, 'build', result.error || result.statusCode); error(logging, 'build', result.error || result.statusCode);
//return 1; //return 1;
} else { } else {
@ -73,7 +75,7 @@ export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
const runtime = await createRuntime(astroConfig, { logging: runtimeLogging }); const runtime = await createRuntime(astroConfig, { logging: runtimeLogging });
const { runtimeConfig } = runtime; const { runtimeConfig } = runtime;
const { snowpack } = runtimeConfig; const { snowpack } = runtimeConfig;
const resolve = (pkgName: string) => snowpack.getUrlForPackage(pkgName) const resolve = (pkgName: string) => snowpack.getUrlForPackage(pkgName);
const imports = new Set<string>(); const imports = new Set<string>();
const statics = new Set<string>(); const statics = new Set<string>();
@ -85,7 +87,7 @@ export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
try { try {
let relPath = './' + rel.replace(/\.(astro|md)$/, '.html'); let relPath = './' + rel.replace(/\.(astro|md)$/, '.html');
if(!relPath.endsWith('index.html')) { if (!relPath.endsWith('index.html')) {
relPath = relPath.replace(/\.html$/, '/index.html'); relPath = relPath.replace(/\.html$/, '/index.html');
} }
@ -93,7 +95,7 @@ export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
const result = await runtime.load(pagePath); const result = await runtime.load(pagePath);
await writeResult(result, outPath, 'utf-8'); await writeResult(result, outPath, 'utf-8');
if(result.statusCode === 200) { if (result.statusCode === 200) {
mergeSet(statics, collectStatics(result.contents.toString('utf-8'))); mergeSet(statics, collectStatics(result.contents.toString('utf-8')));
} }
} catch (err) { } catch (err) {
@ -104,20 +106,20 @@ export async function build(astroConfig: AstroConfig): Promise<0 | 1> {
mergeSet(imports, await collectDynamicImports(filepath, astroConfig, resolve)); mergeSet(imports, await collectDynamicImports(filepath, astroConfig, resolve));
} }
await bundle(imports, {dist, runtime, astroConfig}); await bundle(imports, { dist, runtime, astroConfig });
for(let url of statics) { for (let url of statics) {
const outPath = new URL('.' + url, dist); const outPath = new URL('.' + url, dist);
const result = await runtime.load(url); const result = await runtime.load(url);
await writeResult(result, outPath, null); await writeResult(result, outPath, null);
} }
if(existsSync(astroConfig.public)) { if (existsSync(astroConfig.public)) {
const pub = astroConfig.public; const pub = astroConfig.public;
const publicFiles = (await new fdir().withFullPaths().crawl(pub.pathname).withPromise()) as string[]; const publicFiles = (await new fdir().withFullPaths().crawl(pub.pathname).withPromise()) as string[];
for(const filepath of publicFiles) { for (const filepath of publicFiles) {
const fileUrl = new URL(`file://${filepath}`) const fileUrl = new URL(`file://${filepath}`);
const rel = pathRelative(pub.pathname, fileUrl.pathname); const rel = pathRelative(pub.pathname, fileUrl.pathname);
const outUrl = new URL('./' + rel, dist); const outUrl = new URL('./' + rel, dist);

View file

@ -9,7 +9,7 @@ import { parse } from '../parser/index.js';
import { walk } from 'estree-walker'; import { walk } from 'estree-walker';
import babelParser from '@babel/parser'; import babelParser from '@babel/parser';
import path from 'path'; import path from 'path';
import {rollup} from 'rollup'; import { rollup } from 'rollup';
const { transformSync } = esbuild; const { transformSync } = esbuild;
const { readFile } = fsPromises; const { readFile } = fsPromises;
@ -51,29 +51,29 @@ function compileExpressionSafe(raw: string): string {
const defaultExtensions: Readonly<Record<string, ValidExtensionPlugins>> = { const defaultExtensions: Readonly<Record<string, ValidExtensionPlugins>> = {
'.jsx': 'react', '.jsx': 'react',
'.svelte': 'svelte', '.svelte': 'svelte',
'.vue': 'vue' '.vue': 'vue',
}; };
export async function collectDynamicImports(filename: URL, astroConfig: AstroConfig, resolve: (s: string) => Promise<string>) { export async function collectDynamicImports(filename: URL, astroConfig: AstroConfig, resolve: (s: string) => Promise<string>) {
const imports = new Set<string>(); const imports = new Set<string>();
// No markdown for now // No markdown for now
if(filename.pathname.endsWith('md')) { if (filename.pathname.endsWith('md')) {
return imports; return imports;
} }
const extensions = astroConfig.extensions || defaultExtensions; const extensions = astroConfig.extensions || defaultExtensions;
const source = await readFile(filename, 'utf-8'); const source = await readFile(filename, 'utf-8');
const ast = parse(source, { const ast = parse(source, {
filename filename,
}); });
if(!ast.module) { if (!ast.module) {
return imports; return imports;
} }
const componentImports: ImportDeclaration[] = []; const componentImports: ImportDeclaration[] = [];
const components: Record<string, { plugin: ValidExtensionPlugins; type: string; specifier: string; }> = {}; const components: Record<string, { plugin: ValidExtensionPlugins; type: string; specifier: string }> = {};
const plugins = new Set<ValidExtensionPlugins>(); const plugins = new Set<ValidExtensionPlugins>();
const program = babelParser.parse(ast.module.content, { const program = babelParser.parse(ast.module.content, {
@ -107,7 +107,7 @@ export async function collectDynamicImports(filename: URL, astroConfig: AstroCon
function appendImports(rawName: string, filename: URL, astroConfig: AstroConfig) { function appendImports(rawName: string, filename: URL, astroConfig: AstroConfig) {
const [componentName, componentType] = rawName.split(':'); const [componentName, componentType] = rawName.split(':');
if(!componentType) { if (!componentType) {
return; return;
} }
@ -118,8 +118,8 @@ export async function collectDynamicImports(filename: URL, astroConfig: AstroCon
const defn = components[componentName]; const defn = components[componentName];
const fileUrl = new URL(defn.specifier, filename); const fileUrl = new URL(defn.specifier, filename);
let rel = path.posix.relative(astroConfig.astroRoot.pathname, fileUrl.pathname); let rel = path.posix.relative(astroConfig.astroRoot.pathname, fileUrl.pathname);
switch(defn.plugin) { switch (defn.plugin) {
case 'preact': { case 'preact': {
imports.add(dynamic.get('preact')!); imports.add(dynamic.get('preact')!);
rel = rel.replace(/\.[^.]+$/, '.js'); rel = rel.replace(/\.[^.]+$/, '.js');
@ -166,7 +166,7 @@ export async function collectDynamicImports(filename: URL, astroConfig: AstroCon
break; break;
} }
case 'InlineComponent': { case 'InlineComponent': {
if(/^[A-Z]/.test(node.name)) { if (/^[A-Z]/.test(node.name)) {
appendImports(node.name, filename, astroConfig); appendImports(node.name, filename, astroConfig);
return; return;
} }
@ -174,7 +174,7 @@ export async function collectDynamicImports(filename: URL, astroConfig: AstroCon
break; break;
} }
} }
} },
}); });
return imports; return imports;
@ -189,7 +189,7 @@ interface BundleOptions {
export async function bundle(imports: Set<string>, { runtime, dist }: BundleOptions) { export async function bundle(imports: Set<string>, { runtime, dist }: BundleOptions) {
const ROOT = 'astro:root'; const ROOT = 'astro:root';
const root = ` const root = `
${[...imports].map(url => `import '${url}';`).join('\n')} ${[...imports].map((url) => `import '${url}';`).join('\n')}
`; `;
const inputOptions: InputOptions = { const inputOptions: InputOptions = {
@ -198,14 +198,14 @@ export async function bundle(imports: Set<string>, { runtime, dist }: BundleOpti
{ {
name: 'astro:build', name: 'astro:build',
resolveId(source: string, imported?: string) { resolveId(source: string, imported?: string) {
if(source === ROOT) { if (source === ROOT) {
return source; return source;
} }
if(source.startsWith('/')) { if (source.startsWith('/')) {
return source; return source;
} }
if(imported) { if (imported) {
const outUrl = new URL(source, 'http://example.com' + imported); const outUrl = new URL(source, 'http://example.com' + imported);
return outUrl.pathname; return outUrl.pathname;
} }
@ -213,21 +213,21 @@ export async function bundle(imports: Set<string>, { runtime, dist }: BundleOpti
return null; return null;
}, },
async load(id: string) { async load(id: string) {
if(id === ROOT) { if (id === ROOT) {
return root; return root;
} }
const result = await runtime.load(id); const result = await runtime.load(id);
if(result.statusCode !== 200) { if (result.statusCode !== 200) {
return null; return null;
} }
return result.contents.toString('utf-8'); return result.contents.toString('utf-8');
} },
} },
] ],
} };
const build = await rollup(inputOptions); const build = await rollup(inputOptions);
@ -237,8 +237,8 @@ export async function bundle(imports: Set<string>, { runtime, dist }: BundleOpti
exports: 'named', exports: 'named',
entryFileNames(chunk) { entryFileNames(chunk) {
return chunk.facadeModuleId!.substr(1); return chunk.facadeModuleId!.substr(1);
} },
}; };
await build.write(outputOptions); await build.write(outputOptions);
} }

View file

@ -1,4 +1,4 @@
import type {Element} from 'domhandler'; import type { Element } from 'domhandler';
import cheerio from 'cheerio'; import cheerio from 'cheerio';
export function collectStatics(html: string) { export function collectStatics(html: string) {
@ -8,11 +8,11 @@ export function collectStatics(html: string) {
const append = (el: Element, attr: string) => { const append = (el: Element, attr: string) => {
const value: string = $(el).attr(attr)!; const value: string = $(el).attr(attr)!;
if(value.startsWith('http')) { if (value.startsWith('http')) {
return; return;
} }
statics.add(value); statics.add(value);
} };
$('link[href]').each((i, el) => { $('link[href]').each((i, el) => {
append(el, 'href'); append(el, 'href');
@ -23,4 +23,4 @@ export function collectStatics(html: string) {
}); });
return statics; return statics;
} }

View file

@ -127,7 +127,7 @@ export async function createRuntime(astroConfig: AstroConfig, { logging }: Runti
extensions?: Record<string, string>; extensions?: Record<string, string>;
} = { } = {
extensions, extensions,
resolve: async (pkgName: string) => snowpack.getUrlForPackage(pkgName) resolve: async (pkgName: string) => snowpack.getUrlForPackage(pkgName),
}; };
const snowpackConfig = await loadConfiguration({ const snowpackConfig = await loadConfiguration({