[ci] yarn format

This commit is contained in:
matthewp 2021-11-11 13:45:37 +00:00 committed by GitHub Actions
parent fd52bceea4
commit 8e3fd04dbd
14 changed files with 163 additions and 178 deletions

View file

@ -97,7 +97,7 @@ class AstroBuilder {
route, route,
routeCache: this.routeCache, routeCache: this.routeCache,
viteServer, viteServer,
}) }),
}; };
return; return;
} }
@ -123,7 +123,7 @@ class AstroBuilder {
route, route,
routeCache: this.routeCache, routeCache: this.routeCache,
viteServer, viteServer,
}) }),
}; };
}) })
); );
@ -171,13 +171,13 @@ class AstroBuilder {
allPages, allPages,
pageNames, pageNames,
routeCache: this.routeCache, routeCache: this.routeCache,
viteServer viteServer,
}), }),
rollupPluginAstroBuildCSS({ rollupPluginAstroBuildCSS({
astroPageStyleMap, astroPageStyleMap,
astroStyleMap, astroStyleMap,
chunkToReferenceIdMap, chunkToReferenceIdMap,
pureCSSChunks pureCSSChunks,
}), }),
...(viteConfig.plugins || []), ...(viteConfig.plugins || []),
], ],
@ -202,7 +202,7 @@ class AstroBuilder {
timer.sitemapStart = performance.now(); timer.sitemapStart = performance.now();
if (this.config.buildOptions.sitemap && this.config.buildOptions.site) { if (this.config.buildOptions.sitemap && this.config.buildOptions.site) {
const sitemapStart = performance.now(); const sitemapStart = performance.now();
const sitemap = generateSitemap(pageNames.map(pageName => new URL(`/${pageName}`, this.config.buildOptions.site).href)); const sitemap = generateSitemap(pageNames.map((pageName) => new URL(`/${pageName}`, this.config.buildOptions.site).href));
const sitemapPath = new URL('./sitemap.xml', this.config.dist); const sitemapPath = new URL('./sitemap.xml', this.config.dist);
await fs.promises.mkdir(new URL('./', sitemapPath), { recursive: true }); await fs.promises.mkdir(new URL('./', sitemapPath), { recursive: true });
await fs.promises.writeFile(sitemapPath, sitemap, 'utf8'); await fs.promises.writeFile(sitemapPath, sitemap, 'utf8');

View file

@ -7,4 +7,3 @@ export interface PageBuildData {
route: RouteData; route: RouteData;
} }
export type AllPagesData = Record<string, PageBuildData>; export type AllPagesData = Record<string, PageBuildData>;

View file

@ -191,7 +191,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
}, },
_metadata: { _metadata: {
renderers, renderers,
pathname pathname,
}, },
}; };
@ -217,7 +217,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
attrs: { attrs: {
rel: 'stylesheet', rel: 'stylesheet',
href, href,
'data-astro-injected': true 'data-astro-injected': true,
}, },
injectTo: 'head', injectTo: 'head',
}); });

View file

@ -272,16 +272,20 @@ export async function renderPage(result: SSRResult, Component: AstroComponentFac
const template = await renderToString(result, Component, props, children); const template = await renderToString(result, Component, props, children);
const styles = Array.from(result.styles) const styles = Array.from(result.styles)
.filter(uniqueElements) .filter(uniqueElements)
.map((style) => renderElement('style', { .map((style) =>
renderElement('style', {
...style, ...style,
props: { ...style.props, 'astro-style': true } props: { ...style.props, 'astro-style': true },
})); })
);
const scripts = Array.from(result.scripts) const scripts = Array.from(result.scripts)
.filter(uniqueElements) .filter(uniqueElements)
.map((script, i) => renderElement('script', { .map((script, i) =>
renderElement('script', {
...script, ...script,
props: { ...script.props, 'astro-script': result._metadata.pathname + '/script-' + i } props: { ...script.props, 'astro-script': result._metadata.pathname + '/script-' + i },
})); })
);
return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>'); return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>');
} }

View file

@ -1,4 +1,3 @@
import type { ResolveIdHook, LoadHook, RenderedChunk } from 'rollup'; import type { ResolveIdHook, LoadHook, RenderedChunk } from 'rollup';
import type { Plugin as VitePlugin } from 'vite'; import type { Plugin as VitePlugin } from 'vite';
@ -7,7 +6,6 @@ import { getViteResolve, getViteLoad } from './resolve.js';
import { getViteTransform, TransformHook } from '../vite-plugin-astro/styles.js'; import { getViteTransform, TransformHook } from '../vite-plugin-astro/styles.js';
import * as path from 'path'; import * as path from 'path';
const PLUGIN_NAME = '@astrojs/rollup-plugin-build-css'; const PLUGIN_NAME = '@astrojs/rollup-plugin-build-css';
// This is a virtual module that represents the .astro <style> usage on a page // This is a virtual module that represents the .astro <style> usage on a page
@ -125,7 +123,7 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin {
const referenceId = this.emitFile({ const referenceId = this.emitFile({
name: chunk.name + '.css', name: chunk.name + '.css',
type: 'asset', type: 'asset',
source: chunkCSS source: chunkCSS,
}); });
pureCSSChunks.add(chunk); pureCSSChunks.add(chunk);
chunkToReferenceIdMap.set(chunk.fileName, referenceId); chunkToReferenceIdMap.set(chunk.fileName, referenceId);
@ -141,6 +139,6 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin {
delete bundle[chunkId]; delete bundle[chunkId];
} }
} }
} },
} };
} }

View file

@ -4,7 +4,8 @@ import type { ResolvedConfig, Plugin as VitePlugin } from 'vite';
export function getVitePluginByName(viteConfig: ResolvedConfig, pluginName: string): VitePlugin { export function getVitePluginByName(viteConfig: ResolvedConfig, pluginName: string): VitePlugin {
const plugin = viteConfig.plugins.find(({ name }) => name === pluginName); const plugin = viteConfig.plugins.find(({ name }) => name === pluginName);
if (!plugin) throw new Error(`${pluginName} plugin couldnt be found`); if (!plugin) throw new Error(`${pluginName} plugin couldnt be found`);
return plugin;} return plugin;
}
export function getViteResolvePlugin(viteConfig: ResolvedConfig): VitePlugin { export function getViteResolvePlugin(viteConfig: ResolvedConfig): VitePlugin {
return getVitePluginByName(viteConfig, 'vite:resolve'); return getVitePluginByName(viteConfig, 'vite:resolve');

View file

@ -8,10 +8,7 @@ function fromEntries<V>(entries: [string, V][]) {
return obj; return obj;
} }
export function addRollupInput( export function addRollupInput(inputOptions: InputOptions, newInputs: string[]): InputOptions {
inputOptions: InputOptions,
newInputs: string[]
): InputOptions {
// Add input module ids to existing input option, whether it's a string, array or object // Add input module ids to existing input option, whether it's a string, array or object
// this way you can use multiple html plugins all adding their own inputs // this way you can use multiple html plugins all adding their own inputs
if (!inputOptions.input) { if (!inputOptions.input) {
@ -37,10 +34,7 @@ export function addRollupInput(
...inputOptions, ...inputOptions,
input: { input: {
...inputOptions.input, ...inputOptions.input,
...fromEntries( ...fromEntries(newInputs.map((i) => [i.split('/').slice(-1)[0].split('.')[0], i])),
newInputs
.map(i => [i.split('/').slice(-1)[0].split('.')[0], i]),
),
}, },
}; };
} }

View file

@ -11,9 +11,7 @@ function getSrcSetUrls(srcset: string) {
return []; return [];
} }
const srcsetParts = srcset.includes(',') ? srcset.split(',') : [srcset]; const srcsetParts = srcset.includes(',') ? srcset.split(',') : [srcset];
const urls = srcsetParts const urls = srcsetParts.map((url) => url.trim()).map((url) => (url.includes(' ') ? url.split(' ')[0] : url));
.map(url => url.trim())
.map(url => (url.includes(' ') ? url.split(' ')[0] : url));
return urls; return urls;
} }
@ -101,20 +99,9 @@ export function isHashedAsset(node: Element) {
} }
} }
export function resolveAssetFilePath( export function resolveAssetFilePath(browserPath: string, htmlDir: string, projectRootDir: string, absolutePathPrefix?: string) {
browserPath: string, const _browserPath = absolutePathPrefix && browserPath[0] === '/' ? '/' + npath.posix.relative(absolutePathPrefix, browserPath) : browserPath;
htmlDir: string, return npath.join(_browserPath.startsWith('/') ? projectRootDir : htmlDir, _browserPath.split('/').join(npath.sep));
projectRootDir: string,
absolutePathPrefix?: string,
) {
const _browserPath =
absolutePathPrefix && browserPath[0] === '/'
? '/' + npath.posix.relative(absolutePathPrefix, browserPath)
: browserPath;
return npath.join(
_browserPath.startsWith('/') ? projectRootDir : htmlDir,
_browserPath.split('/').join(npath.sep),
);
} }
export function getSourceAttribute(node: Element) { export function getSourceAttribute(node: Element) {
@ -160,16 +147,16 @@ export function getSourcePaths(node: Element) {
throw new Error(`Missing attribute ${key} in element ${node.nodeName}`); throw new Error(`Missing attribute ${key} in element ${node.nodeName}`);
} }
let paths: {path: string, location: Location}[] = []; let paths: { path: string; location: Location }[] = [];
if (src && key === 'srcset') { if (src && key === 'srcset') {
paths = getSrcSetUrls(src).map(path => ({ paths = getSrcSetUrls(src).map((path) => ({
path, path,
location location,
})); }));
} else if (src) { } else if (src) {
paths.push({ paths.push({
path: src, path: src,
location location,
}); });
} }
@ -183,7 +170,7 @@ export function getTextContent(node: Node): string {
if (adapter.isTextNode(node)) { if (adapter.isTextNode(node)) {
return node.value || ''; return node.value || '';
} }
const subtree = findNodes(node, n => adapter.isTextNode(n)); const subtree = findNodes(node, (n) => adapter.isTextNode(n));
return subtree.map(getTextContent).join(''); return subtree.map(getTextContent).join('');
} }

View file

@ -1,4 +1,3 @@
import type { AstroConfig, RouteCache } from '../@types/astro-core'; import type { AstroConfig, RouteCache } from '../@types/astro-core';
import type { LogOptions } from '../core/logger'; import type { LogOptions } from '../core/logger';
import type { ViteDevServer, Plugin as VitePlugin } from 'vite'; import type { ViteDevServer, Plugin as VitePlugin } from 'vite';
@ -94,7 +93,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
renderedPageMap.set(id, html); renderedPageMap.set(id, html);
const document = parse5.parse(html, { const document = parse5.parse(html, {
sourceCodeLocationInfo: true sourceCodeLocationInfo: true,
}); });
const frontEndImports = []; const frontEndImports = [];
@ -149,13 +148,13 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
if (frontEndImports.length) { if (frontEndImports.length) {
htmlInput.add(id); htmlInput.add(id);
const jsSource = frontEndImports.map(sid => `import '${sid}';`).join('\n'); const jsSource = frontEndImports.map((sid) => `import '${sid}';`).join('\n');
astroPageMap.set(id, jsSource); astroPageMap.set(id, jsSource);
} }
if (assetImports.length) { if (assetImports.length) {
const pageStyleId = getAstroPageStyleId(pathname); const pageStyleId = getAstroPageStyleId(pathname);
const jsSource = assetImports.map(sid => `import '${sid}';`).join('\n'); const jsSource = assetImports.map((sid) => `import '${sid}';`).join('\n');
astroPageStyleMap.set(pageStyleId, jsSource); astroPageStyleMap.set(pageStyleId, jsSource);
assetInput.add(pageStyleId); assetInput.add(pageStyleId);
} }
@ -171,7 +170,6 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
return outOptions; return outOptions;
}, },
async resolveId(id) { async resolveId(id) {
switch (true) { switch (true) {
case astroScriptMap.has(id): case astroScriptMap.has(id):
@ -213,7 +211,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
return `assets/${pageName}.[hash].js`; return `assets/${pageName}.[hash].js`;
} }
return 'assets/[name].[hash].js'; return 'assets/[name].[hash].js';
} },
}); });
return outputOptions; return outputOptions;
}, },
@ -238,7 +236,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
const referenceId = this.emitFile({ const referenceId = this.emitFile({
type: 'asset', type: 'asset',
name: npath.basename(assetPath), name: npath.basename(assetPath),
source: await dataPromise source: await dataPromise,
}); });
assetIdMap.set(assetPath, referenceId); assetIdMap.set(assetPath, referenceId);
} }
@ -272,23 +270,26 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
const key = pathname + relPath + attrs.rel || 'stylesheet'; const key = pathname + relPath + attrs.rel || 'stylesheet';
if (!linkChunksAdded.has(key)) { if (!linkChunksAdded.has(key)) {
linkChunksAdded.add(key); linkChunksAdded.add(key);
insertBefore(lastNode.parentNode, createElement('link', { insertBefore(
lastNode.parentNode,
createElement('link', {
rel: 'stylesheet', rel: 'stylesheet',
...attrs, ...attrs,
href: relPath href: relPath,
}), lastNode); }),
lastNode
);
added = true; added = true;
} }
} }
} }
return added; return added;
} };
for (const [id, html] of renderedPageMap) { for (const [id, html] of renderedPageMap) {
const pathname = id.substr(ASTRO_PAGE_PREFIX.length); const pathname = id.substr(ASTRO_PAGE_PREFIX.length);
const document = parse5.parse(html, { const document = parse5.parse(html, {
sourceCodeLocationInfo: true sourceCodeLocationInfo: true,
}); });
if (facadeIdMap.has(id)) { if (facadeIdMap.has(id)) {
@ -301,10 +302,14 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
if (getAttribute(script, 'astro-script')) { if (getAttribute(script, 'astro-script')) {
if (i === 0) { if (i === 0) {
const relPath = npath.posix.relative(pathname, bundlePath); const relPath = npath.posix.relative(pathname, bundlePath);
insertBefore(script.parentNode, createScript({ insertBefore(
script.parentNode,
createScript({
type: 'module', type: 'module',
src: relPath src: relPath,
}), script); }),
script
);
} }
remove(script); remove(script);
} }
@ -320,7 +325,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
switch (rel) { switch (rel) {
case 'stylesheet': { case 'stylesheet': {
if (!pageCSSAdded) { if (!pageCSSAdded) {
const attrs = Object.fromEntries(node.attrs.map(attr => [attr.name, attr.value])); const attrs = Object.fromEntries(node.attrs.map((attr) => [attr.name, attr.value]));
delete attrs['data-astro-injected']; delete attrs['data-astro-injected'];
pageCSSAdded = appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs); pageCSSAdded = appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs);
} }
@ -329,7 +334,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
} }
case 'preload': { case 'preload': {
if (getAttribute(node, 'as') === 'style') { if (getAttribute(node, 'as') === 'style') {
const attrs = Object.fromEntries(node.attrs.map(attr => [attr.name, attr.value])); const attrs = Object.fromEntries(node.attrs.map((attr) => [attr.name, attr.value]));
appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs); appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs);
remove(node); remove(node);
} }
@ -351,7 +356,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
if (hasSrcSet(node)) { if (hasSrcSet(node)) {
const srcset = getAttribute(node, 'srcset')!; const srcset = getAttribute(node, 'srcset')!;
let changedSrcset = srcset; let changedSrcset = srcset;
const urls = matchSrcset(srcset).map(c => c.url); const urls = matchSrcset(srcset).map((c) => c.url);
for (const url of urls) { for (const url of urls) {
if (assetIdMap.has(url)) { if (assetIdMap.has(url)) {
const referenceId = assetIdMap.get(url)!; const referenceId = assetIdMap.get(url)!;
@ -383,9 +388,9 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
this.emitFile({ this.emitFile({
fileName: outPath, fileName: outPath,
source: outHTML, source: outHTML,
type: 'asset' type: 'asset',
}); });
} }
} },
} };
} }

View file

@ -4,7 +4,7 @@ import { loadFixture } from './test-utils.js';
import srcsetParse from 'srcset-parse'; import srcsetParse from 'srcset-parse';
// This package isn't real ESM, so have to coerce it // This package isn't real ESM, so have to coerce it
const matchSrcset = (srcsetParse).default; const matchSrcset = srcsetParse.default;
// Asset bundling // Asset bundling
describe('Assets', () => { describe('Assets', () => {
@ -28,7 +28,7 @@ describe('Assets', () => {
const $ = cheerio.load(html); const $ = cheerio.load(html);
const srcset = $('img').attr('srcset'); const srcset = $('img').attr('srcset');
const candidates = matchSrcset(srcset); const candidates = matchSrcset(srcset);
const match = candidates.find(a => a.density === 2); const match = candidates.find((a) => a.density === 2);
const data = await fixture.readFile('/' + match.url); const data = await fixture.readFile('/' + match.url);
expect(!!data).to.equal(true); expect(!!data).to.equal(true);
}); });
@ -38,7 +38,7 @@ describe('Assets', () => {
const $ = cheerio.load(html); const $ = cheerio.load(html);
const srcset = $('img').attr('srcset'); const srcset = $('img').attr('srcset');
const candidates = matchSrcset(srcset); const candidates = matchSrcset(srcset);
const match = candidates.find(a => a.density === 3); const match = candidates.find((a) => a.density === 3);
const data = await fixture.readFile('/' + match.url); const data = await fixture.readFile('/' + match.url);
expect(!!data).to.equal(true); expect(!!data).to.equal(true);
}); });

View file

@ -11,9 +11,7 @@ describe('Styles SSR', () => {
}); });
it('Has <link> tags', async () => { it('Has <link> tags', async () => {
const MUST_HAVE_LINK_TAGS = [ const MUST_HAVE_LINK_TAGS = ['assets/index'];
'assets/index'
];
const html = await fixture.readFile('/index.html'); const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html); const $ = cheerio.load(html);
@ -71,8 +69,7 @@ describe('Styles SSR', () => {
let scopedClass; let scopedClass;
// test 1: <style> tag in <head> is transformed // test 1: <style> tag in <head> is transformed
const css = raw const css = raw.replace(/\.astro-[A-Za-z0-9-]+/, (match) => {
.replace(/\.astro-[A-Za-z0-9-]+/, (match) => {
scopedClass = match; // get class hash from result scopedClass = match; // get class hash from result
return match; return match;
}); });