jest.mock("rollup", () => ({ rollup: jest.fn().mockResolvedValue({}), watch: jest.fn().mockReturnValue({ on: jest.fn(), close: jest.fn() }), defineConfig: (config: any) => config, })); jest.mock("../../src/rollup/fluent-to-rollupfs", () => jest.fn().mockReturnValue({}), ); jest.mock("../../src/rollup/rollup-fs-adapter", () => ({ RollupFsAdapter: jest.fn().mockImplementation(() => ({})), })); jest.mock("../../src/web-fs-loader", () => jest.fn().mockReturnValue({ name: "web-fs-loader" }), ); jest.mock("../../src/utils/browser", () => ({ isBrowserOrWorkerEnvironment: jest.fn().mockReturnValue(false), })); jest.mock("../../src/glob", () => ({ glob: jest.fn().mockResolvedValue([]), })); import { rollup, watch } from "../../src/rollup"; import { glob } from "../../src/glob"; const makeFs = () => ({ readFileSync: jest.fn(), writeFileSync: jest.fn(), statSync: jest.fn(), readdirSync: jest.fn(), mkdirSync: jest.fn(), copyFileSync: jest.fn(), realpathSync: jest.fn(), renameSync: jest.fn(), rmSync: jest.fn(), lstatSync: jest.fn(), }) as any; describe("rollup wrapper", () => { beforeEach(() => { jest.clearAllMocks(); delete (globalThis as any).__rollupFs; }); describe("rollup()", () => { test("should reject when fs is not provided", async () => { await expect(rollup({} as any)).rejects.toThrow( "A filesystem must be provided, but none was found on options.fs", ); }); test("should convert the FileSystem via fluentToRollupfs and pass it to bareRollup", async () => { const bareRollupMock = require("rollup").rollup; const fluentToRollupfs = require("../../src/rollup/fluent-to-rollupfs"); const mockRollupFs = { mocked: "rollupfs" }; fluentToRollupfs.mockReturnValue(mockRollupFs); const fs = makeFs(); await rollup({ fs, input: "src/index.ts" }); expect(fluentToRollupfs).toHaveBeenCalledWith(fs); expect(bareRollupMock).toHaveBeenCalledWith( expect.objectContaining({ fs: mockRollupFs }), ); }); test("should set globalThis.__rollupFs", async () => { const fs = makeFs(); await rollup({ fs, input: "src/index.ts" }); expect((globalThis as any).__rollupFs).toBeDefined(); }); }); describe("watch()", () => { test("should throw when called in a browser/worker environment", () => { const { isBrowserOrWorkerEnvironment, } = require("../../src/utils/browser"); isBrowserOrWorkerEnvironment.mockReturnValueOnce(true); expect(() => watch({ fs: makeFs(), input: "src/index.ts" })).toThrow( "watch() is not supported in browser/worker environments", ); }); test("should throw when fs is not provided", () => { expect(() => watch({} as any)).toThrow( "A filesystem must be provided, but none was found on options.fs", ); }); test("should convert the FileSystem via fluentToRollupfs and pass it to rollupWatch", () => { const rollupWatchMock = require("rollup").watch; const fluentToRollupfs = require("../../src/rollup/fluent-to-rollupfs"); const mockRollupFs = { mocked: "rollupfs" }; fluentToRollupfs.mockReturnValue(mockRollupFs); const fs = makeFs(); watch({ fs, input: "src/index.ts" }); expect(fluentToRollupfs).toHaveBeenCalledWith(fs); expect(rollupWatchMock).toHaveBeenCalledWith( expect.objectContaining({ fs: mockRollupFs }), ); }); test("should set globalThis.__rollupFs", () => { const fs = makeFs(); watch({ fs, input: "src/index.ts" }); expect((globalThis as any).__rollupFs).toBeDefined(); }); test("should not inject webFsLoader (watch is Node-only, never invoked in browser)", () => { const webFsLoader = require("../../src/web-fs-loader"); const fs = makeFs(); watch({ fs, input: "src/index.ts" }); expect(webFsLoader).not.toHaveBeenCalled(); }); }); describe("composite build", () => { const makeBuildWithOutput = (output: any[]) => ({ generate: jest.fn().mockResolvedValue({ output }), write: jest.fn().mockResolvedValue({ output }), close: jest.fn(), }); test("does not mutate plugins array across iterations in browser mode", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; const { isBrowserOrWorkerEnvironment, } = require("../../src/utils/browser"); isBrowserOrWorkerEnvironment.mockReturnValue(true); globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js" }, ]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js" }, ]), ); const plugins = [{ name: "test-plugin" }]; const build = await rollup({ fs: makeFs(), input: "src/client/*.html", plugins, }); await build.write({ dir: "dist" }); // Original array must not have been mutated expect(plugins).toHaveLength(1); // Both calls should have extract-large-modules + webFsLoader appended independently expect(bareRollupMock).toHaveBeenCalledTimes(2); for (const call of bareRollupMock.mock.calls) { const passedPlugins = call[0].plugins; expect(passedPlugins).toHaveLength(3); // test-plugin + extract-large-modules + web-fs-loader } }); test("throws when generate is called after close", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); bareRollupMock.mockResolvedValue( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.close(); await expect(build.generate({ dir: "dist" })).rejects.toThrow( "Bundle is already closed", ); }); test("throws when write is called after close", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); bareRollupMock.mockResolvedValue( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.close(); await expect(build.write({ dir: "dist" })).rejects.toThrow( "Bundle is already closed", ); }); test("injects extract-large-modules plugin into each composite build entry", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js" }, ]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js" }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); expect(bareRollupMock).toHaveBeenCalledTimes(2); for (const call of bareRollupMock.mock.calls) { const plugins = call[0].plugins as any[]; const extractPlugin = plugins.find( (p: any) => p && p.name === "extract-large-modules", ); expect(extractPlugin).toBeDefined(); expect(typeof extractPlugin.transform).toBe("function"); expect(typeof extractPlugin.outputOptions).toBe("function"); } }); test("extract-large-modules assigns vendor chunk name for large node_modules", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); // Capture the extract-large-modules plugin from the first build call let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); // Simulate transform recording a large module (>200KB) const largeCode = "x".repeat(200_001); extractPlugin.transform( largeCode, "/project/node_modules/react-dom/cjs/react-dom.production.js", ); // Get the manualChunks function from outputOptions const outputOpts = extractPlugin.outputOptions({}); const chunkName = outputOpts.manualChunks( "/project/node_modules/react-dom/cjs/react-dom.production.js", {} as any, ); expect(chunkName).toBe("vendor-react-dom--page1"); }); test("extract-large-modules handles Windows backslash module ids", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const largeCode = "x".repeat(200_001); const unscoped = "C:\\project\\node_modules\\react-dom\\cjs\\react-dom.production.js"; const scoped = "C:\\project\\node_modules\\@servicenow\\ui-renderer\\dist\\index.js"; extractPlugin.transform(largeCode, unscoped); extractPlugin.transform(largeCode, scoped); const outputOpts = extractPlugin.outputOptions({}); expect(outputOpts.manualChunks(unscoped, {} as any)).toBe( "vendor-react-dom--page1", ); expect(outputOpts.manualChunks(scoped, {} as any)).toBe( "vendor-@servicenow-ui-renderer--page1", ); }); test("extract-large-modules assigns vendor chunk name for scoped packages", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const largeCode = "x".repeat(200_001); extractPlugin.transform( largeCode, "/project/node_modules/@servicenow/ui-renderer/dist/index.js", ); const outputOpts = extractPlugin.outputOptions({}); const chunkName = outputOpts.manualChunks( "/project/node_modules/@servicenow/ui-renderer/dist/index.js", {} as any, ); expect(chunkName).toBe("vendor-@servicenow-ui-renderer--page1"); }); test("extract-large-modules does not extract large non-node_modules files", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const largeCode = "x".repeat(200_001); extractPlugin.transform(largeCode, "/project/src/lib/huge-data.ts"); const outputOpts = extractPlugin.outputOptions({}); const chunkName = outputOpts.manualChunks( "/project/src/lib/huge-data.ts", {} as any, ); expect(chunkName).toBeUndefined(); }); test("extract-large-modules does not extract small node_modules", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); // Small module (under 200KB threshold) extractPlugin.transform( "small code", "/project/node_modules/lodash/pick.js", ); const outputOpts = extractPlugin.outputOptions({}); const chunkName = outputOpts.manualChunks( "/project/node_modules/lodash/pick.js", {} as any, ); expect(chunkName).toBeUndefined(); }); test("extract-large-modules preserves existing manualChunks function", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); // Existing manualChunks that claims a module const existingManualChunks = jest.fn().mockReturnValue("custom-chunk"); const outputOpts = extractPlugin.outputOptions({ manualChunks: existingManualChunks, }); const chunkName = outputOpts.manualChunks( "/project/node_modules/react/index.js", {} as any, ); // Existing function takes priority expect(chunkName).toBe("custom-chunk"); expect(existingManualChunks).toHaveBeenCalled(); }); test("different pages get different vendor chunk names", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); const extractPlugins: any[] = []; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin) { extractPlugins.push(plugin); } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); expect(extractPlugins).toHaveLength(2); const largeCode = "x".repeat(200_001); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; // Each plugin instance produces a different vendor chunk name extractPlugins[0].transform(largeCode, moduleId); const opts0 = extractPlugins[0].outputOptions({}); expect(opts0.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page1", ); extractPlugins[1].transform(largeCode, moduleId); const opts1 = extractPlugins[1].outputOptions({}); expect(opts1.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page2", ); }); test("single-entry glob injects extract-large-modules", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); bareRollupMock.mockResolvedValue( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js" }, ]), ); await rollup({ fs: makeFs(), input: "src/client/*.html", }); expect(bareRollupMock).toHaveBeenCalledTimes(1); const plugins = bareRollupMock.mock.calls[0][0].plugins as any[]; const extractPlugin = plugins.find( (p: any) => p && p.name === "extract-large-modules", ); expect(extractPlugin).toBeDefined(); }); test("nested entry derives kebab-cased entry tag from full relative path", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/admin/settings.html", "src/client/dashboard/index.html", ]); const extractPlugins: any[] = []; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin) { extractPlugins.push(plugin); } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/**/*.html", }); await build.generate({ dir: "dist" }); const largeCode = "x".repeat(200_001); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; extractPlugins[0].transform(largeCode, moduleId); const opts0 = extractPlugins[0].outputOptions({}); expect(opts0.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--admin-settings", ); extractPlugins[1].transform(largeCode, moduleId); const opts1 = extractPlugins[1].outputOptions({}); expect(opts1.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--dashboard-index", ); }); test("mergeOutputs deduplicates chunks with the same fileName", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); const vendorCode = "var react = 'big module';\nexport { react };"; // Both builds produce a vendor chunk with the same fileName // (simulates what generateBundle does — renames to content hash) bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js", code: "import './vendor-react-dom--abcd1234.jsdbx';", }, { type: "chunk", isEntry: false, fileName: "vendor-react-dom--abcd1234.jsdbx", name: "vendor-react-dom--page1", code: vendorCode, }, { type: "asset", fileName: "vendor-react-dom--abcd1234.jsdbx.map", source: "sourcemap-content", }, ]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js", code: "import './vendor-react-dom--abcd1234.jsdbx';", }, { type: "chunk", isEntry: false, fileName: "vendor-react-dom--abcd1234.jsdbx", name: "vendor-react-dom--page2", code: vendorCode, }, { type: "asset", fileName: "vendor-react-dom--abcd1234.jsdbx.map", source: "sourcemap-content", }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); const result = await build.generate({ dir: "dist" }); // Only one copy of the vendor chunk and its sourcemap in merged output const vendorChunks = result.output.filter( (o: any) => o.fileName === "vendor-react-dom--abcd1234.jsdbx", ); expect(vendorChunks).toHaveLength(1); const vendorMaps = result.output.filter( (o: any) => o.fileName === "vendor-react-dom--abcd1234.jsdbx.map", ); expect(vendorMaps).toHaveLength(1); // Both entry chunks are present expect( result.output.find((o: any) => o.fileName === "page1.js"), ).toBeDefined(); expect( result.output.find((o: any) => o.fileName === "page2.js"), ).toBeDefined(); }); test("mergeOutputs keeps chunks with different fileNames", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); // Builds produce vendor chunks with different fileNames (different code) bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js", code: "import './vendor-react-dom--aaaa1111.jsdbx';", }, { type: "chunk", isEntry: false, fileName: "vendor-react-dom--aaaa1111.jsdbx", name: "vendor-react-dom--page1", code: "var react = 'version-a';", }, ]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js", code: "import './vendor-react-dom--bbbb2222.jsdbx';", }, { type: "chunk", isEntry: false, fileName: "vendor-react-dom--bbbb2222.jsdbx", name: "vendor-react-dom--page2", code: "var react = 'version-b';", }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); const result = await build.generate({ dir: "dist" }); // Both vendor chunks kept — different hash = different file const vendor1 = result.output.find( (o: any) => o.fileName === "vendor-react-dom--aaaa1111.jsdbx", ) as any; const vendor2 = result.output.find( (o: any) => o.fileName === "vendor-react-dom--bbbb2222.jsdbx", ) as any; expect(vendor1.code).toBe("var react = 'version-a';"); expect(vendor2.code).toBe("var react = 'version-b';"); }); test("extract-large-modules has generateBundle hook for hash renaming", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); expect(extractPlugin.generateBundle).toBeDefined(); // Simulate generateBundle renaming a vendor chunk const bundle: Record = { "page.js": { type: "chunk", isEntry: true, fileName: "page.js", name: "page", code: "import './vendor-react-dom--page1.jsdbx';", }, "vendor-react-dom--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page1.jsdbx", name: "vendor-react-dom--page1", code: "var react = 'module code';", }, }; await extractPlugin.generateBundle({}, bundle); // The entry-tagged key should be gone, replaced by a hash-named key expect(bundle["vendor-react-dom--page1.jsdbx"]).toBeUndefined(); const vendorKeys = Object.keys(bundle).filter((k) => k.startsWith("vendor-react-dom--"), ); expect(vendorKeys).toHaveLength(1); expect(vendorKeys[0]).toMatch(/^vendor-react-dom--[0-9a-f]{8}\.jsdbx$/); // Entry chunk's import reference is rewritten expect(bundle["page.js"].code).toContain(vendorKeys[0]); expect(bundle["page.js"].code).not.toContain("page1"); }); test("mergeOutputs places a chunk first even if assets precede it", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); // First build returns only an asset, second returns a chunk bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([{ type: "asset", fileName: "style.css" }]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js" }, ]), ); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); const result = await build.generate({ dir: "dist" }); expect(result.output[0].type).toBe("chunk"); }); test("emits per-page .translations.json for each HTML entry", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); // The perPageTranslations plugin runs inside generateBundle before // rollup produces its output. We simulate its effect by returning // output that already has per-page filenames — the plugin renamed // them in the bundle object before rollup serialized the result. bareRollupMock .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page1.js" }, { type: "asset", fileName: "page1.html", source: "" }, { type: "asset", fileName: "page1.translations.json", source: JSON.stringify({ messages: ["Save", "Cancel"] }), }, ]), ) .mockResolvedValueOnce( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page2.js" }, { type: "asset", fileName: "page2.html", source: "" }, { type: "asset", fileName: "page2.translations.json", source: JSON.stringify({ messages: ["Cancel", "Delete"] }), }, ]), ); const fs = makeFs(); const build = await rollup({ fs, input: "src/client/*.html", }); const result = await build.generate({ dir: "dist" }); // Each page should have its own translations file const page1Translations = result.output.find( (o) => o.type === "asset" && o.fileName === "page1.translations.json", ); const page2Translations = result.output.find( (o) => o.type === "asset" && o.fileName === "page2.translations.json", ); expect(page1Translations).toBeDefined(); const parsed1 = JSON.parse((page1Translations as any).source); expect(parsed1.messages).toEqual(["Save", "Cancel"]); expect(page2Translations).toBeDefined(); const parsed2 = JSON.parse((page2Translations as any).source); expect(parsed2.messages).toEqual(["Cancel", "Delete"]); // No generic .translations.json should exist const genericTranslations = result.output.find( (o) => o.type === "asset" && o.fileName === ".translations.json", ); expect(genericTranslations).toBeUndefined(); }); test("identical vendor code produces the same content hash across builds", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); const extractPlugins: any[] = []; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin) { extractPlugins.push(plugin); } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const vendorCode = "var react = 'big module';\nexport { react };"; // Build 1: page1's vendor chunk const bundle1: Record = { "vendor-react-dom--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page1.jsdbx", name: "vendor-react-dom--page1", code: vendorCode, }, }; await extractPlugins[0].generateBundle({}, bundle1); // Build 2: page2's vendor chunk with identical code const bundle2: Record = { "vendor-react-dom--page2.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page2.jsdbx", name: "vendor-react-dom--page2", code: vendorCode, }, }; await extractPlugins[1].generateBundle({}, bundle2); const hash1 = Object.keys(bundle1)[0]; const hash2 = Object.keys(bundle2)[0]; expect(hash1).toBe(hash2); }); test("sourcemap comment does not affect content hash", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce([ "src/client/page1.html", "src/client/page2.html", ]); const extractPlugins: any[] = []; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin) { extractPlugins.push(plugin); } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const baseCode = "var react = 'big module';\nexport { react };"; // Chunk with sourcemap comment A const bundle1: Record = { "vendor-react-dom--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page1.jsdbx", name: "vendor-react-dom--page1", code: baseCode + "\n//# sourceMappingURL=vendor-react-dom--page1.jsdbx.map", }, }; await extractPlugins[0].generateBundle({}, bundle1); // Chunk with sourcemap comment B (different filename) const bundle2: Record = { "vendor-react-dom--page2.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page2.jsdbx", name: "vendor-react-dom--page2", code: baseCode + "\n//# sourceMappingURL=vendor-react-dom--page2.jsdbx.map", }, }; await extractPlugins[1].generateBundle({}, bundle2); // Same logical code → same hash despite different sourcemap comments const hash1 = Object.keys(bundle1)[0]; const hash2 = Object.keys(bundle2)[0]; expect(hash1).toBe(hash2); }); test("multiple vendor chunks from one entry get separate hashes", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); // Two large modules extracted from same entry const largeCode = "x".repeat(200_001); extractPlugin.transform( largeCode, "/project/node_modules/react-dom/index.js", ); extractPlugin.transform( largeCode + " different", "/project/node_modules/lodash/index.js", ); const outputOpts = extractPlugin.outputOptions({}); expect( outputOpts.manualChunks( "/project/node_modules/react-dom/index.js", {} as any, ), ).toBe("vendor-react-dom--page1"); expect( outputOpts.manualChunks( "/project/node_modules/lodash/index.js", {} as any, ), ).toBe("vendor-lodash--page1"); // generateBundle renames both to content hashes const bundle: Record = { "page.js": { type: "chunk", isEntry: true, fileName: "page.js", name: "page", code: "import './vendor-react-dom--page1.jsdbx';\nimport './vendor-lodash--page1.jsdbx';", }, "vendor-react-dom--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page1.jsdbx", name: "vendor-react-dom--page1", code: "var react = 'react code';", }, "vendor-lodash--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-lodash--page1.jsdbx", name: "vendor-lodash--page1", code: "var lodash = 'lodash code';", }, }; await extractPlugin.generateBundle({}, bundle); // Both entry-tagged keys should be gone expect(bundle["vendor-react-dom--page1.jsdbx"]).toBeUndefined(); expect(bundle["vendor-lodash--page1.jsdbx"]).toBeUndefined(); // Two distinct hash-named vendor chunks const reactKeys = Object.keys(bundle).filter((k) => k.startsWith("vendor-react-dom--"), ); const lodashKeys = Object.keys(bundle).filter((k) => k.startsWith("vendor-lodash--"), ); expect(reactKeys).toHaveLength(1); expect(lodashKeys).toHaveLength(1); expect(reactKeys[0]).toMatch(/^vendor-react-dom--[0-9a-f]{8}\.jsdbx$/); expect(lodashKeys[0]).toMatch(/^vendor-lodash--[0-9a-f]{8}\.jsdbx$/); // Entry chunk references both new filenames expect(bundle["page.js"].code).toContain(reactKeys[0]); expect(bundle["page.js"].code).toContain(lodashKeys[0]); }); test("module at exactly the threshold is not extracted", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; // Exactly 200_000 bytes — at the threshold, NOT above it extractPlugin.transform("x".repeat(200_000), moduleId); const outputOpts = extractPlugin.outputOptions({}); expect(outputOpts.manualChunks(moduleId, {} as any)).toBeUndefined(); // 200_001 bytes — above the threshold extractPlugin.transform("x".repeat(200_001), moduleId); const outputOpts2 = extractPlugin.outputOptions({}); expect(outputOpts2.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page1", ); }); test("custom vendorChunkThreshold lowers extraction boundary", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", vendorChunkThreshold: 100, }); await build.generate({ dir: "dist" }); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; // 101 bytes — above the custom 100-byte threshold extractPlugin.transform("x".repeat(101), moduleId); const outputOpts = extractPlugin.outputOptions({}); expect(outputOpts.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page1", ); // 100 bytes — at the threshold, NOT above it extractPlugin.transform("x".repeat(100), moduleId); const outputOpts2 = extractPlugin.outputOptions({}); expect(outputOpts2.manualChunks(moduleId, {} as any)).toBeUndefined(); }); test("custom vendorChunkThreshold raises extraction boundary", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", vendorChunkThreshold: 500_000, }); await build.generate({ dir: "dist" }); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; // 300_000 bytes — above default 200K but below custom 500K threshold extractPlugin.transform("x".repeat(300_000), moduleId); const outputOpts = extractPlugin.outputOptions({}); expect(outputOpts.manualChunks(moduleId, {} as any)).toBeUndefined(); // 500_001 bytes — above the custom threshold extractPlugin.transform("x".repeat(500_001), moduleId); const outputOpts2 = extractPlugin.outputOptions({}); expect(outputOpts2.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page1", ); }); test("manualChunks respects existing object-form manualChunks", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const moduleId = "/project/node_modules/react-dom/cjs/react-dom.production.js"; const otherModuleId = "/project/node_modules/lodash/lodash.js"; extractPlugin.transform("x".repeat(300_000), moduleId); extractPlugin.transform("x".repeat(300_000), otherModuleId); // Provide manualChunks as an object mapping const outputOpts = extractPlugin.outputOptions({ manualChunks: { "my-custom-chunk": [otherModuleId] }, }); // lodash is claimed by the object-form manualChunks expect(outputOpts.manualChunks(otherModuleId, {} as any)).toBe( "my-custom-chunk", ); // react-dom is NOT in the object — falls through to size-based extraction expect(outputOpts.manualChunks(moduleId, {} as any)).toBe( "vendor-react-dom--page1", ); }); test("generateBundle handles vendor chunk name containing double dashes", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); // Simulate a scoped package whose name itself contains "--" // e.g. vendor-foo--bar--page1 (pkg name "foo--bar", entry tag "page1") const bundle: Record = { "vendor-foo--bar--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-foo--bar--page1.jsdbx", name: "vendor-foo--bar--page1", code: "var foo = 'bar';", }, }; await extractPlugin.generateBundle({}, bundle); // Old key gone expect(bundle["vendor-foo--bar--page1.jsdbx"]).toBeUndefined(); // The prefix should be "vendor-foo--bar" (lastIndexOf splits at the final --) const newKey = Object.keys(bundle).find((k) => k.match(/^vendor-foo--bar--[0-9a-f]{8}\.jsdbx$/), ); expect(newKey).toBeDefined(); }); test("generateBundle renames accompanying sourcemap files", async () => { const bareRollupMock = require("rollup").rollup; const globMock = glob as jest.Mock; globMock.mockResolvedValueOnce(["src/client/page1.html"]); let extractPlugin: any; bareRollupMock.mockImplementation((opts: any) => { const plugin = (opts.plugins as any[]).find( (p: any) => p && p.name === "extract-large-modules", ); if (plugin && !extractPlugin) { extractPlugin = plugin; } return Promise.resolve( makeBuildWithOutput([ { type: "chunk", isEntry: true, fileName: "page.js" }, ]), ); }); const build = await rollup({ fs: makeFs(), input: "src/client/*.html", }); await build.generate({ dir: "dist" }); const bundle: Record = { "vendor-react-dom--page1.jsdbx": { type: "chunk", isEntry: false, fileName: "vendor-react-dom--page1.jsdbx", name: "vendor-react-dom--page1", code: "var react = 'module code';", }, "vendor-react-dom--page1.jsdbx.map": { type: "asset", fileName: "vendor-react-dom--page1.jsdbx.map", source: '{"mappings":"AAAA"}', }, }; await extractPlugin.generateBundle({}, bundle); // Old keys gone expect(bundle["vendor-react-dom--page1.jsdbx"]).toBeUndefined(); expect(bundle["vendor-react-dom--page1.jsdbx.map"]).toBeUndefined(); // New hash-named chunk and its .map both exist const vendorKey = Object.keys(bundle).find((k) => k.match(/^vendor-react-dom--[0-9a-f]{8}\.jsdbx$/), ); expect(vendorKey).toBeDefined(); expect(bundle[vendorKey + ".map"]).toBeDefined(); expect(bundle[vendorKey + ".map"].fileName).toBe(vendorKey + ".map"); }); }); });