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

Prevent getCollection from breaking in vitest (#10846)

* Prevent getCollection from breaking in vitest

* Linting

* Another way

* Make backwards compat

* Oops

* runHookConfigSetup creates a new settings
This commit is contained in:
Matthew Phillips 2024-04-23 07:58:57 -04:00 committed by GitHub
parent 335879218e
commit 3294f7a343
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 51 additions and 17 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Prevent getCollection breaking in vitest

View file

@ -3,12 +3,18 @@ import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url'; import { fileURLToPath, pathToFileURL } from 'node:url';
import { prependForwardSlash, slash } from '../../core/path.js'; import { prependForwardSlash, slash } from '../../core/path.js';
import type { ImageMetadata } from '../types.js'; import type { ImageMetadata } from '../types.js';
import type * as vite from 'vite';
import { imageMetadata } from './metadata.js'; import { imageMetadata } from './metadata.js';
type FileEmitter = vite.Rollup.EmitFile;
export async function emitESMImage( export async function emitESMImage(
id: string | undefined, id: string | undefined,
watchMode: boolean, /** @deprecated */
fileEmitter: any _watchMode: boolean,
// FIX: in Astro 5, this function should not be passed in dev mode at all.
// Or rethink the API so that a function that throws isn't passed through.
fileEmitter?: FileEmitter,
): Promise<ImageMetadata | undefined> { ): Promise<ImageMetadata | undefined> {
if (!id) { if (!id) {
return undefined; return undefined;
@ -37,18 +43,26 @@ export async function emitESMImage(
}); });
// Build // Build
if (!watchMode) { let isBuild = typeof fileEmitter === 'function';
if(isBuild) {
const pathname = decodeURI(url.pathname); const pathname = decodeURI(url.pathname);
const filename = path.basename(pathname, path.extname(pathname) + `.${fileMetadata.format}`); const filename = path.basename(pathname, path.extname(pathname) + `.${fileMetadata.format}`);
const handle = fileEmitter({ try {
name: filename, // fileEmitter throws in dev
source: await fs.readFile(url), const handle = fileEmitter!({
type: 'asset', name: filename,
}); source: await fs.readFile(url),
type: 'asset',
});
emittedImage.src = `__ASTRO_ASSET_IMAGE__${handle}__`; emittedImage.src = `__ASTRO_ASSET_IMAGE__${handle}__`;
} else { } catch {
isBuild = false;
}
}
if(!isBuild) {
// Pass the original file information through query params so we don't have to load the file twice // Pass the original file information through query params so we don't have to load the file twice
url.searchParams.append('origWidth', fileMetadata.width.toString()); url.searchParams.append('origWidth', fileMetadata.width.toString());
url.searchParams.append('origHeight', fileMetadata.height.toString()); url.searchParams.append('origHeight', fileMetadata.height.toString());

View file

@ -95,6 +95,7 @@ export default function assets({
mode, mode,
}: AstroPluginOptions & { mode: string }): vite.Plugin[] { }: AstroPluginOptions & { mode: string }): vite.Plugin[] {
let resolvedConfig: vite.ResolvedConfig; let resolvedConfig: vite.ResolvedConfig;
let shouldEmitFile = false;
globalThis.astroAsset = { globalThis.astroAsset = {
referencedImages: new Set(), referencedImages: new Set(),
@ -194,6 +195,9 @@ export default function assets({
{ {
name: 'astro:assets:esm', name: 'astro:assets:esm',
enforce: 'pre', enforce: 'pre',
config(_, env) {
shouldEmitFile = env.command === 'build';
},
configResolved(viteConfig) { configResolved(viteConfig) {
resolvedConfig = viteConfig; resolvedConfig = viteConfig;
}, },
@ -214,7 +218,8 @@ export default function assets({
return; return;
} }
const imageMetadata = await emitESMImage(id, this.meta.watchMode, this.emitFile); const emitFile = shouldEmitFile ? this.emitFile : undefined;
const imageMetadata = await emitESMImage(id, this.meta.watchMode, emitFile);
if (!imageMetadata) { if (!imageMetadata) {
throw new AstroError({ throw new AstroError({

View file

@ -35,8 +35,8 @@ export function getViteConfig(inlineConfig: UserConfig) {
level: 'info', level: 'info',
}); });
const { astroConfig: config } = await resolveConfig({}, cmd); const { astroConfig: config } = await resolveConfig({}, cmd);
const settings = await createSettings(config, inlineConfig.root); let settings = await createSettings(config, inlineConfig.root);
await runHookConfigSetup({ settings, command: cmd, logger }); settings = await runHookConfigSetup({ settings, command: cmd, logger });
const viteConfig = await createVite( const viteConfig = await createVite(
{ {
mode, mode,

View file

@ -2,14 +2,14 @@ import type { PluginContext } from 'rollup';
import { z } from 'zod'; import { z } from 'zod';
import { emitESMImage } from '../assets/utils/emitAsset.js'; import { emitESMImage } from '../assets/utils/emitAsset.js';
export function createImage(pluginContext: PluginContext, entryFilePath: string) { export function createImage(pluginContext: PluginContext, shouldEmitFile: boolean, entryFilePath: string) {
return () => { return () => {
return z.string().transform(async (imagePath, ctx) => { return z.string().transform(async (imagePath, ctx) => {
const resolvedFilePath = (await pluginContext.resolve(imagePath, entryFilePath))?.id; const resolvedFilePath = (await pluginContext.resolve(imagePath, entryFilePath))?.id;
const metadata = await emitESMImage( const metadata = await emitESMImage(
resolvedFilePath, resolvedFilePath,
pluginContext.meta.watchMode, pluginContext.meta.watchMode,
pluginContext.emitFile shouldEmitFile ? pluginContext.emitFile : undefined,
); );
if (!metadata) { if (!metadata) {

View file

@ -92,6 +92,7 @@ export async function getEntryData(
_internal: EntryInternal; _internal: EntryInternal;
}, },
collectionConfig: CollectionConfig, collectionConfig: CollectionConfig,
shouldEmitFile: boolean,
pluginContext: PluginContext pluginContext: PluginContext
) { ) {
let data; let data;
@ -105,7 +106,7 @@ export async function getEntryData(
let schema = collectionConfig.schema; let schema = collectionConfig.schema;
if (typeof schema === 'function') { if (typeof schema === 'function') {
schema = schema({ schema = schema({
image: createImage(pluginContext, entry._internal.filePath), image: createImage(pluginContext, shouldEmitFile, entry._internal.filePath),
}); });
} }

View file

@ -74,10 +74,14 @@ export function astroContentImportPlugin({
const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes); const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const dataEntryConfigByExt = getEntryConfigByExtMap(settings.dataEntryTypes); const dataEntryConfigByExt = getEntryConfigByExtMap(settings.dataEntryTypes);
const { contentDir } = contentPaths; const { contentDir } = contentPaths;
let shouldEmitFile = false;
const plugins: Plugin[] = [ const plugins: Plugin[] = [
{ {
name: 'astro:content-imports', name: 'astro:content-imports',
config(_config, env) {
shouldEmitFile = env.command === 'build';
},
async transform(_, viteId) { async transform(_, viteId) {
if (hasContentFlag(viteId, DATA_FLAG)) { if (hasContentFlag(viteId, DATA_FLAG)) {
const fileId = viteId.split('?')[0] ?? viteId; const fileId = viteId.split('?')[0] ?? viteId;
@ -90,6 +94,7 @@ export function astroContentImportPlugin({
config: settings.config, config: settings.config,
fs, fs,
pluginContext: this, pluginContext: this,
shouldEmitFile,
}); });
const code = ` const code = `
@ -112,6 +117,7 @@ export const _internal = {
config: settings.config, config: settings.config,
fs, fs,
pluginContext: this, pluginContext: this,
shouldEmitFile,
}); });
const code = ` const code = `
@ -190,6 +196,7 @@ type GetEntryModuleParams<TEntryType extends ContentEntryType | DataEntryType> =
pluginContext: PluginContext; pluginContext: PluginContext;
entryConfigByExt: Map<string, TEntryType>; entryConfigByExt: Map<string, TEntryType>;
config: AstroConfig; config: AstroConfig;
shouldEmitFile: boolean;
}; };
async function getContentEntryModule( async function getContentEntryModule(
@ -222,6 +229,7 @@ async function getContentEntryModule(
? await getEntryData( ? await getEntryData(
{ id, collection, _internal, unvalidatedData }, { id, collection, _internal, unvalidatedData },
collectionConfig, collectionConfig,
params.shouldEmitFile,
pluginContext pluginContext
) )
: unvalidatedData; : unvalidatedData;
@ -256,7 +264,8 @@ async function getDataEntryModule(
? await getEntryData( ? await getEntryData(
{ id, collection, _internal, unvalidatedData }, { id, collection, _internal, unvalidatedData },
collectionConfig, collectionConfig,
pluginContext params.shouldEmitFile,
pluginContext,
) )
: unvalidatedData; : unvalidatedData;