import path from "path"; import mime from "mime-types"; import { createFilter } from "@rollup/pluginutils"; import { InputPluginOption, TransformResult } from "rollup"; import MagicString from "magic-string"; import { computeContentHash } from "../crypto"; // Regex to find URLs in CSS/SASS const CSS_URL_REGEX = /url\(['"]?([^'")]+\.[^.)'"]+)['"]?\)/g; interface CssUrlOptions { include?: string | string[]; exclude?: string | string[]; shouldExtract?: ( filePath: string, fileContent: Uint8Array, mimeType: string, ) => boolean; getExtractNameAndUrl?: ( url: string, filePath: string, mimeType: string, contentHash: string, ) => { name: string; url: string }; warnSize?: number; } // helper so we can await inside String.replace const replaceAsync = async ( str: string, re: RegExp, fn: (...args: string[]) => Promise, ): Promise => { const parts: string[] = []; let last = 0; for (const m of str.matchAll(re)) { parts.push(str.slice(last, m.index!), await fn(...m)); last = m.index! + m[0].length; } parts.push(str.slice(last)); return parts.join(""); }; export function cssUrl(options: CssUrlOptions = {}): InputPluginOption { const filter = createFilter( options.include || ["**/*.scss", "**/*.sass", "**/*.css"], options.exclude, ); const shouldExtract = options.shouldExtract || ((_, content) => content.length > 14 * 1024); const getExtractNameAndUrl = options.getExtractNameAndUrl || ((url) => ({ name: url, url })); const warnSize = options.warnSize || 100 * 1024; const emittedFiles = new Set(); return { name: "css-url", transform: async function ( code: string, id: string, ): Promise { if (!filter(id)) { return null; } // Collect resolved asset file paths so the source manifest plugin // (and any other downstream consumer) can discover them via // this.getModuleInfo(id).meta[‘css-url’].assets. const resolvedAssets: string[] = []; const resultCode = await replaceAsync( code, CSS_URL_REGEX, async (match, url) => { // Don’t touch http(s) or already-inlined urls if (/^(?:data:|https?:|\/\/)/i.test(url)) { return match; } try { // Resolve path relative to the current file const currentDir = path.resolve(path.dirname(id)); const filePath = path.join(currentDir, url); const fileContent = await this.fs.readFile(filePath); this.addWatchFile(filePath); resolvedAssets.push(filePath); // Get MIME type const mimeType = mime.lookup(filePath); if (!mimeType) { this.warn(`Could not determine MIME type for file ${url}`); return match; } if (shouldExtract(filePath, fileContent, mimeType)) { const contentHash = await computeContentHash(fileContent); const { name, url: extractedUrl } = getExtractNameAndUrl( url, filePath, mimeType, contentHash, ); if (!emittedFiles.has(name)) { emittedFiles.add(name); this.emitFile({ type: "asset", fileName: name, source: fileContent, }); } return `url('${extractedUrl}')`; } else { // Warn if file is large if (fileContent.length > warnSize) { this.warn( `Inlining file ${url} with large size ${fileContent.length}`, ); } // inline as base64 data URL const base64 = Buffer.from(fileContent).toString("base64"); return `url('data:${mimeType};base64,${base64}')`; } } catch (err) { this.warn(`Error processing file ${url}: ${err}`); return match; } }, ); if (resultCode === code) { return null; } const magicString = new MagicString(resultCode); return { code: magicString.toString(), map: magicString.generateMap({ includeContent: true, hires: true, }), meta: { "css-url": { assets: resolvedAssets }, }, }; }, }; }