import type { Plugin, OutputBundle, OutputChunk } from "rollup"; import path from "path"; import { parseDOM } from "htmlparser2"; import { selectAll } from "css-select"; import serialize, { DomSerializerOptions } from "dom-serializer"; import type { IsomorphicRollupFs } from "../fs-iface"; import type { Element } from "domhandler"; import nodeFsAdapter from "../node-fs-adapter"; import { exists } from "../utils/fs-utils"; import { glob } from "glob"; interface HtmlScriptEntrypointsOptions { fs?: IsomorphicRollupFs; rootDir: string; updateSrcPath?: (originalSrc: string, emittedFileName: string) => string; entryPath?: ( entry: string, { fullPath, dir }: { fullPath: string; dir: string }, ) => { [key: string]: string }; serializerOptions?: DomSerializerOptions; transformHtml?: (html: string, fileName: string) => string; } interface HtmlInfo { htmlPath: string; htmlDir: string; document: Element; entryElements: Map; } export default function htmlScriptEntrypoints( options: HtmlScriptEntrypointsOptions, ): Plugin { const { rootDir, updateSrcPath = (_, emitted) => emitted, entryPath = (entry, context) => { const parsed = path.parse(entry); return { [parsed.name]: context.fullPath }; }, serializerOptions = {}, transformHtml = (html) => html, } = options; let htmlRegistry: HtmlInfo[] = []; const cleanup = () => { // Cleanup htmlRegistry = []; }; return { name: "html-script-entrypoints", async options(inputOptions) { if (typeof inputOptions.input !== "string") { this.error( "htmlScriptEntrypoints plugin only supports a single HTML file as input.", ); } const inputPath = inputOptions.input as string; if (!(inputPath.endsWith(".xml") || inputPath.endsWith(".html"))) { return; } const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter; if (!fs) { throw new Error("No filesystem was passed to plugin. Cannot continue"); } const fileExists = exists(fs); const globResults = await glob(inputPath, { fs, platform: process.platform, }); const entryPoints: Record = {}; for (const htmlPath of globResults.sort((a, b) => a.localeCompare(b, "en"), )) { const htmlDir = path.dirname(htmlPath); const htmlContent = (await fs.readFile(htmlPath, "utf8")) as string; const [document] = parseDOM(htmlContent, { decodeEntities: false, xmlMode: true, }) as Element[]; const scriptElements = selectAll( "script[src], g\\:import[src]", document.parent, ) as Element[]; const entryElements = new Map(); for (const scriptEl of scriptElements) { const src = scriptEl.attribs?.src; if (!src) continue; const resolved = path.resolve(htmlDir, src); const relativePath = path.relative(rootDir, resolved); const fullPathWithoutQueryParams = resolved.replace(/\?.+/, ""); const fileExistsResult = await fileExists(fullPathWithoutQueryParams); if (fileExistsResult) { const entry = entryPath(relativePath, { fullPath: resolved, dir: htmlDir, }); if (Object.keys(entry).length !== 1) { continue; } Object.assign(entryPoints, entry); const [entryKey] = Object.entries(entry)[0]; entryElements.set(entryKey, { scriptEl }); } } if (Object.keys(entryPoints).length < 1) { this.error( `No script entry points were found in ${htmlPath}. Expected a script tag that resolved to an entry point. (ex: '')`, ); } htmlRegistry.push({ htmlPath, htmlDir, document, entryElements, }); } return { ...inputOptions, input: entryPoints, }; }, buildStart() { htmlRegistry.forEach((item) => { this.addWatchFile(item.htmlPath); }); }, generateBundle(_, bundle: OutputBundle) { for (const { htmlPath, htmlDir, document, entryElements, } of htmlRegistry) { if ( !document || !document.parent || !htmlDir || !htmlPath || !entryElements ) continue; for (const [name, { scriptEl }] of entryElements.entries()) { const originalSrc = scriptEl.attribs?.src; if (!originalSrc) continue; const chunk = Object.values(bundle).find( (output): output is OutputChunk => output.type === "chunk" && output.name === name, ); if (chunk) { scriptEl.attribs.src = updateSrcPath(originalSrc, chunk.fileName); } } const updatedHtml = serialize(document.parent, { encodeEntities: false, xmlMode: true, emptyAttrs: true, ...serializerOptions, }); const htmlFileName = path.relative(rootDir, htmlPath); this.emitFile({ type: "asset", fileName: htmlFileName, source: transformHtml(updatedHtml, htmlFileName), }); } cleanup(); }, }; }