Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brave-pandas-make.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Refactors some internals to improve Rolldown compatibility
2 changes: 1 addition & 1 deletion packages/astro/src/actions/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export function vitePluginActions({
shouldAppendForwardSlash(settings.config.trailingSlash, settings.config.build.format),
),
);
return code;
return { code };
},
};
}
74 changes: 40 additions & 34 deletions packages/astro/src/assets/vite-plugin-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,32 +117,34 @@ export default function assets({ settings }: { settings: AstroSettings }): vite.
},
load(id) {
if (id === resolvedVirtualModuleId) {
return /* ts */ `
export { getConfiguredImageService, isLocalService } from "astro/assets";
import { getImage as getImageInternal } from "astro/assets";
export { default as Image } from "astro/components/${imageComponentPrefix}Image.astro";
export { default as Picture } from "astro/components/${imageComponentPrefix}Picture.astro";
export { inferRemoteSize } from "astro/assets/utils/inferRemoteSize.js";

export const imageConfig = ${JSON.stringify({ ...settings.config.image, experimentalResponsiveImages: settings.config.experimental.responsiveImages })};
// This is used by the @astrojs/node integration to locate images.
// It's unused on other platforms, but on some platforms like Netlify (and presumably also Vercel)
// new URL("dist/...") is interpreted by the bundler as a signal to include that directory
// in the Lambda bundle, which would bloat the bundle with images.
// To prevent this, we mark the URL construction as pure,
// so that it's tree-shaken away for all platforms that don't need it.
export const outDir = /* #__PURE__ */ new URL(${JSON.stringify(
new URL(
settings.buildOutput === 'server'
? settings.config.build.client
: settings.config.outDir,
),
)});
export const assetsDir = /* #__PURE__ */ new URL(${JSON.stringify(
settings.config.build.assets,
)}, outDir);
export const getImage = async (options) => await getImageInternal(options, imageConfig);
`;
return {
code: `
export { getConfiguredImageService, isLocalService } from "astro/assets";
import { getImage as getImageInternal } from "astro/assets";
export { default as Image } from "astro/components/${imageComponentPrefix}Image.astro";
export { default as Picture } from "astro/components/${imageComponentPrefix}Picture.astro";
export { inferRemoteSize } from "astro/assets/utils/inferRemoteSize.js";

export const imageConfig = ${JSON.stringify({ ...settings.config.image, experimentalResponsiveImages: settings.config.experimental.responsiveImages })};
// This is used by the @astrojs/node integration to locate images.
// It's unused on other platforms, but on some platforms like Netlify (and presumably also Vercel)
// new URL("dist/...") is interpreted by the bundler as a signal to include that directory
// in the Lambda bundle, which would bloat the bundle with images.
// To prevent this, we mark the URL construction as pure,
// so that it's tree-shaken away for all platforms that don't need it.
export const outDir = /* #__PURE__ */ new URL(${JSON.stringify(
new URL(
settings.buildOutput === 'server'
? settings.config.build.client
: settings.config.outDir,
),
)});
export const assetsDir = /* #__PURE__ */ new URL(${JSON.stringify(
settings.config.build.assets,
)}, outDir);
export const getImage = async (options) => await getImageInternal(options, imageConfig);
`,
};
}
},
buildStart() {
Expand All @@ -151,7 +153,7 @@ export default function assets({ settings }: { settings: AstroSettings }): vite.
},
// In build, rewrite paths to ESM imported images in code to their final location
async renderChunk(code) {
const assetUrlRE = /__ASTRO_ASSET_IMAGE__([\w$]{8})__(?:_(.*?)__)?/g;
const assetUrlRE = /__ASTRO_ASSET_IMAGE__([\w$]+)__(?:_(.*?)__)?/g;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In rolldown hashes are not exactly 8 long


let match;
let s;
Expand Down Expand Up @@ -205,7 +207,7 @@ export default function assets({ settings }: { settings: AstroSettings }): vite.
return;
}

const emitFile = shouldEmitFile ? this.emitFile : undefined;
const emitFile = shouldEmitFile ? this.emitFile.bind(this) : undefined;
const imageMetadata = await emitESMImage(
id,
this.meta.watchMode,
Expand All @@ -223,20 +225,24 @@ export default function assets({ settings }: { settings: AstroSettings }): vite.
if (settings.config.experimental.svg && /\.svg$/.test(id)) {
const { contents, ...metadata } = imageMetadata;
// We know that the contents are present, as we only emit this property for SVG files
return makeSvgComponent(metadata, contents!);
return { code: makeSvgComponent(metadata, contents!) };
}

// We can only reliably determine if an image is used on the server, as we need to track its usage throughout the entire build.
// Since you cannot use image optimization on the client anyway, it's safe to assume that if the user imported
// an image on the client, it should be present in the final build.
if (options?.ssr) {
return `export default ${getProxyCode(
imageMetadata,
settings.buildOutput === 'server',
)}`;
return {
code: `export default ${getProxyCode(
imageMetadata,
settings.buildOutput === 'server',
)}`,
};
} else {
globalThis.astroAsset.referencedImages.add(imageMetadata.fsPath);
return `export default ${JSON.stringify(imageMetadata)}`;
return {
code: `export default ${JSON.stringify(imageMetadata)}`,
};
}
}
},
Expand Down
20 changes: 11 additions & 9 deletions packages/astro/src/content/vite-plugin-content-virtual-mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export function astroContentVirtualModPlugin({
}
if (id === RESOLVED_DATA_STORE_VIRTUAL_ID) {
if (!fs.existsSync(dataStoreFile)) {
return 'export default new Map()';
return { code: 'export default new Map()' };
}
const jsonData = await fs.promises.readFile(dataStoreFile, 'utf-8');

Expand All @@ -161,18 +161,20 @@ export function astroContentVirtualModPlugin({

if (id === ASSET_IMPORTS_RESOLVED_STUB_ID) {
const assetImportsFile = new URL(ASSET_IMPORTS_FILE, settings.dotAstroDir);
if (!fs.existsSync(assetImportsFile)) {
return 'export default new Map()';
}
return fs.readFileSync(assetImportsFile, 'utf-8');
return {
code: fs.existsSync(assetImportsFile)
? fs.readFileSync(assetImportsFile, 'utf-8')
: 'export default new Map()',
};
}

if (id === MODULES_MJS_VIRTUAL_ID) {
const modules = new URL(MODULES_IMPORTS_FILE, settings.dotAstroDir);
if (!fs.existsSync(modules)) {
return 'export default new Map()';
}
return fs.readFileSync(modules, 'utf-8');
return {
code: fs.existsSync(modules)
? fs.readFileSync(modules, 'utf-8')
: 'export default new Map()',
};
}
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ export function vitePluginComponentEntry(internals: BuildInternals): VitePlugin
const componentId = id.slice(astroEntryPrefix.length);
const exportNames = componentToExportNames.get(componentId);
if (exportNames) {
return `export { ${exportNames.join(', ')} } from ${JSON.stringify(componentId)}`;
return {
code: `export { ${exportNames.join(', ')} } from ${JSON.stringify(componentId)}`,
};
}
}
},
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/plugins/plugin-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function vitePluginManifest(options: StaticBuildOptions, internals: BuildInterna
];
const exports = [`export { manifest }`];

return [...imports, ...contents, ...exports].join('\n');
return { code: [...imports, ...contents, ...exports].join('\n') };
}
},

Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/plugins/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
exports.push(`export { renderers };`);

return `${imports.join('\n')}${exports.join('\n')}`;
return { code: `${imports.join('\n')}${exports.join('\n')}` };
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/core/build/plugins/plugin-prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ function getNonPrerenderOnlyChunks(bundle: Rollup.OutputBundle, internals: Build

nonPrerenderOnlyEntryChunks.add(chunk);
}
if (chunk.type === 'chunk' && chunk.isDynamicEntry) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be a bug in Astro according to the patch file

nonPrerenderOnlyEntryChunks.add(chunk);
}
}

// From the `nonPrerenderedEntryChunks`, we crawl all the imports/dynamicImports to find all
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/build/plugins/plugin-renderers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export function vitePluginRenderers(opts: StaticBuildOptions): VitePlugin {

exports.push(`export const renderers = [${rendererItems}];`);

return `${imports.join('\n')}\n${exports.join('\n')}`;
return { code: `${imports.join('\n')}\n${exports.join('\n')}` };
} else {
return `export const renderers = [];`;
return { code: `export const renderers = [];` };
}
}
},
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/build/plugins/plugin-ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function vitePluginAdapter(adapter: AstroAdapter): VitePlugin {
},
async load(id) {
if (id === RESOLVED_ADAPTER_VIRTUAL_MODULE_ID) {
return `export * from ${JSON.stringify(adapter.serverEntrypoint)};`;
return { code: `export * from ${JSON.stringify(adapter.serverEntrypoint)};` };
}
},
};
Expand Down Expand Up @@ -103,7 +103,7 @@ function vitePluginSSR(
const ssrCode = generateSSRCode(adapter, middleware!.id);
imports.push(...ssrCode.imports);
contents.push(...ssrCode.contents);
return [...imports, ...contents, ...exports].join('\n');
return { code: [...imports, ...contents, ...exports].join('\n') };
}
},
async generateBundle(_opts, bundle) {
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/core/middleware/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }):
if (!userMiddlewareIsPresent && settings.config.i18n?.routing === 'manual') {
throw new AstroError(MissingMiddlewareForInternationalization);
}
return 'export const onRequest = (_, next) => next()';
return { code: 'export const onRequest = (_, next) => next()' };
} else if (id === MIDDLEWARE_MODULE_ID) {
if (!userMiddlewareIsPresent && settings.config.i18n?.routing === 'manual') {
throw new AstroError(MissingMiddlewareForInternationalization);
Expand All @@ -53,7 +53,7 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }):
const preMiddleware = createMiddlewareImports(settings.middlewares.pre, 'pre');
const postMiddleware = createMiddlewareImports(settings.middlewares.post, 'post');

const source = `
const code = `
${
userMiddlewareIsPresent
? `import { onRequest as userOnRequest } from '${resolvedMiddlewareId}';`
Expand All @@ -69,7 +69,7 @@ export const onRequest = sequence(
);
`.trim();

return source;
return { code };
}
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions
},
load(id) {
if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) {
return `export const serverIslandMap = ${serverIslandPlaceholder};`;
return { code: `export const serverIslandMap = ${serverIslandPlaceholder};` };
}
},
transform(_code, id) {
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/env/vite-plugin-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ export function astroEnv({ settings, sync, envLoader }: AstroEnvPluginParams): P
load(id, options) {
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.client)) {
ensureTemplateAreLoaded();
return templates!.client;
return { code: templates!.client };
}
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.server)) {
if (options?.ssr) {
ensureTemplateAreLoaded();
return templates!.server;
return { code: templates!.server };
}
throw new AstroError({
...AstroErrorData.ServerOnlyModule,
Expand All @@ -86,7 +86,7 @@ export function astroEnv({ settings, sync, envLoader }: AstroEnvPluginParams): P
}
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.internal)) {
ensureTemplateAreLoaded();
return templates!.internal;
return { code: templates!.internal };
}
},
};
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/manifest/virtual-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function virtualModulePlugin({
});
}
// There's nothing wrong about using `/client` on the server
return `${serializeClientConfig(manifest)};`;
return { code: serializeClientConfig(manifest) };
}
// server
else if (id == RESOLVED_VIRTUAL_SERVER_ID) {
Expand All @@ -58,7 +58,7 @@ export default function virtualModulePlugin({
message: AstroErrorData.ServerOnlyModule.message(VIRTUAL_SERVER_ID),
});
}
return `${serializeServerConfig(manifest)};`;
return { code: serializeServerConfig(manifest) };
}
},
};
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/prefetch/vite-plugin-prefetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function astroPrefetch({ settings }: { settings: AstroSettings })
load(id) {
if (id === resolvedVirtualModuleId) {
if (!prefetch) throwPrefetchNotEnabledError();
return `export { prefetch } from "astro/virtual-modules/prefetch.js";`;
return { code: `export { prefetch } from "astro/virtual-modules/prefetch.js";` };
}
},
transform(code, id) {
Expand Down
Loading