import { rollup as bareRollup, watch as rollupWatch, RollupBuild, InputOptions, OutputOptions, InputPluginOption, RollupWatchOptions, RollupWatcher, RollupOutput, OutputBundle, OutputChunk, OutputAsset, Plugin, } from "rollup"; import { FileSystem } from "@servicenow/sdk-build-core"; import MagicString from "magic-string"; import path from "path"; import { composeSourcemap } from "../utils/compose-sourcemap"; import fluentToRollupfs from "./fluent-to-rollupfs"; import { RollupFsAdapter } from "./rollup-fs-adapter"; import type { IsomorphicRollupFs } from "../fs-iface"; import type { RollupFsModule } from "rollup"; import webFsLoader from "../web-fs-loader"; import { isBrowserOrWorkerEnvironment } from "../utils/browser"; import { glob } from "../glob"; import { subtle } from "../crypto"; interface RollupOptions extends Omit { fs: FileSystem; // This is included for compatibility with config files but ignored by rollup.rollup output?: OutputOptions | OutputOptions[]; /** Minimum module size in bytes above which a node_modules dependency is * extracted into its own vendor chunk. Defaults to 200 000 (≈200 KB). */ vendorChunkThreshold?: number; } interface WatchOptions extends Omit { fs: FileSystem; } declare global { var __rollupFs: IsomorphicRollupFs | undefined; } /** * Checks whether the input looks like a glob pattern targeting HTML or XML * files (e.g. "src/client/**\/*.html"). When true, the wrapper resolves the * glob and runs one rollup build per file to prevent code-splitting. */ const isHtmlGlobInput = (input: unknown): input is string => typeof input === "string" && (input.includes("*") || input.includes("?")) && (input.endsWith(".html") || input.endsWith(".xml")); const setupRollupFs = (fs: FileSystem): RollupFsModule => { const rollupFs = fluentToRollupfs(fs); globalThis.__rollupFs = new RollupFsAdapter(fs); return rollupFs; }; const injectBrowserPlugins = (options: RollupOptions): RollupOptions => { if (isBrowserOrWorkerEnvironment()) { const existing: InputPluginOption[] = []; if (Array.isArray(options.plugins)) { existing.push(...options.plugins); } else if (options.plugins) { existing.push(options.plugins); } return { ...options, plugins: [...existing, webFsLoader()] }; } return options; }; /** * Build a single rollup bundle (one or more entries in a single invocation). */ const invokeSingleRollup = ( options: RollupOptions, rollupFs: RollupFsModule, ): Promise => { const opts = injectBrowserPlugins(options); return bareRollup({ ...opts, fs: rollupFs, }); }; /** * Merges multiple RollupOutput arrays into one, concatenating all chunks * and assets. The first entry of the first output is used as the leading * OutputChunk (required by the RollupOutput tuple type). */ const mergeOutputs = (outputs: RollupOutput[]): RollupOutput => { const seen = new Set(); const allItems: (OutputChunk | OutputAsset)[] = []; for (const o of outputs) { for (const item of o.output) { // Hash-named vendor chunks are identical across page builds; // keep only the first occurrence of each fileName. if (seen.has(item.fileName)) continue; seen.add(item.fileName); allItems.push(item); } } if (allItems.length === 0) { throw new Error("No output was generated from any rollup build."); } // RollupOutput requires the first element to be an OutputChunk. // Ensure a chunk leads the array even if the first output item is an asset. const firstChunkIdx = allItems.findIndex((o) => o.type === "chunk"); if (firstChunkIdx > 0) { const [chunk] = allItems.splice(firstChunkIdx, 1); allItems.unshift(chunk); } return { output: allItems as [OutputChunk, ...(OutputChunk | OutputAsset)[]], }; }; /** * Strips the trailing sourceMappingURL comment from chunk code so that two * chunks with identical logic but different sourcemap filenames compare equal. */ const stripSourcemapComment = (code: string): string => code.replace(/\/\/[#@]\s*sourceMappingURL=[^\n]*\s*$/, ""); /** * Computes a content hash using SHA-1 via the Web Crypto API. Produces an * 8-character hex digest suitable for content-based naming of vendor chunks. * Consistent with the hashing approach used by the URL plugin. */ const contentHash = async (str: string): Promise => { const bytes = new TextEncoder().encode(str); const digest = await subtle.digest("SHA-1", bytes); return Array.from(new Uint8Array(digest)) .map((b) => b.toString(16).padStart(2, "0")) .join("") .substring(0, 8); }; /** * Default minimum module size (in bytes of transformed source) above which the * module is extracted into its own chunk rather than inlined into the entry * bundle. 200 KB raw ≈ 50–60 KB gzipped — the point where a separate HTTP * request costs less than re-downloading the bytes in every entry. * Configurable via `vendorChunkThreshold` in RollupOptions. */ const DEFAULT_VENDOR_CHUNK_THRESHOLD = 200_000; /** * Rewrites references to renamed chunks in the code of all other chunks, * using MagicString so the sourcemap stays correct. */ const rewriteChunkReferences = ( renames: Map, bundle: OutputBundle, ): void => { if (renames.size === 0) return; for (const chunk of Object.values(bundle)) { if (chunk.type !== "chunk") continue; let modified = false; const s = new MagicString(chunk.code); for (const [oldName, newName] of renames) { let idx = chunk.code.indexOf(oldName); while (idx !== -1) { s.overwrite(idx, idx + oldName.length, newName, { contentOnly: true }); modified = true; idx = chunk.code.indexOf(oldName, idx + oldName.length); } } if (modified) { chunk.code = s.toString(); composeSourcemap(chunk, s.generateMap({ hires: "boundary" }), bundle); } } }; /** * Rollup plugin that extracts large node_modules into their own named chunks. * * In per-entry isolated builds every static dependency is inlined into the * entry chunk. When multiple pages share a large dependency (e.g. React), * each page duplicates it. This plugin records module sizes during * `transform` and uses `manualChunks` to extract node_modules that exceed * LARGE_MODULE_THRESHOLD into deterministic named chunks that the browser * can cache across page navigations. * * Only node_modules are extracted — user source code stays inlined per * entry to preserve build isolation. Extracting user code would create * shared chunks that re-introduce version skew when only one page is * rebuilt. * * Vendor chunks are named `vendor---` where the hash is * derived from the chunk's code. Identical vendor code across page builds * produces the same filename, so `mergeOutputs` deduplicates by fileName * and the filesystem naturally consolidates them during `write`. */ const extractLargeModules = ( entryTag: string, threshold = DEFAULT_VENDOR_CHUNK_THRESHOLD, ): Plugin => { const moduleSizes = new Map(); return { name: "extract-large-modules", transform(code, id) { moduleSizes.set(id, code.length); return null; }, outputOptions(options) { const existing = options.manualChunks; return { ...options, manualChunks(id, api) { if (typeof existing === "function") { const result = existing.call(this, id, api); if (result) return result; } else if (typeof existing === "object" && existing !== null) { // Rollup accepts manualChunks as Record. // Check if the module belongs to any user-defined chunk. for (const [chunkName, moduleIds] of Object.entries(existing)) { if (moduleIds.includes(id)) return chunkName; } } const size = moduleSizes.get(id); if (size && size > threshold) { // Only extract node_modules — user source code stays inlined // per entry to preserve build isolation. Extracting user code // would re-introduce shared-chunk version skew: modifying // the file and rebuilding one page silently affects others. // Module ids use native separators on Windows; normalize so the // same sources split identically on every OS. const normalizedId = id.replace(/\\/g, "/"); const nmIdx = normalizedId.lastIndexOf("node_modules/"); if (nmIdx !== -1) { const afterNm = normalizedId.slice( nmIdx + "node_modules/".length, ); const pkgName = afterNm.startsWith("@") ? afterNm.split("/").slice(0, 2).join("-") : afterNm.split("/")[0]; // Use entryTag as a temporary unique name; generateBundle // renames to a content hash once the code is known. return `vendor-${pkgName}--${entryTag}`; } } return undefined; }, }; }, async generateBundle(_options, bundle) { const renames = new Map(); for (const [fileName, chunk] of Object.entries(bundle)) { if (chunk.type !== "chunk" || !chunk.name?.startsWith("vendor-")) continue; const hash = await contentHash(stripSourcemapComment(chunk.code)); // vendor-react-dom--entryTag → vendor-react-dom-- const dashDashIdx = chunk.name.lastIndexOf("--"); const vendorPrefix = dashDashIdx !== -1 ? chunk.name.slice(0, dashDashIdx) : chunk.name; const ext = path.extname(fileName); const newFileName = `${vendorPrefix}--${hash}${ext}`; if (newFileName === fileName) continue; renames.set(fileName, newFileName); chunk.fileName = newFileName; bundle[newFileName] = chunk; delete bundle[fileName]; // Rename accompanying sourcemap const mapKey = fileName + ".map"; if (bundle[mapKey]) { const newMapKey = newFileName + ".map"; bundle[mapKey].fileName = newMapKey; bundle[newMapKey] = bundle[mapKey]; delete bundle[mapKey]; } } rewriteChunkReferences(renames, bundle); }, }; }; /** * Extracts the non-glob base directory from a glob pattern. * e.g. "/project/src/client/**\/*.html" → "/project/src/client" */ const globBase = (pattern: string): string => { let dir = pattern; while (path.basename(dir).includes("*") || path.basename(dir).includes("?")) { dir = path.dirname(dir); } return dir; }; /** * Derives a deterministic entry tag from an HTML file path by kebab-casing * the full relative path (without extension) from `baseDir`. Used as a * temporary discriminator for vendor chunk names before content-hash renaming. * * Examples: * deriveEntryTag("/p/src/client/index.html", "/p/src/client") → "index" * deriveEntryTag("/p/src/client/llama-page/index.html", "/p/src/client") → "llama-page-index" * deriveEntryTag("/p/src/client/admin/settings.html", "/p/src/client") → "admin-settings" * deriveEntryTag("/p/src/client/admin/deep/page.html", "/p/src/client") → "admin-deep-page" */ const deriveEntryTag = (filePath: string, baseDir: string): string => { const relative = path.relative(baseDir, filePath).replace(/\\/g, "/"); const withoutExt = relative.replace(/\.[^.]+$/, ""); return withoutExt.replace(/\//g, "-"); }; /** * Creates a deferred composite RollupBuild from a list of input files. * Unlike building upfront, this defers `bareRollup()` to write/generate * time so that each file gets a fully isolated build cycle (options → * buildStart → transform → generateBundle) with no shared plugin state. * * This is necessary because rollup plugins are stateful objects — the * options hook runs during bareRollup() and mutates plugin state (e.g. * uiPage's htmlRegistry). Building all files upfront and writing later * causes all options hooks to run before any generateBundle, breaking * per-entry isolation. */ const createDeferredCompositeRollupBuild = ( files: string[], options: RollupOptions, rollupFs: RollupFsModule, baseDir: string, ): RollupBuild => { const buildEach = async ( outputOptions: OutputOptions, method: "generate" | "write", ): Promise => { const outputs: RollupOutput[] = []; for (const file of files) { const existingPlugins: InputPluginOption[] = []; if (Array.isArray(options.plugins)) { existingPlugins.push(...options.plugins); } else if (options.plugins) { existingPlugins.push(options.plugins); } const entryTag = deriveEntryTag(file, baseDir); const build = await invokeSingleRollup( { ...options, input: file, plugins: [ extractLargeModules(entryTag, options.vendorChunkThreshold), ...existingPlugins, ], }, rollupFs, ); outputs.push(await build[method](outputOptions)); await build.close(); } return mergeOutputs(outputs); }; return { cache: undefined, closed: false, watchFiles: [], async close() { this.closed = true; }, async [Symbol.asyncDispose]() { await this.close(); }, async generate(outputOptions: OutputOptions): Promise { if (this.closed) { throw new Error( "Bundle is already closed, no more calls to 'generate' are allowed.", ); } return buildEach(outputOptions, "generate"); }, async write(outputOptions: OutputOptions): Promise { if (this.closed) { throw new Error( "Bundle is already closed, no more calls to 'write' are allowed.", ); } return buildEach(outputOptions, "write"); }, }; }; const invokeRollup = async (options: RollupOptions): Promise => { if (!options.fs) { return Promise.reject( new Error( "A filesystem must be provided, but none was found on options.fs", ), ); } const rollupFs = setupRollupFs(options.fs); // When input is a glob matching HTML/XML files, build each file as a // separate rollup invocation. This prevents code-splitting: each entry // gets a fully self-contained bundle with all dependencies inlined. // // UI Pages load independently on separate .do endpoints — shared chunks // provide no runtime benefit and can break during partial rebuilds when // only some pages are reconfigured. if (isHtmlGlobInput(options.input)) { const baseDir = globBase(options.input); const files = await glob(options.input, { fs: options.fs }); const sortedFiles = files .map((f) => String(f)) .sort((a, b) => a.localeCompare(b, "en")); if (sortedFiles.length === 0) { // No files matched — fall through to single build so rollup can // report its own error or plugins can handle the empty input. return invokeSingleRollup(options, rollupFs); } if (sortedFiles.length === 1) { const entryTag = deriveEntryTag(sortedFiles[0], baseDir); const existingPlugins: InputPluginOption[] = []; if (Array.isArray(options.plugins)) { existingPlugins.push(...options.plugins); } else if (options.plugins) { existingPlugins.push(options.plugins); } return invokeSingleRollup( { ...options, input: sortedFiles[0], plugins: [ extractLargeModules(entryTag, options.vendorChunkThreshold), ...existingPlugins, ], }, rollupFs, ); } return createDeferredCompositeRollupBuild( sortedFiles, options, rollupFs, baseDir, ); } return invokeSingleRollup(options, rollupFs); }; const invokeWatch = (options: WatchOptions): RollupWatcher => { if (isBrowserOrWorkerEnvironment()) { throw new Error("watch() is not supported in browser/worker environments"); } if (!options.fs) { throw new Error( "A filesystem must be provided, but none was found on options.fs", ); } const rollupFs = fluentToRollupfs(options.fs); /** * Creates a global that's accessible to all other plugins that we know of * that can use our passed in filesystem. */ globalThis.__rollupFs = new RollupFsAdapter(options.fs); // webFsLoader is intentionally not injected here: watch is a dev/Node-only // feature and is never invoked in browser or worker environments. return rollupWatch({ ...options, fs: rollupFs, }); }; export const rollup = (options: RollupOptions): Promise => { return invokeRollup(options); }; export const watch = (options: WatchOptions): RollupWatcher => { return invokeWatch(options); }; export { defineConfig, VERSION } from "rollup";