From fcb21c76b78aa7e4715f00f4529d260d87e74637 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Thu, 19 Nov 2026 12:16:44 +0900 Subject: [PATCH 1/2] perf(plugins): read each source once across the prepasses and compilers The import graph, the class-slot reservation and the prewarm each read the project's sources from disk, and a Next production build runs all of them again for its server, edge and client compilers. They now read through a stamp-checked cache that one build shares: plugin-utils' `readSource` serves a file again from the cache while its modification stamp is unchanged, inside `withSourceCache`. Next hands one cache to the webpack plugins of all its production compilers and uses one for the Turbopack setup; a plain webpack build shares one per preparation. Watch and dev builds still start from a fresh cache for each compilation. The module resolver keeps its own cache and reads misses through the shared one. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_shared_source_reads.json | 9 + .../next-plugin/src/__tests__/plugin.test.ts | 4278 +++++++++-------- packages/next-plugin/src/plugin.ts | 62 +- packages/next-plugin/src/prewarm.ts | 6 +- .../src/__tests__/source-cache.test.ts | 103 + packages/plugin-utils/src/import-graph.ts | 27 +- packages/plugin-utils/src/index.ts | 1 + .../plugin-utils/src/reservation-discovery.ts | 4 +- packages/plugin-utils/src/source-cache.ts | 65 + .../src/__tests__/plugin.test.ts | 26 + packages/webpack-plugin/src/plugin.ts | 24 +- 11 files changed, 2432 insertions(+), 2173 deletions(-) create mode 100644 .changepacks/changepack_log_shared_source_reads.json create mode 100644 packages/plugin-utils/src/__tests__/source-cache.test.ts create mode 100644 packages/plugin-utils/src/source-cache.ts diff --git a/.changepacks/changepack_log_shared_source_reads.json b/.changepacks/changepack_log_shared_source_reads.json new file mode 100644 index 000000000..f48a22bcd --- /dev/null +++ b/.changepacks/changepack_log_shared_source_reads.json @@ -0,0 +1,9 @@ +{ + "changes": { + "packages/plugin-utils/package.json": "Patch", + "packages/webpack-plugin/package.json": "Patch", + "packages/next-plugin/package.json": "Patch" + }, + "note": "Read each source file once per build in the passes that run before the bundler. The import graph, the class-slot reservation and the prewarm read the same files, and a Next production build runs them once per compiler (server, edge, client): they now share a stamp-checked source cache (`withSourceCache` / `readSource` in plugin-utils), which Next passes to the webpack plugin of each compiler. Watch and dev builds keep reading the disk on every compilation. Output is unchanged.", + "date": "2026-11-19T00:00:00.000Z" +} diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index b70090bbd..5350eaecd 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -1,2127 +1,2151 @@ -import { spawnSync } from 'node:child_process' -import * as fs from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' - -import type { StaticImportGraph } from '@devup-ui/plugin-utils' -import * as importGraphModule from '@devup-ui/plugin-utils' -import * as wasm from '@devup-ui/wasm' -import * as webpackPluginModule from '@devup-ui/webpack-plugin' -import { - afterEach, - beforeEach, - describe, - expect, - it, - mock, - spyOn, -} from 'bun:test' - -import * as coordinatorModule from '../coordinator' -import * as coordinatorPortModule from '../coordinator-port' -import cssLoader, { resetInit as resetCssInit } from '../css-loader' -import { - DevupUI, - reloadTurboSetupModuleForTesting, - resetTurboSetupCacheForTesting, - restoreSessionState, -} from '../plugin' -import { - loadWasm, - setWasmForTesting, - setWebpackPluginForTesting, -} from '../wasm' - -type CodeExtractResult = ReturnType -type NextWebpackConfig = Parameters< - NonNullable['webpack']> ->[0] -type NextWebpackContext = Parameters< - NonNullable['webpack']> ->[1] - -function createWebpackConfig(): NextWebpackConfig { - return { plugins: [] } as unknown as NextWebpackConfig -} - -function createWebpackContext( - overrides: Partial = {}, -): NextWebpackContext { - return { buildId: 'tmpBuildId', ...overrides } as NextWebpackContext -} - -function setNodeEnv(value: string): void { - process.env.NODE_ENV = value -} - -function createCodeExtractResult(contents: string): CodeExtractResult { - return { - css: '', - code: contents, - cssFile: '', - map: undefined, - updatedBaseStyle: false, - free: mock(), - [Symbol.dispose]: mock(), - } as unknown as CodeExtractResult -} - -function createSingleFileGraph(filename: string): StaticImportGraph { - return { - files: [filename], - fileSet: new Set([filename]), - staticImports: new Map([[filename, new Set()]]), - staticImporters: new Map([[filename, new Set()]]), - dynamicTargets: new Set(), - dynamicImports: new Map([[filename, new Set()]]), - externalImports: new Map([[filename, new Set()]]), - } -} - -let existsSyncSpy: ReturnType -let mkdirSyncSpy: ReturnType -let readFileSyncSpy: ReturnType -let writeFileSyncSpy: ReturnType -let unlinkSyncSpy: ReturnType -let getDefaultThemeSpy: ReturnType -let getThemeInterfaceSpy: ReturnType -let setPrefixSpy: ReturnType -let registerThemeSpy: ReturnType -let getCssSpy: ReturnType -let importSheetSpy: ReturnType -let importClassMapSpy: ReturnType -let importFileMapSpy: ReturnType -let exportSheetSpy: ReturnType -let exportClassMapSpy: ReturnType -let exportFileMapSpy: ReturnType -let codeExtractSpy: ReturnType -let codeExtractWithoutSourceMapSpy: ReturnType -let devupUIWebpackPluginSpy: ReturnType -let startCoordinatorSpy: ReturnType -let readJsxImportSourceSpy: ReturnType - -let originalEnv: NodeJS.ProcessEnv -let originalEnvValues: NodeJS.ProcessEnv -let originalFetch: typeof global.fetch -let originalDebugPort: number - -beforeEach(() => { - resetTurboSetupCacheForTesting() - existsSyncSpy = spyOn(fs, 'existsSync').mockReturnValue(false) - mkdirSyncSpy = spyOn(fs, 'mkdirSync').mockReturnValue(undefined) - readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue('{}') - writeFileSyncSpy = spyOn(fs, 'writeFileSync').mockReturnValue(undefined) - unlinkSyncSpy = spyOn(fs, 'unlinkSync').mockReturnValue(undefined) - getDefaultThemeSpy = spyOn(wasm, 'getDefaultTheme').mockReturnValue(undefined) - getThemeInterfaceSpy = spyOn(wasm, 'getThemeInterface').mockReturnValue('') - setPrefixSpy = spyOn(wasm, 'setPrefix').mockReturnValue(undefined) - registerThemeSpy = spyOn(wasm, 'registerTheme').mockReturnValue(undefined) - getCssSpy = spyOn(wasm, 'getCss').mockReturnValue('') - importSheetSpy = spyOn(wasm, 'importSheet').mockReturnValue(undefined) - importClassMapSpy = spyOn(wasm, 'importClassMap').mockReturnValue(undefined) - importFileMapSpy = spyOn(wasm, 'importFileMap').mockReturnValue(undefined) - exportSheetSpy = spyOn(wasm, 'exportSheet').mockReturnValue( - JSON.stringify({ - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }), - ) - exportClassMapSpy = spyOn(wasm, 'exportClassMap').mockReturnValue( - JSON.stringify({}), - ) - exportFileMapSpy = spyOn(wasm, 'exportFileMap').mockReturnValue( - JSON.stringify({}), - ) - codeExtractSpy = spyOn(wasm, 'codeExtract').mockImplementation( - (_path: string, contents: string) => createCodeExtractResult(contents), - ) - codeExtractWithoutSourceMapSpy = spyOn( - wasm, - 'codeExtractWithoutSourceMap', - ).mockImplementation((_path: string, contents: string) => - createCodeExtractResult(contents), - ) - devupUIWebpackPluginSpy = spyOn( - webpackPluginModule, - 'DevupUIWebpackPlugin', - ).mockImplementation(mock() as never) - startCoordinatorSpy = spyOn( - coordinatorModule, - 'startCoordinator', - ).mockReturnValue({ close: mock() as () => void }) - readJsxImportSourceSpy = spyOn( - importGraphModule, - 'readJsxImportSource', - ).mockReturnValue(undefined) - setWasmForTesting(wasm) - setWebpackPluginForTesting(webpackPluginModule) - - originalEnv = process.env - originalEnvValues = { ...originalEnv } - originalFetch = global.fetch - originalDebugPort = process.debugPort - global.fetch = mock(() => Promise.resolve({} as Response)) -}) - -afterEach(() => { - coordinatorModule.resetCoordinator() - resetTurboSetupCacheForTesting() - setWasmForTesting(undefined) - setWebpackPluginForTesting(undefined) - for (const key of Object.keys(originalEnv)) { - if (!Object.hasOwn(originalEnvValues, key)) delete originalEnv[key] - } - Object.assign(originalEnv, originalEnvValues) - process.env = originalEnv - global.fetch = originalFetch - process.debugPort = originalDebugPort - readJsxImportSourceSpy.mockRestore() - existsSyncSpy.mockRestore() - mkdirSyncSpy.mockRestore() - readFileSyncSpy.mockRestore() - writeFileSyncSpy.mockRestore() - unlinkSyncSpy.mockRestore() - getDefaultThemeSpy.mockRestore() - getThemeInterfaceSpy.mockRestore() - setPrefixSpy.mockRestore() - registerThemeSpy.mockRestore() - getCssSpy.mockRestore() - importSheetSpy.mockRestore() - importClassMapSpy.mockRestore() - importFileMapSpy.mockRestore() - exportSheetSpy.mockRestore() - exportClassMapSpy.mockRestore() - exportFileMapSpy.mockRestore() - codeExtractSpy.mockRestore() - codeExtractWithoutSourceMapSpy.mockRestore() - devupUIWebpackPluginSpy.mockRestore() - startCoordinatorSpy.mockRestore() -}) - -describe('DevupUINextPlugin', () => { - it.each(['1', 'auto', undefined])( - 'rejects typos at creation before setup in mode %s', - (mode) => { - if (mode === undefined) delete process.env.TURBOPACK - else process.env.TURBOPACK = mode - expect(() => - Reflect.apply(DevupUI, undefined, [ - {}, - { shorthands: { bgx: ['backgroundColour'] } }, - ]), - ).toThrow(importGraphModule.ShorthandConfigError) - expect(writeFileSyncSpy).not.toHaveBeenCalled() - expect(startCoordinatorSpy).not.toHaveBeenCalled() - expect(devupUIWebpackPluginSpy).not.toHaveBeenCalled() - }, - ) - - it('registers canonical targets when a Turbopack plugin is created', () => { - process.env.TURBOPACK = '1' - const registration = spyOn(wasm, 'registerShorthands').mockReturnValue( - undefined, - ) - try { - DevupUI({}, { shorthands: { bgx: ['backgroundColor', 'py', '--Gap'] } }) - expect(registration.mock.calls).toEqual([ - [ - { - bgx: ['background-color', 'padding-top', 'padding-bottom', '--Gap'], - }, - ], - ]) - } finally { - registration.mockRestore() - } - }) - - it('reads StyleX under the styleResolution a Turbopack plugin is given', () => { - process.env.TURBOPACK = '1' - const resolution = spyOn(wasm, 'setStylexStyleResolution') - try { - DevupUI({}, { stylex: { styleResolution: 'legacy-expand-shorthands' } }) - expect(resolution.mock.calls).toEqual([['legacy-expand-shorthands']]) - } finally { - resolution.mockRestore() - wasm.setStylexStyleResolution(null) - } - }) - - it.each(['1', undefined])( - 'rejects an unknown styleResolution before setup in mode %s', - (mode) => { - if (mode === undefined) delete process.env.TURBOPACK - else process.env.TURBOPACK = mode - expect(() => - Reflect.apply(DevupUI, undefined, [ - {}, - { stylex: { styleResolution: 'last-wins' } }, - ]), - ).toThrow(importGraphModule.StylexConfigError) - expect(startCoordinatorSpy).not.toHaveBeenCalled() - expect(devupUIWebpackPluginSpy).not.toHaveBeenCalled() - }, - ) - - it('rejects a typo before reading an available production handoff', () => { - process.env.TURBOPACK = '1' - setNodeEnv('production') - DevupUI({}, { shorthands: { bgx: ['backgroundColor'] } }) - reloadTurboSetupModuleForTesting() - readFileSyncSpy.mockClear() - const shorthands = { bgx: ['backgroundColour'] } - Object.defineProperty(shorthands, 'toJSON', { - value: () => ({ bgx: ['background-color'] }), - }) - - expect(() => - Reflect.apply(DevupUI, undefined, [{}, { shorthands }]), - ).toThrow(importGraphModule.ShorthandConfigError) - expect(readFileSyncSpy).not.toHaveBeenCalled() - expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) - }) - - it('prewarms and serves actual default Turbo extraction through native state', () => { - // The child starts inside the fixture, as Next does, instead of changing - // its directory after the plugin modules have loaded. - const root = fs.mkdtempSync(join(tmpdir(), 'devup-next-native-')) - const child = spawnSync( - process.execPath, - [ - '-e', - ` - import assert from 'node:assert/strict'; - import { mkdirSync, realpathSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; - import { DevupUI } from ${JSON.stringify(new URL('../plugin.ts', import.meta.url).href)}; - import loader from ${JSON.stringify(new URL('../loader.ts', import.meta.url).href)}; - import { loadWasm, withModuleResolver } from ${JSON.stringify(new URL('../wasm.ts', import.meta.url).href)}; - import { flushCoordinatorWrites, resetCoordinator } from ${JSON.stringify(new URL('../coordinator.ts', import.meta.url).href)}; - import { loadCompiler } from ${JSON.stringify(new URL('../../../plugin-utils/src/index.ts', import.meta.url).href)}; - const native = loadCompiler('native'), wasm = loadCompiler('wasm'); - const primedWasm = loadWasm('wasm'); // Resolve the old loader dependency at its installed location. - const root = ${JSON.stringify(root)}; - assert.equal(realpathSync.native(process.cwd()), realpathSync.native(root)); - try { - mkdirSync(join(root, 'src/app'), { recursive: true }); - writeFileSync(join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { jsx: 'react-jsx' }, include: ['src'] })); - writeFileSync(join(root, 'src/tokens.ts'), "export const tone = 'teal';"); - const source = "import {Box} from '@devup-ui/react'; import {tone} from '../tokens'; export default function Page(){return ;}"; - const resourcePath = join(root, 'src/app/page.tsx'); - writeFileSync(resourcePath, source); - native.resetStateForTesting(); wasm.resetStateForTesting(); - withModuleResolver(primedWasm); // Match normal fixed-cwd supplier resolution after fixture setup. - const before = { native: native.getCss(null, false), wasm: wasm.getCss(null, false) }; - const config = DevupUI({}, { singleCss: true, debug: false }); - const options = config.turbopack.rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'].loaders[0].options; - const code = await new Promise((resolve, reject) => loader.call({ - resourcePath, getOptions: () => options, addDependency() {}, - async: () => (error, code) => error ? reject(error) : resolve(code), - }, Buffer.from(source))); - const after = { native: native.getCss(null, false), wasm: wasm.getCss(null, false) }; - console.info(JSON.stringify({ observed: 'next-default-native', before, after, code })); - assert.equal(typeof code, 'string'); assert(!code.includes(' { - resetCssInit() - const failure = new Error('consumer callback failure', { - cause: new Error('consumer cause'), - }) - let callbacks = 0 - const context = { - resourcePath: 'df/devup-ui/devup-ui.css', - getOptions: () => ({ - watch: false, - defaultFileMap: {}, - defaultClassMap: {}, - defaultSheet: {}, - }), - callback() { - callbacks++ - throw failure - }, - } - expect(() => - Reflect.apply(cssLoader, context, [Buffer.from('ready')]), - ).toThrow(failure) - expect(callbacks).toBe(1) - resetCssInit() - }) - - it('retains original CSS compiler failure and cause in one callback', () => { - resetCssInit() - const cause = new Error('compiler cause') - const failure = new Error('compiler failure', { cause }) - getCssSpy.mockImplementation(() => { - throw failure - }) - const received: (Error | null)[] = [] - Reflect.apply( - cssLoader, - { - resourcePath: 'df/devup-ui/devup-ui.css', - getOptions: () => ({ - watch: true, - sheetFile: 'sheet', - classMapFile: 'classes', - fileMapFile: 'files', - themeFile: 'theme', - }), - callback(error: Error | null) { - received.push(error) - }, - }, - [Buffer.from('ready')], - ) - expect(received).toEqual([failure]) - expect(received[0]?.cause).toBe(cause) - resetCssInit() - }) - - it('caches each selected physical compiler and rejects invalid engines', () => { - setWasmForTesting(undefined) - const native = importGraphModule.loadCompiler('native') - const explicitWasm = importGraphModule.loadCompiler('wasm') - expect(loadWasm()).toBe(native) - expect(loadWasm('native')).toBe(native) - expect(loadWasm('wasm')).toBe(explicitWasm) - expect(loadWasm('wasm')).toBe(explicitWasm) - expect(native).not.toBe(explicitWasm) - expect(() => Reflect.apply(loadWasm, undefined, ['other'])).toThrow( - importGraphModule.InvalidEngineError, - ) - expect(() => Reflect.apply(loadWasm, undefined, [null])).toThrow( - importGraphModule.InvalidEngineError, - ) - }) - - describe('webpack', () => { - it.each(['native', 'wasm'] as const)( - 'retains %s in a deferred Webpack callback', - (engine) => { - delete process.env.TURBOPACK - const options = { engine } - const config = DevupUI({}, options) - options.engine = engine === 'native' ? 'wasm' : 'native' - config.webpack?.(createWebpackConfig(), createWebpackContext()) - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ engine }), - ) - }, - ) - - it.each([ - ['omitted', {}], - ['undefined', { atomHoist: undefined }], - ['OFF', { atomHoist: 0 }], - ['ON', { atomHoist: 2 }], - ['custom', { atomHoist: 3 }], - ])( - 'default regressions: delegates %s atom policy to webpack', - (_label, options) => { - // Given: the webpack path, whose constructor owns the resolved default. - delete process.env.TURBOPACK - const ret = DevupUI({}, { ...options, singleCss: true }) - // When: Next configures its webpack compilation. - ret.webpack?.(createWebpackConfig(), createWebpackContext()) - // Then: explicit zero/thresholds and singleCss reach the real adapter seam. - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - ...options, - engine: 'native', - singleCss: true, - cssDir: resolve('.next/cache', 'devup-ui'), - productionPrewarmFiles: [], - }) - }, - ) - - it('should apply webpack plugin', async () => { - const ret = DevupUI({}) - - ret.webpack!(createWebpackConfig(), createWebpackContext()) - - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - cssDir: resolve('.next/cache', 'devup-ui'), - engine: 'native', - productionPrewarmFiles: [], - }) - }) - - it('hands licenseBanner to the webpack plugin', () => { - DevupUI({}, { licenseBanner: false }).webpack!( - createWebpackConfig(), - createWebpackContext(), - ) - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ licenseBanner: false }), - ) - }) - - it('reads routes from the project root when it holds app or pages', () => { - // Given: a Next app with `app/` at the root and no `src/`. - existsSyncSpy.mockImplementation( - (path: fs.PathLike) => String(path) === resolve('app'), - ) - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(resolve('app/page.tsx'))) - try { - // When - DevupUI({}).webpack!(createWebpackConfig(), createWebpackContext()) - // Then - expect(graphSpy).toHaveBeenCalledWith( - process.cwd(), - resolve('tsconfig.json'), - ) - } finally { - graphSpy.mockRestore() - } - }) - - it('reads routes and places the CSS under the Next project directory', () => { - // Given: `next build apps/web` started from the workspace root. - const dir = resolve('apps', 'web') - existsSyncSpy.mockImplementation( - (path: fs.PathLike) => String(path) === join(dir, 'app'), - ) - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(join(dir, 'app', 'page.tsx'))) - try { - // When - DevupUI({}).webpack!( - createWebpackConfig(), - createWebpackContext({ dir }), - ) - // Then - expect(graphSpy).toHaveBeenCalledWith(dir, join(dir, 'tsconfig.json')) - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ - cssDir: join(dir, '.next', 'cache', 'devup-ui'), - }), - ) - } finally { - graphSpy.mockRestore() - } - }) - - it('places the dev CSS under the Next project directory', () => { - const dir = resolve('apps', 'web') - DevupUI({}).webpack!( - createWebpackConfig(), - createWebpackContext({ dev: true, dir }), - ) - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - cssDir: join(dir, 'df', 'devup-ui_tmpBuildId'), - engine: 'native', - watch: true, - }) - }) - - it('should apply webpack plugin with dev', async () => { - const ret = DevupUI({}) - - ret.webpack!(createWebpackConfig(), createWebpackContext({ dev: true })) - - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - cssDir: resolve('df', 'devup-ui_tmpBuildId'), - engine: 'native', - watch: true, - }) - }) - - it('should apply webpack plugin with config', async () => { - const ret = DevupUI( - {}, - { - package: 'new-package', - }, - ) - - ret.webpack!(createWebpackConfig(), createWebpackContext()) - - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - package: 'new-package', - engine: 'native', - cssDir: resolve('.next/cache', 'devup-ui'), - productionPrewarmFiles: [], - }) - }) - - it('should apply webpack plugin with webpack obj', async () => { - const webpack = mock() - const ret = DevupUI( - { - webpack, - }, - { - package: 'new-package', - }, - ) - - ret.webpack!(createWebpackConfig(), createWebpackContext()) - - expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ - package: 'new-package', - engine: 'native', - cssDir: resolve('.next/cache', 'devup-ui'), - productionPrewarmFiles: [], - }) - expect(webpack).toHaveBeenCalled() - }) - }) - describe('turbo', () => { - it('reuses production setup across Next config module reloads', () => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_PROFILE = '1' - getDefaultThemeSpy.mockReturnValue('dark') - const filename = resolve('src/app/page.tsx') - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(filename)) - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx']) - const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) - const normalizeSpy = spyOn(importGraphModule, 'normalizeShorthands') - const handoffFile = join('df', 'setup.bin') - let handoff: Parameters[1] | undefined - writeFileSyncSpy.mockImplementation((path, data) => { - if (String(path) === handoffFile) handoff = data - }) - readFileSyncSpy.mockImplementation((path) => { - if (String(path) === handoffFile && handoff !== undefined) { - return handoff as never - } - return '{}' as never - }) - unlinkSyncSpy.mockImplementation((path) => { - if (String(path) === handoffFile) throw new Error('cleanup failed') - }) - - try { - const first = DevupUI( - {}, - { singleCss: true, shorthands: { bgx: ['backgroundColor'] } }, - ) - reloadTurboSetupModuleForTesting() - const second = DevupUI( - { env: { EXISTING: 'value' } }, - { singleCss: true, shorthands: { bgx: ['background-color'] } }, - ) - - expect(second.turbopack?.rules).toEqual(first.turbopack?.rules) - expect(second.env).toEqual({ - DEVUP_UI_DEFAULT_THEME: 'dark', - EXISTING: 'value', - }) - expect(graphSpy).toHaveBeenCalledTimes(1) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(1) - expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) - expect(normalizeSpy).toHaveBeenCalledTimes(2) - expect(unlinkSyncSpy).toHaveBeenCalledWith(handoffFile) - expect(profileSpy).toHaveBeenCalledWith( - expect.stringContaining('"cacheHit":true'), - ) - } finally { - normalizeSpy.mockRestore() - profileSpy.mockRestore() - compiledSpy.mockRestore() - graphSpy.mockRestore() - } - }) - it.each([true, false])( - 'availability: reuses production setup and warns once across config reloads (singleCss %s)', - (singleCss) => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_PROFILE = '1' - getDefaultThemeSpy.mockReturnValue('dark') - const filename = resolve('src/app/page.tsx') - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(filename)) - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx']) - const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) - const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) - const handoffFile = join('df', 'setup.bin') - let handoff: Parameters[1] | undefined - writeFileSyncSpy.mockImplementation((path, data) => { - if (String(path) === handoffFile) handoff = data - }) - readFileSyncSpy.mockImplementation((path) => { - if (String(path) === handoffFile && handoff !== undefined) { - return handoff as never - } - return '{}' as never - }) - unlinkSyncSpy.mockImplementation((path) => { - if (String(path) === handoffFile) throw new Error('cleanup failed') - }) - - try { - const first = DevupUI({}, { singleCss, atomHoist: 2 }) - reloadTurboSetupModuleForTesting() - const second = DevupUI( - { env: { EXISTING: 'value' } }, - { singleCss, atomHoist: 2 }, - ) - - expect(second.turbopack?.rules).toEqual(first.turbopack?.rules) - expect(second.env).toEqual({ - DEVUP_UI_DEFAULT_THEME: 'dark', - EXISTING: 'value', - }) - expect(graphSpy).toHaveBeenCalledTimes(1) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(1) - expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) - expect(warningSpy).toHaveBeenCalledTimes(singleCss ? 0 : 1) - expect(unlinkSyncSpy).toHaveBeenCalledWith(handoffFile) - expect(profileSpy).toHaveBeenCalledWith( - expect.stringContaining('"cacheHit":true'), - ) - } finally { - warningSpy.mockRestore() - profileSpy.mockRestore() - compiledSpy.mockRestore() - graphSpy.mockRestore() - } - }, - ) - - it('falls back when a production setup handoff is not reusable', () => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - const filename = resolve('src/app/page.tsx') - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(filename)) - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx']) - const handoffFile = join('df', 'setup.bin') - let failHandoffWrite = false - let handoff: Parameters[1] | undefined - writeFileSyncSpy.mockImplementation((path, data) => { - if (String(path) !== handoffFile) return - if (failHandoffWrite) throw new Error('write failed') - handoff = data - }) - readFileSyncSpy.mockImplementation((path) => { - if (String(path) === handoffFile && handoff !== undefined) { - return handoff as never - } - return '{}' as never - }) - - try { - DevupUI({}) - // The same module instance must not consume its own handoff. - DevupUI({}) - reloadTurboSetupModuleForTesting() - handoff = Buffer.from('invalid handoff') - failHandoffWrite = true - - // A corrupt read and a failed replacement write both fall back to the - // complete setup without leaking a token into another config load. - expect(() => DevupUI({})).not.toThrow() - expect(graphSpy).toHaveBeenCalledTimes(3) - expect(process.env.DEVUP_UI_TURBO_SETUP_TOKEN).toBeUndefined() - } finally { - compiledSpy.mockRestore() - graphSpy.mockRestore() - } - }) - - it('compiles every source extension the import graph lists under Turbopack', () => { - process.env.TURBOPACK = '1' - const rules = Object.keys(DevupUI({}).turbopack?.rules ?? {}) - const glob = rules.find((rule) => rule.startsWith('*.{')) - expect(glob?.slice(3, -1).split(',').sort()).toEqual( - importGraphModule.SOURCE_EXTENSIONS.map((extension) => - extension.slice(1), - ).sort(), - ) - }) - - it('should apply turbo config', async () => { - process.env.TURBOPACK = '1' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - const ret = DevupUI({}) - - expect(ret).toEqual({ - turbopack: { - rules: { - './df/devup-ui/*.css': [ - { - loader: '@devup-ui/next-plugin/css-loader', - options: { - engine: 'native', - watch: false, - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - theme: {}, - defaultClassMap: {}, - defaultFileMap: {}, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - }, - }, - ], - '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { - loaders: [ - { - loader: '@devup-ui/next-plugin/loader', - options: { - engine: 'native', - package: '@devup-ui/react', - cssDir: resolve('df', 'devup-ui'), - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - watch: false, - singleCss: false, - theme: {}, - defaultClassMap: {}, - defaultFileMap: {}, - importAliases: { - '@emotion/react': null, - '@emotion/styled': 'styled', - '@emotion/css': null, - '@vanilla-extract/css': null, - '@vanilla-extract/css-utils': null, - 'styled-components': 'styled', - }, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - }, - }, - ], - condition: { - not: { - path: new RegExp( - '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', - ), - }, - }, - }, - }, - }, - }) - }) - it('should apply turbo config with create df', async () => { - process.env.TURBOPACK = '1' - existsSyncSpy.mockReturnValue(false) - mkdirSyncSpy.mockReturnValue('') - writeFileSyncSpy.mockReturnValue(undefined) - const ret = DevupUI({}) - - expect(ret).toEqual({ - turbopack: { - rules: { - './df/devup-ui/*.css': [ - { - loader: '@devup-ui/next-plugin/css-loader', - options: { - engine: 'native', - watch: false, - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - theme: {}, - defaultClassMap: {}, - defaultFileMap: {}, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - }, - }, - ], - '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { - condition: { - not: { - path: new RegExp( - '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', - ), - }, - }, - loaders: [ - { - loader: '@devup-ui/next-plugin/loader', - options: { - engine: 'native', - package: '@devup-ui/react', - cssDir: resolve('df', 'devup-ui'), - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - importAliases: { - '@emotion/react': null, - '@emotion/styled': 'styled', - '@emotion/css': null, - '@vanilla-extract/css': null, - '@vanilla-extract/css-utils': null, - 'styled-components': 'styled', - }, - watch: false, - singleCss: false, - theme: {}, - defaultClassMap: {}, - defaultFileMap: {}, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - }, - }, - ], - }, - }, - }, - }) - expect(mkdirSyncSpy).toHaveBeenCalledWith('df', { - recursive: true, - }) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join('df', '.gitignore'), - '*', - ) - }) - it('should apply turbo config with exists df and devup.json', async () => { - process.env.TURBOPACK = '1' - existsSyncSpy.mockReturnValue(true) - readFileSyncSpy.mockReturnValue(JSON.stringify({ theme: 'theme' })) - mkdirSyncSpy.mockReturnValue('') - writeFileSyncSpy.mockReturnValue(undefined) - const ret = DevupUI({}) - - expect(ret).toEqual({ - turbopack: { - rules: { - './df/devup-ui/*.css': [ - { - loader: '@devup-ui/next-plugin/css-loader', - options: { - engine: 'native', - watch: false, - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - theme: 'theme', - defaultClassMap: {}, - defaultFileMap: {}, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - }, - }, - ], - '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { - condition: { - not: { - path: new RegExp( - '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', - ), - }, - }, - loaders: [ - { - loader: '@devup-ui/next-plugin/loader', - options: { - engine: 'native', - package: '@devup-ui/react', - cssDir: resolve('df', 'devup-ui'), - coordinatorPortFile: join('df', 'coordinator.port'), - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - watch: false, - singleCss: false, - theme: 'theme', - defaultClassMap: {}, - defaultFileMap: {}, - importAliases: { - '@emotion/react': null, - '@emotion/styled': 'styled', - '@emotion/css': null, - '@vanilla-extract/css': null, - '@vanilla-extract/css-utils': null, - 'styled-components': 'styled', - }, - defaultSheet: { - css: {}, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - }, - themeFile: 'devup.json', - themeFiles: [resolve('devup.json')], - }, - }, - ], - }, - }, - }, - }) - // mkdirSync is NOT called when existsSync returns true - expect(mkdirSyncSpy).not.toHaveBeenCalled() - // gitignore is also NOT written when it exists - expect(writeFileSyncSpy).not.toHaveBeenCalledWith( - join('df', '.gitignore'), - '*', - ) - }) - it('should start coordinator even in production mode', () => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - const ret = DevupUI({}) - expect(ret).toEqual({ - turbopack: { - rules: expect.any(Object), - }, - }) - expect(startCoordinatorSpy).toHaveBeenCalledWith({ - distDir: 'df', - wasm: coordinatorModule.openCoordinatorCompiler('df', wasm), - package: '@devup-ui/react', - cssDir: resolve('df', 'devup-ui'), - singleCss: false, - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - importAliases: { - '@emotion/react': null, - '@emotion/styled': 'styled', - '@emotion/css': null, - '@vanilla-extract/css': null, - '@vanilla-extract/css-utils': null, - 'styled-components': 'styled', - }, - coordinatorPortFile: join('df', 'coordinator.port'), - canonicalMap: expect.any(Object), - expectedBaseFiles: expect.any(Array), - prewarmedFiles: expect.any(Array), - prewarmedOutputs: expect.any(Map), - sourceMap: false, - }) - }) - it('extracts vanilla-extract modules as written', () => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - const filename = resolve('src/styles.css.ts') - const source = `import { style } from '@vanilla-extract/css' -export const box = style({ color: 'red' })` - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue(createSingleFileGraph(filename)) - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/styles.css.ts']) - readFileSyncSpy.mockImplementation((path: fs.PathOrFileDescriptor) => - String(path).endsWith('styles.css.ts') ? source : '{}', - ) - - try { - DevupUI({}) - - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( - 'src/styles.css.ts', - source, - '@devup-ui/react', - expect.any(String), - false, - false, - true, - expect.anything(), - ) - } finally { - graphSpy.mockRestore() - compiledSpy.mockRestore() - } - }) - it('keeps source maps when Next production browser source maps are enabled', () => { - setNodeEnv('production') - process.env.TURBOPACK = '1' - - DevupUI({ productionBrowserSourceMaps: true }) - - expect(startCoordinatorSpy).toHaveBeenCalledWith( - expect.objectContaining({ sourceMap: true }), - ) - }) - it('keeps configuring Turbopack when the import graph cannot be read', () => { - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_PROFILE = '1' - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockImplementation(() => { - throw new Error('unreadable') - }) - const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) - const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) - try { - expect(DevupUI({}).turbopack?.rules).toBeDefined() - expect(profileSpy).toHaveBeenCalledWith( - expect.stringContaining('"failed":true'), - ) - expect(warnSpy).toHaveBeenCalledWith( - '[devup-ui] Turbopack import graph failed: unreadable. Classes are not merged across files only one module imports, and the production stylesheet waits for extraction to go quiet instead of for every compiled file.', - ) - } finally { - profileSpy.mockRestore() - warnSpy.mockRestore() - graphSpy.mockRestore() - } - }) - it.each([ - [{}, false], - [{ debug: true }, true], - ])('sets debug class names from %j', (options, debug) => { - process.env.TURBOPACK = '1' - const setDebugSpy = spyOn(wasm, 'setDebug').mockReturnValue(undefined) - try { - DevupUI({}, options) - expect(setDebugSpy).toHaveBeenCalledWith(debug) - } finally { - setDebugSpy.mockRestore() - } - }) - it('should create theme.d.ts file', async () => { - process.env.TURBOPACK = '1' - existsSyncSpy.mockReturnValue(true) - getThemeInterfaceSpy.mockReturnValue('interface code') - readFileSyncSpy.mockReturnValue(JSON.stringify({ theme: 'theme' })) - mkdirSyncSpy.mockReturnValue('') - writeFileSyncSpy.mockReturnValue(undefined) - DevupUI({}) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join('df', 'theme.d.ts'), - 'interface code', - ) - // mkdirSync is NOT called when existsSync returns true - expect(mkdirSyncSpy).not.toHaveBeenCalled() - }) - it('should set DEVUP_UI_DEFAULT_THEME when getDefaultTheme returns a value', async () => { - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_DEFAULT_THEME = '' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - getDefaultThemeSpy.mockReturnValue('dark') - const config: any = {} - const ret = DevupUI(config) - - expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('dark') - expect(ret.env).toEqual({ - DEVUP_UI_DEFAULT_THEME: 'dark', - }) - expect(config.env).toEqual({ - DEVUP_UI_DEFAULT_THEME: 'dark', - }) - }) - it('should not set DEVUP_UI_DEFAULT_THEME when getDefaultTheme returns undefined', async () => { - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_DEFAULT_THEME = '' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - getDefaultThemeSpy.mockReturnValue(undefined) - const config: any = {} - const ret = DevupUI(config) - - expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('') - expect(ret.env).toBeUndefined() - expect(config.env).toBeUndefined() - }) - it('should set DEVUP_UI_DEFAULT_THEME and preserve existing env vars', async () => { - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_DEFAULT_THEME = '' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - getDefaultThemeSpy.mockReturnValue('light') - const config: any = { - env: { - CUSTOM_VAR: 'value', - }, - } - const ret = DevupUI(config) - - expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('light') - expect(ret.env).toEqual({ - CUSTOM_VAR: 'value', - DEVUP_UI_DEFAULT_THEME: 'light', - }) - expect(config.env).toEqual({ - CUSTOM_VAR: 'value', - DEVUP_UI_DEFAULT_THEME: 'light', - }) - }) - it('should call setPrefix when prefix option is provided', async () => { - process.env.TURBOPACK = '1' - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - DevupUI({}, { prefix: 'my-prefix' }) - expect(setPrefixSpy).toHaveBeenCalledWith('my-prefix') - }) - it.each([ - [undefined, true], - [true, true], - [false, false], - ] as const)( - 'sets the license banner from licenseBanner=%s under Turbopack', - (licenseBanner, expected) => { - process.env.TURBOPACK = '1' - using setLicenseBanner = spyOn( - wasm, - 'setLicenseBanner', - ).mockReturnValue(undefined) - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - DevupUI({}, { licenseBanner }) - expect(setLicenseBanner).toHaveBeenCalledWith(expected) - }, - ) - it('numbers the files the scan finds, and survives a failing scan', () => { - process.env.TURBOPACK = '1' - const collectSpy = spyOn(importGraphModule, 'collectNumberedFiles') - const seedSpy = spyOn(wasm, 'seedFileMap').mockReturnValue(undefined) - try { - collectSpy.mockImplementation((options: any) => { - expect(options.roots).toEqual( - ['src', 'app', 'pages'].map((dir) => resolve(dir)), - ) - expect(options.toId(resolve('src', 'a.tsx'))).toBe('src/a.tsx') - return ['src/a.tsx'] - }) - DevupUI({}, { include: ['@acme/ui'] }) - expect(seedSpy).toHaveBeenCalledWith(['src/a.tsx']) - expect(collectSpy.mock.calls[0][0]).toMatchObject({ - include: ['@acme/ui'], - }) - collectSpy.mockImplementation(() => { - throw 'scan boom' - }) - const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) - try { - DevupUI({}, {}) - expect(warnSpy).toHaveBeenCalledWith( - '[devup-ui] Turbopack file numbering failed: scan boom. Stylesheet file numbers follow the order Turbopack compiles files in, so they can differ between builds of the same source.', - ) - } finally { - warnSpy.mockRestore() - } - } finally { - collectSpy.mockRestore() - seedSpy.mockRestore() - } - }) - it('reserves shared class slots in path order before next dev extracts', () => { - process.env.TURBOPACK = '1' - const reserve = mock() - const reservationSpy = spyOn( - importGraphModule, - 'createSharedSlotReservation', - ).mockReturnValue({ - dependencies: [], - packageManifests: [], - invalidate: mock(), - reserve, - }) - try { - // One-shot builds take their order from the sorted prewarm instead. - DevupUI({}) - expect(reservationSpy).not.toHaveBeenCalled() - - setNodeEnv('development') - DevupUI({}, { include: ['@acme/ui'], singleCss: true }) - // Into the app's own engine session, never the shared engine. - expect(reservationSpy).toHaveBeenCalledWith( - coordinatorModule.openCoordinatorCompiler('df', wasm), - ) - const [discovery, options] = reserve.mock.calls[0] as Parameters< - ReturnType< - typeof importGraphModule.createSharedSlotReservation - >['reserve'] - > - expect(discovery).toMatchObject({ - roots: ['src', 'app', 'pages'].map((dir) => resolve(dir)), - include: ['@acme/ui'], - cwd: process.cwd(), - tsconfigPath: resolve('tsconfig.json'), - package: '@devup-ui/react', - }) - // The coordinator's own filename and CSS directory for each file. - expect(discovery.toId?.(resolve('src', 'a.tsx'))).toBe('src/a.tsx') - expect(options).toMatchObject({ - singleCss: true, - importMainCssInCode: false, - importMainCssInCss: true, - }) - expect( - options.cssDir({ - filename: 'src/app/page.tsx', - physicalPath: resolve('src', 'app', 'page.tsx'), - code: '', - }), - ).toBe('./../../df/devup-ui') - - // A failing reservation leaves extraction in arrival order. - reserve.mockImplementation(() => { - throw new Error('reserve boom') - }) - const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) - try { - expect(() => DevupUI({})).not.toThrow() - expect(warnSpy).toHaveBeenCalledWith( - '[devup-ui] Turbopack shared class-slot reservation failed: reserve boom. Classes several files share take their names in the order `next dev` extracts them, so they can differ between dev sessions.', - ) - } finally { - warnSpy.mockRestore() - } - } finally { - reservationSpy.mockRestore() - } - }) - describe('restoreSessionState', () => { - const files = ['sheet.json', 'classMap.json', 'fileMap.json'] as const - const engine = () => ({ - importSheet: mock(), - importClassMap: mock(), - importFileMap: mock(), - resetBuildState: mock(), - }) - - it('imports nothing unless every file reads', () => { - readFileSyncSpy.mockImplementation((path: string) => { - if (path === 'fileMap.json') throw new Error('ENOENT') - return '{}' - }) - const restored = engine() - restoreSessionState(restored, files) - expect(restored.importSheet).not.toHaveBeenCalled() - expect(restored.importClassMap).not.toHaveBeenCalled() - expect(restored.importFileMap).not.toHaveBeenCalled() - }) - - it('imports nothing when one file is corrupt', () => { - readFileSyncSpy.mockImplementation((path: string) => - path === 'classMap.json' ? '{"a":' : '{}', - ) - const restored = engine() - restoreSessionState(restored, files) - expect(restored.importSheet).not.toHaveBeenCalled() - }) - - it('drops a state that does not import', () => { - readFileSyncSpy.mockImplementation((path: string) => - JSON.stringify({ path }), - ) - const restored = engine() - restored.importClassMap.mockImplementation(() => { - throw new Error('older release') - }) - restoreSessionState(restored, files) - expect(restored.importSheet).toHaveBeenCalledWith({ - path: 'sheet.json', - }) - expect(restored.importFileMap).not.toHaveBeenCalled() - expect(restored.resetBuildState).toHaveBeenCalledTimes(1) - }) - }) - it('should import previous session state on restart', () => { - process.env.TURBOPACK = '1' - existsSyncSpy - .mockReturnValueOnce(true) // distDir - .mockReturnValueOnce(true) // cssDir - .mockReturnValueOnce(true) // gitignoreFile - .mockReturnValueOnce(false) // devupFile in loadDevupConfigSync - - // Simulate previous session state files on disk - const prevSheet = { - css: { a: 'color:red' }, - font_faces: {}, - global_css_files: [], - imports: {}, - keyframes: {}, - properties: {}, - } - const prevClassMap = { a: 0 } - const prevFileMap = { 'src/App.tsx': 0 } - - const files: Record = { - [join('df', 'sheet.json')]: JSON.stringify(prevSheet), - [join('df', 'classMap.json')]: JSON.stringify(prevClassMap), - [join('df', 'fileMap.json')]: JSON.stringify(prevFileMap), - } - readFileSyncSpy.mockImplementation((path: string) => files[path] ?? '{}') - - DevupUI({}) - - // Verify previous state was imported before registerTheme - expect(importSheetSpy).toHaveBeenCalledWith(prevSheet) - expect(importClassMapSpy).toHaveBeenCalledWith(prevClassMap) - expect(importFileMapSpy).toHaveBeenCalledWith(prevFileMap) - expect(registerThemeSpy).toHaveBeenCalledWith({}) - - // Verify stale port file was deleted before starting coordinator - expect(unlinkSyncSpy).toHaveBeenCalledWith(join('df', 'coordinator.port')) - }) - it('writes its own state next to another live process on the same distDir', () => { - process.env.TURBOPACK = '1' - const stateDir = join('df', `state.${process.pid}`) - const portSpy = spyOn( - coordinatorPortModule, - 'resolveCoordinatorPortFile', - ).mockReturnValue(join('df', `coordinator.${process.pid}.port`)) - const staleSpy = spyOn( - coordinatorPortModule, - 'removeStaleStateDirs', - ).mockReturnValue(undefined) - const prevSheet = { css: { a: 'color:red' } } - readFileSyncSpy.mockImplementation((path: string) => - path === join('df', 'sheet.json') ? JSON.stringify(prevSheet) : '{}', - ) - try { - const config = DevupUI({}) - - expect(staleSpy).toHaveBeenCalledWith('df') - expect(mkdirSyncSpy).toHaveBeenCalledWith(stateDir, { recursive: true }) - // It still restores what the shared state holds... - expect(importSheetSpy).toHaveBeenCalledWith(prevSheet) - // ...but writes only its own files. - expect(startCoordinatorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - coordinatorPortFile: join('df', `coordinator.${process.pid}.port`), - sheetFile: join(stateDir, 'sheet.json'), - classMapFile: join(stateDir, 'classMap.json'), - fileMapFile: join(stateDir, 'fileMap.json'), - }), - ) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join(stateDir, 'canonicalMap.json'), - expect.any(String), - ) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join(stateDir, 'setup.bin'), - expect.anything(), - ) - const rule = config.turbopack?.rules?.[ - '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}' - ] as { - loaders: { options: { sheetFile: string } }[] - } - expect(rule.loaders[0].options.sheetFile).toBe( - join(stateDir, 'sheet.json'), - ) - } finally { - portSpy.mockRestore() - staleSpy.mockRestore() - } - }) - it('should handle missing state files gracefully on first run', () => { - process.env.TURBOPACK = '1' - existsSyncSpy - .mockReturnValueOnce(false) // distDir — doesn't exist - .mockReturnValueOnce(false) // cssDir - .mockReturnValueOnce(false) // gitignoreFile - .mockReturnValueOnce(false) // devupFile - - // readFileSync throws for state files (they don't exist) - readFileSyncSpy.mockImplementation((path: string) => { - throw new Error(`ENOENT: no such file or directory, open '${path}'`) - }) - - // Should not throw — try-catch handles missing files - DevupUI({}) - - // importSheet should NOT have been called (readFileSync threw) - expect(importSheetSpy).not.toHaveBeenCalled() - expect(importClassMapSpy).not.toHaveBeenCalled() - expect(importFileMapSpy).not.toHaveBeenCalled() - - // registerTheme should still be called with empty theme - expect(registerThemeSpy).toHaveBeenCalledWith({}) - }) - it('should start coordinator in development mode', async () => { - process.env.TURBOPACK = '1' - setNodeEnv('development') - existsSyncSpy - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(true) - .mockReturnValueOnce(false) - writeFileSyncSpy.mockReturnValue(undefined) - - const closeMock = mock() as () => void - startCoordinatorSpy.mockReturnValue({ close: closeMock }) - - const exitHandlers: (() => void)[] = [] - const processOnSpy = spyOn(process, 'on').mockImplementation( - (event: string, handler: (...args: unknown[]) => void) => { - if (event === 'exit') exitHandlers.push(handler as () => void) - return process - }, - ) - - try { - DevupUI({}) - - // Verify coordinator was started with correct options - expect(startCoordinatorSpy).toHaveBeenCalledWith({ - distDir: 'df', - wasm: coordinatorModule.openCoordinatorCompiler('df', wasm), - package: '@devup-ui/react', - cssDir: resolve('df', 'devup-ui'), - singleCss: false, - sheetFile: join('df', 'sheet.json'), - classMapFile: join('df', 'classMap.json'), - fileMapFile: join('df', 'fileMap.json'), - importAliases: { - '@emotion/react': null, - '@emotion/styled': 'styled', - '@emotion/css': null, - '@vanilla-extract/css': null, - '@vanilla-extract/css-utils': null, - 'styled-components': 'styled', - }, - coordinatorPortFile: join('df', 'coordinator.port'), - canonicalMap: expect.any(Object), - expectedBaseFiles: expect.any(Array), - prewarmedFiles: [], - prewarmedOutputs: expect.any(Map), - sourceMap: true, - theme: { - files: [resolve('devup.json')], - reload: expect.any(Function), - }, - }) - // The coordinator registers an edited theme through the same path. - const { theme } = startCoordinatorSpy.mock.calls[0]![0] as { - theme: { reload: () => string[] } - } - registerThemeSpy.mockClear() - expect(theme.reload()).toEqual([resolve('devup.json')]) - expect(registerThemeSpy).toHaveBeenCalledWith({}) - expect(codeExtractSpy).not.toHaveBeenCalled() - expect(codeExtractWithoutSourceMapSpy).not.toHaveBeenCalled() - - // Verify initial CSS file is written - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join(resolve('df', 'devup-ui'), 'devup-ui.css'), - '', - ) - - // Verify exit handler was registered and calls coordinator.close() - expect(exitHandlers.length).toBeGreaterThan(0) - exitHandlers[0]!() - expect(closeMock).toHaveBeenCalledTimes(1) - - // Verify --inspect-brk env vars are NOT set - expect(process.env.TURBOPACK_DEBUG_JS).toBeUndefined() - expect(process.env.NODE_OPTIONS ?? '').not.toContain('--inspect-brk') - } finally { - processOnSpy.mockRestore() - } - }) - - it('registers the Tailwind CSS theme and watches its files', () => { - process.env.TURBOPACK = '1' - const tailwindSpy = spyOn( - importGraphModule, - 'findTailwindCss', - ).mockReturnValue({ - file: resolve('app.css'), - files: [resolve('app.css'), resolve('tokens.css')], - css: '@import "tailwindcss";', - }) - try { - const config = DevupUI({}) - - expect(registerThemeSpy).toHaveBeenCalledWith({ - tailwindCss: '@import "tailwindcss";', - }) - const rule = config.turbopack?.rules?.[ - '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}' - ] as { - loaders: { options: { themeFiles: string[] } }[] - } - expect(rule.loaders[0].options.themeFiles).toEqual([ - resolve('devup.json'), - resolve('app.css'), - resolve('tokens.css'), - ]) - } finally { - tailwindSpy.mockRestore() - } - }) - - it('hands the coordinator the full compiled-file set, not the static-only route map', () => { - process.env.TURBOPACK = '1' - process.env.DEVUP_UI_PROFILE = '1' - const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) - // The base sheet must wait for lazily-loaded modules too, so - // expectedBaseFiles comes from computeCompiledFiles (static + dynamic - // edges) rather than computeFileRoutes (static edges only). Using the - // route map here served the sheet before any dynamic() module extracted. - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx', 'src/lazy/panel.tsx']) - const routesSpy = spyOn( - importGraphModule, - 'computeFileRoutes', - ).mockReturnValue({ 'src/app/page.tsx': [0] }) - const events: string[] = [] - codeExtractWithoutSourceMapSpy.mockImplementation( - (filename: string, contents: string) => { - events.push(`extract:${filename}`) - return Object.assign(createCodeExtractResult(contents), { - dependencies: [`${filename}.tokens.ts`], - }) - }, - ) - startCoordinatorSpy.mockImplementation(() => { - events.push('startCoordinator') - return { close: mock() as () => void } - }) - try { - DevupUI({}, { atomHoist: 0 }) - - expect(startCoordinatorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - expectedBaseFiles: ['src/app/page.tsx', 'src/lazy/panel.tsx'], - prewarmedFiles: ['src/app/page.tsx', 'src/lazy/panel.tsx'], - }), - ) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( - 'src/app/page.tsx', - '{}', - '@devup-ui/react', - expect.any(String), - false, - false, - true, - expect.anything(), - ) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( - 'src/lazy/panel.tsx', - '{}', - '@devup-ui/react', - expect.any(String), - false, - false, - true, - expect.anything(), - ) - expect(events).toEqual([ - 'extract:src/app/page.tsx', - 'extract:src/lazy/panel.tsx', - 'startCoordinator', - ]) - const coordinatorOptions = startCoordinatorSpy.mock.calls[0]?.[0] - expect(coordinatorOptions?.prewarmedOutputs).toEqual( - new Map([ - [ - 'src/app/page.tsx', - expect.objectContaining({ - code: '{}', - source: '{}', - dependencies: ['src/app/page.tsx.tokens.ts'], - }), - ], - [ - 'src/lazy/panel.tsx', - expect.objectContaining({ - code: '{}', - source: '{}', - dependencies: ['src/lazy/panel.tsx.tokens.ts'], - }), - ], - ]), - ) - const profiles: Record[] = profileSpy.mock.calls - .map(([value]) => value) - .filter( - (value): value is string => - typeof value === 'string' && - value.startsWith('[devup-ui:profile] '), - ) - .map((value) => JSON.parse(value.slice('[devup-ui:profile] '.length))) - const prewarmProfile = profiles.find( - ({ phase }) => phase === 'next.prewarm', - ) - expect(prewarmProfile).toMatchObject({ - collectMs: expect.any(Number), - extractMs: expect.any(Number), - files: 2, - phase: 'next.prewarm', - readMs: expect.any(Number), - sourceBytes: Buffer.byteLength('{}') * 2, - }) - expect(profiles).toEqual( - expect.arrayContaining([ - expect.objectContaining({ phase: 'next.initialCss' }), - expect.objectContaining({ phase: 'next.stateSnapshot' }), - expect.objectContaining({ phase: 'next.setup' }), - ]), - ) - // the static-only route map is not consulted outside atom-hoist mode - expect(routesSpy).not.toHaveBeenCalled() - } finally { - profileSpy.mockRestore() - compiledSpy.mockRestore() - routesSpy.mockRestore() - } - }) - - it('prewarms source candidates hidden from the route closure', () => { - process.env.TURBOPACK = '1' - const page = resolve('src/app/page.tsx') - const templateTarget = resolve('src/demos/template-target.tsx') - const graphSpy = spyOn( - importGraphModule, - 'buildStaticImportGraph', - ).mockReturnValue({ - files: [page, templateTarget], - fileSet: new Set([page, templateTarget]), - staticImports: new Map([ - [page, new Set()], - [templateTarget, new Set()], - ]), - staticImporters: new Map([ - [page, new Set()], - [templateTarget, new Set()], - ]), - dynamicTargets: new Set(), - dynamicImports: new Map([ - [page, new Set()], - [templateTarget, new Set()], - ]), - externalImports: new Map([ - [page, new Set()], - [templateTarget, new Set()], - ]), - }) - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx']) - try { - DevupUI({}) - - expect(startCoordinatorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - expectedBaseFiles: ['src/app/page.tsx'], - prewarmedFiles: [ - 'src/app/page.tsx', - 'src/demos/template-target.tsx', - ], - }), - ) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) - } finally { - graphSpy.mockRestore() - compiledSpy.mockRestore() - } - }) - - it('prewarms the same complete file set in singleCss mode', () => { - process.env.TURBOPACK = '1' - const compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/page.tsx', 'src/app/card.tsx']) - try { - DevupUI({}, { singleCss: true }) - - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( - 'src/app/card.tsx', - '{}', - '@devup-ui/react', - expect.any(String), - true, - false, - true, - expect.anything(), - ) - expect(startCoordinatorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - singleCss: true, - prewarmedFiles: ['src/app/card.tsx', 'src/app/page.tsx'], - }), - ) - } finally { - compiledSpy.mockRestore() - } - }) - - it('does not enable atom hoisting when atomHoist is explicitly zero', () => { - process.env.TURBOPACK = '1' - const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( - undefined, - ) - const importFileRoutesSpy = spyOn( - wasm, - 'importFileRoutes', - ).mockReturnValue(undefined) - const importCanonicalMapSpy = spyOn( - wasm, - 'importCanonicalMap', - ).mockReturnValue(undefined) - try { - DevupUI({}, { atomHoist: 0 }) - expect(setAtomHoistSpy).not.toHaveBeenCalled() - expect(importFileRoutesSpy).not.toHaveBeenCalled() - // single-importer collapse still runs (it is the always-on default) - expect(importCanonicalMapSpy).toHaveBeenCalled() - } finally { - setAtomHoistSpy.mockRestore() - importFileRoutesSpy.mockRestore() - importCanonicalMapSpy.mockRestore() - } - }) - - describe('default regressions', () => { - let canonicalSpy: ReturnType - let routesSpy: ReturnType - let compiledSpy: ReturnType - let importRoutesSpy: ReturnType - let thresholdSpy: ReturnType - - beforeEach(() => { - process.env.TURBOPACK = '1' - setNodeEnv('production') - canonicalSpy = spyOn( - importGraphModule, - 'buildCanonicalMap', - ).mockReturnValue({}) - routesSpy = spyOn( - importGraphModule, - 'computeFileRoutes', - ).mockReturnValue({ - 'src/app/layout.tsx': [0, 1], - 'src/app/a/page.tsx': [0], - 'src/app/b/page.tsx': [1], - }) - compiledSpy = spyOn( - importGraphModule, - 'computeCompiledFiles', - ).mockReturnValue(['src/app/a/page.tsx', 'src/app/b/page.tsx']) - importRoutesSpy = spyOn(wasm, 'importFileRoutes').mockReturnValue( - undefined, - ) - thresholdSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue(undefined) - }) - - afterEach(() => { - canonicalSpy.mockRestore() - routesSpy.mockRestore() - compiledSpy.mockRestore() - importRoutesSpy.mockRestore() - thresholdSpy.mockRestore() - }) - - it.each([undefined, 0, -1, NaN, Infinity, -Infinity, 0.5, 1, 2, 3])( - 'availability: keeps per-file mode for request %s', - (atomHoist) => { - // Given: multi-route reach and legacy whole-file hoisting are available. - process.env.DEVUP_HOIST_V = '3' - const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) - try { - // When: Turbopack receives the numeric request. - DevupUI({}, { atomHoist }) - // Then: only explicit finite positive requests warn; none install atoms. - expect(routesSpy).not.toHaveBeenCalled() - expect(importRoutesSpy).not.toHaveBeenCalled() - expect(thresholdSpy).not.toHaveBeenCalled() - expect(canonicalSpy).toHaveBeenCalledWith( - expect.objectContaining({ hoistV: 3 }), - ) - expect(warningSpy).toHaveBeenCalledTimes( - atomHoist !== undefined && - Number.isFinite(atomHoist) && - atomHoist > 0 - ? 1 - : 0, - ) - } finally { - warningSpy.mockRestore() - } - }, - ) - - it.each([ - ['omitted', {}], - ['undefined', { atomHoist: undefined }], - ])( - 'keeps omitted atomHoist %s silent without consulting route reach', - (_label, options) => { - const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) - try { - DevupUI({}, options) - expect(routesSpy).not.toHaveBeenCalled() - expect(importRoutesSpy).not.toHaveBeenCalled() - expect(thresholdSpy).not.toHaveBeenCalled() - expect(warningSpy).not.toHaveBeenCalled() - } finally { - warningSpy.mockRestore() - } - }, - ) - - it.each([0, -1, NaN, Infinity, -Infinity])( - 'keeps legacy OFF for atomHoist %s', - (atomHoist) => { - // Given: a valid multi-route fixture, so fallback cannot hide enabling. - // When: an explicitly disabled numeric option is supplied. - DevupUI({}, { atomHoist }) - // Then: collapse remains active but atom reach is not consulted. - expect(canonicalSpy).toHaveBeenCalled() - expect(routesSpy).not.toHaveBeenCalled() - expect(importRoutesSpy).not.toHaveBeenCalled() - expect(thresholdSpy).not.toHaveBeenCalled() - }, - ) - - it('defers a custom threshold above the minimum until reservation lands', () => { - // Given: two routes; the threshold must not be replaced by the default. - // When: the caller requests three routes. - DevupUI({}, { atomHoist: 3 }) - // Then: unavailable atom hoisting never installs a threshold. - expect(thresholdSpy).not.toHaveBeenCalled() - expect(routesSpy).not.toHaveBeenCalled() - }) - - it.each([ - ['omitted', {}], - ['undefined', { atomHoist: undefined }], - ['enabled', { atomHoist: 2 }], - ])( - 'ignores %s atomHoist before planning in actual singleCss mode', - (_label, options) => { - // Given: legacy whole-file hoisting and an explicit-OFF single sheet. - process.env.DEVUP_HOIST_V = '3' - const off = DevupUI({}, { singleCss: true, atomHoist: 0 }) - const offExtractions = [...codeExtractWithoutSourceMapSpy.mock.calls] - expect(offExtractions).toHaveLength(2) - codeExtractWithoutSourceMapSpy.mockClear() - canonicalSpy.mockClear() - - // When: only the atom option changes. - const on = DevupUI({}, { singleCss: true, ...options }) - - // Then: reach/threshold, legacy policy, IDs, imports and loader config agree. - expect(routesSpy).not.toHaveBeenCalled() - expect(importRoutesSpy).not.toHaveBeenCalled() - expect(thresholdSpy).not.toHaveBeenCalled() - expect(canonicalSpy).toHaveBeenCalledWith( - expect.objectContaining({ hoistV: 3 }), - ) - expect(codeExtractWithoutSourceMapSpy.mock.calls).toEqual( - offExtractions, - ) - expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( - 'src/app/a/page.tsx', - '{}', - '@devup-ui/react', - expect.any(String), - true, - false, - true, - expect.anything(), - ) - expect(on.turbopack?.rules).toEqual(off.turbopack?.rules) - }, - ) - }) - - it('preserves single-importer collapse but defers atom reach when atomHoist is set', () => { - process.env.TURBOPACK = '1' - // 4 distinct leaf routes (ids 0..3); layout shared by all four. - const computeSpy = spyOn( - importGraphModule, - 'computeFileRoutes', - ).mockReturnValue({ - 'src/app/layout.tsx': [0, 1, 2, 3], - 'src/app/a/page.tsx': [0], - 'src/app/b/page.tsx': [1], - 'src/app/c/page.tsx': [2], - 'src/app/d/page.tsx': [3], - }) - const importFileRoutesSpy = spyOn( - wasm, - 'importFileRoutes', - ).mockReturnValue(undefined) - const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( - undefined, - ) - // Collapse must still run while atom hoisting is unavailable. - const importCanonicalMapSpy = spyOn( - wasm, - 'importCanonicalMap', - ).mockReturnValue(undefined) - try { - DevupUI({}, { atomHoist: 2 }) - expect(computeSpy).not.toHaveBeenCalled() - expect(importFileRoutesSpy).not.toHaveBeenCalled() - expect(setAtomHoistSpy).not.toHaveBeenCalled() - // composition: collapse pre-pass also ran - expect(importCanonicalMapSpy).toHaveBeenCalled() - } finally { - computeSpy.mockRestore() - importFileRoutesSpy.mockRestore() - setAtomHoistSpy.mockRestore() - importCanonicalMapSpy.mockRestore() - } - }) - - it('defers even the former minimum-clamped atomHoist request', () => { - process.env.TURBOPACK = '1' - const computeSpy = spyOn( - importGraphModule, - 'computeFileRoutes', - ).mockReturnValue({ - 'src/app/a/page.tsx': [0], - 'src/app/b/page.tsx': [1], - }) - const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( - undefined, - ) - try { - DevupUI({}, { atomHoist: 1 }) - expect(computeSpy).not.toHaveBeenCalled() - expect(setAtomHoistSpy).not.toHaveBeenCalled() - } finally { - computeSpy.mockRestore() - setAtomHoistSpy.mockRestore() - } - }) - - it('keeps atom hoisting off when fewer than two routes exist', () => { - process.env.TURBOPACK = '1' - const computeSpy = spyOn( - importGraphModule, - 'computeFileRoutes', - ).mockReturnValue({ 'src/app/a/page.tsx': [0] }) - const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( - undefined, - ) - try { - DevupUI({}, { atomHoist: 2 }) - expect(setAtomHoistSpy).not.toHaveBeenCalled() - } finally { - computeSpy.mockRestore() - setAtomHoistSpy.mockRestore() - } - }) - }) -}) +import { spawnSync } from 'node:child_process' +import * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +import type { StaticImportGraph } from '@devup-ui/plugin-utils' +import * as importGraphModule from '@devup-ui/plugin-utils' +import * as wasm from '@devup-ui/wasm' +import * as webpackPluginModule from '@devup-ui/webpack-plugin' +import { + afterEach, + beforeEach, + describe, + expect, + it, + mock, + spyOn, +} from 'bun:test' + +import * as coordinatorModule from '../coordinator' +import * as coordinatorPortModule from '../coordinator-port' +import cssLoader, { resetInit as resetCssInit } from '../css-loader' +import { + DevupUI, + reloadTurboSetupModuleForTesting, + resetTurboSetupCacheForTesting, + restoreSessionState, +} from '../plugin' +import { + loadWasm, + setWasmForTesting, + setWebpackPluginForTesting, +} from '../wasm' + +type CodeExtractResult = ReturnType +type NextWebpackConfig = Parameters< + NonNullable['webpack']> +>[0] +type NextWebpackContext = Parameters< + NonNullable['webpack']> +>[1] + +function createWebpackConfig(): NextWebpackConfig { + return { plugins: [] } as unknown as NextWebpackConfig +} + +function createWebpackContext( + overrides: Partial = {}, +): NextWebpackContext { + return { buildId: 'tmpBuildId', ...overrides } as NextWebpackContext +} + +function setNodeEnv(value: string): void { + process.env.NODE_ENV = value +} + +function createCodeExtractResult(contents: string): CodeExtractResult { + return { + css: '', + code: contents, + cssFile: '', + map: undefined, + updatedBaseStyle: false, + free: mock(), + [Symbol.dispose]: mock(), + } as unknown as CodeExtractResult +} + +function createSingleFileGraph(filename: string): StaticImportGraph { + return { + files: [filename], + fileSet: new Set([filename]), + staticImports: new Map([[filename, new Set()]]), + staticImporters: new Map([[filename, new Set()]]), + dynamicTargets: new Set(), + dynamicImports: new Map([[filename, new Set()]]), + externalImports: new Map([[filename, new Set()]]), + } +} + +let existsSyncSpy: ReturnType +let mkdirSyncSpy: ReturnType +let readFileSyncSpy: ReturnType +let writeFileSyncSpy: ReturnType +let unlinkSyncSpy: ReturnType +let getDefaultThemeSpy: ReturnType +let getThemeInterfaceSpy: ReturnType +let setPrefixSpy: ReturnType +let registerThemeSpy: ReturnType +let getCssSpy: ReturnType +let importSheetSpy: ReturnType +let importClassMapSpy: ReturnType +let importFileMapSpy: ReturnType +let exportSheetSpy: ReturnType +let exportClassMapSpy: ReturnType +let exportFileMapSpy: ReturnType +let codeExtractSpy: ReturnType +let codeExtractWithoutSourceMapSpy: ReturnType +let devupUIWebpackPluginSpy: ReturnType +let startCoordinatorSpy: ReturnType +let readJsxImportSourceSpy: ReturnType + +let originalEnv: NodeJS.ProcessEnv +let originalEnvValues: NodeJS.ProcessEnv +let originalFetch: typeof global.fetch +let originalDebugPort: number + +beforeEach(() => { + resetTurboSetupCacheForTesting() + existsSyncSpy = spyOn(fs, 'existsSync').mockReturnValue(false) + mkdirSyncSpy = spyOn(fs, 'mkdirSync').mockReturnValue(undefined) + readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue('{}') + writeFileSyncSpy = spyOn(fs, 'writeFileSync').mockReturnValue(undefined) + unlinkSyncSpy = spyOn(fs, 'unlinkSync').mockReturnValue(undefined) + getDefaultThemeSpy = spyOn(wasm, 'getDefaultTheme').mockReturnValue(undefined) + getThemeInterfaceSpy = spyOn(wasm, 'getThemeInterface').mockReturnValue('') + setPrefixSpy = spyOn(wasm, 'setPrefix').mockReturnValue(undefined) + registerThemeSpy = spyOn(wasm, 'registerTheme').mockReturnValue(undefined) + getCssSpy = spyOn(wasm, 'getCss').mockReturnValue('') + importSheetSpy = spyOn(wasm, 'importSheet').mockReturnValue(undefined) + importClassMapSpy = spyOn(wasm, 'importClassMap').mockReturnValue(undefined) + importFileMapSpy = spyOn(wasm, 'importFileMap').mockReturnValue(undefined) + exportSheetSpy = spyOn(wasm, 'exportSheet').mockReturnValue( + JSON.stringify({ + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }), + ) + exportClassMapSpy = spyOn(wasm, 'exportClassMap').mockReturnValue( + JSON.stringify({}), + ) + exportFileMapSpy = spyOn(wasm, 'exportFileMap').mockReturnValue( + JSON.stringify({}), + ) + codeExtractSpy = spyOn(wasm, 'codeExtract').mockImplementation( + (_path: string, contents: string) => createCodeExtractResult(contents), + ) + codeExtractWithoutSourceMapSpy = spyOn( + wasm, + 'codeExtractWithoutSourceMap', + ).mockImplementation((_path: string, contents: string) => + createCodeExtractResult(contents), + ) + devupUIWebpackPluginSpy = spyOn( + webpackPluginModule, + 'DevupUIWebpackPlugin', + ).mockImplementation(mock() as never) + startCoordinatorSpy = spyOn( + coordinatorModule, + 'startCoordinator', + ).mockReturnValue({ close: mock() as () => void }) + readJsxImportSourceSpy = spyOn( + importGraphModule, + 'readJsxImportSource', + ).mockReturnValue(undefined) + setWasmForTesting(wasm) + setWebpackPluginForTesting(webpackPluginModule) + + originalEnv = process.env + originalEnvValues = { ...originalEnv } + originalFetch = global.fetch + originalDebugPort = process.debugPort + global.fetch = mock(() => Promise.resolve({} as Response)) +}) + +afterEach(() => { + coordinatorModule.resetCoordinator() + resetTurboSetupCacheForTesting() + setWasmForTesting(undefined) + setWebpackPluginForTesting(undefined) + for (const key of Object.keys(originalEnv)) { + if (!Object.hasOwn(originalEnvValues, key)) delete originalEnv[key] + } + Object.assign(originalEnv, originalEnvValues) + process.env = originalEnv + global.fetch = originalFetch + process.debugPort = originalDebugPort + readJsxImportSourceSpy.mockRestore() + existsSyncSpy.mockRestore() + mkdirSyncSpy.mockRestore() + readFileSyncSpy.mockRestore() + writeFileSyncSpy.mockRestore() + unlinkSyncSpy.mockRestore() + getDefaultThemeSpy.mockRestore() + getThemeInterfaceSpy.mockRestore() + setPrefixSpy.mockRestore() + registerThemeSpy.mockRestore() + getCssSpy.mockRestore() + importSheetSpy.mockRestore() + importClassMapSpy.mockRestore() + importFileMapSpy.mockRestore() + exportSheetSpy.mockRestore() + exportClassMapSpy.mockRestore() + exportFileMapSpy.mockRestore() + codeExtractSpy.mockRestore() + codeExtractWithoutSourceMapSpy.mockRestore() + devupUIWebpackPluginSpy.mockRestore() + startCoordinatorSpy.mockRestore() +}) + +describe('DevupUINextPlugin', () => { + it.each(['1', 'auto', undefined])( + 'rejects typos at creation before setup in mode %s', + (mode) => { + if (mode === undefined) delete process.env.TURBOPACK + else process.env.TURBOPACK = mode + expect(() => + Reflect.apply(DevupUI, undefined, [ + {}, + { shorthands: { bgx: ['backgroundColour'] } }, + ]), + ).toThrow(importGraphModule.ShorthandConfigError) + expect(writeFileSyncSpy).not.toHaveBeenCalled() + expect(startCoordinatorSpy).not.toHaveBeenCalled() + expect(devupUIWebpackPluginSpy).not.toHaveBeenCalled() + }, + ) + + it('registers canonical targets when a Turbopack plugin is created', () => { + process.env.TURBOPACK = '1' + const registration = spyOn(wasm, 'registerShorthands').mockReturnValue( + undefined, + ) + try { + DevupUI({}, { shorthands: { bgx: ['backgroundColor', 'py', '--Gap'] } }) + expect(registration.mock.calls).toEqual([ + [ + { + bgx: ['background-color', 'padding-top', 'padding-bottom', '--Gap'], + }, + ], + ]) + } finally { + registration.mockRestore() + } + }) + + it('reads StyleX under the styleResolution a Turbopack plugin is given', () => { + process.env.TURBOPACK = '1' + const resolution = spyOn(wasm, 'setStylexStyleResolution') + try { + DevupUI({}, { stylex: { styleResolution: 'legacy-expand-shorthands' } }) + expect(resolution.mock.calls).toEqual([['legacy-expand-shorthands']]) + } finally { + resolution.mockRestore() + wasm.setStylexStyleResolution(null) + } + }) + + it.each(['1', undefined])( + 'rejects an unknown styleResolution before setup in mode %s', + (mode) => { + if (mode === undefined) delete process.env.TURBOPACK + else process.env.TURBOPACK = mode + expect(() => + Reflect.apply(DevupUI, undefined, [ + {}, + { stylex: { styleResolution: 'last-wins' } }, + ]), + ).toThrow(importGraphModule.StylexConfigError) + expect(startCoordinatorSpy).not.toHaveBeenCalled() + expect(devupUIWebpackPluginSpy).not.toHaveBeenCalled() + }, + ) + + it('rejects a typo before reading an available production handoff', () => { + process.env.TURBOPACK = '1' + setNodeEnv('production') + DevupUI({}, { shorthands: { bgx: ['backgroundColor'] } }) + reloadTurboSetupModuleForTesting() + readFileSyncSpy.mockClear() + const shorthands = { bgx: ['backgroundColour'] } + Object.defineProperty(shorthands, 'toJSON', { + value: () => ({ bgx: ['background-color'] }), + }) + + expect(() => + Reflect.apply(DevupUI, undefined, [{}, { shorthands }]), + ).toThrow(importGraphModule.ShorthandConfigError) + expect(readFileSyncSpy).not.toHaveBeenCalled() + expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) + }) + + it('prewarms and serves actual default Turbo extraction through native state', () => { + // The child starts inside the fixture, as Next does, instead of changing + // its directory after the plugin modules have loaded. + const root = fs.mkdtempSync(join(tmpdir(), 'devup-next-native-')) + const child = spawnSync( + process.execPath, + [ + '-e', + ` + import assert from 'node:assert/strict'; + import { mkdirSync, realpathSync, writeFileSync } from 'node:fs'; + import { join } from 'node:path'; + import { DevupUI } from ${JSON.stringify(new URL('../plugin.ts', import.meta.url).href)}; + import loader from ${JSON.stringify(new URL('../loader.ts', import.meta.url).href)}; + import { loadWasm, withModuleResolver } from ${JSON.stringify(new URL('../wasm.ts', import.meta.url).href)}; + import { flushCoordinatorWrites, resetCoordinator } from ${JSON.stringify(new URL('../coordinator.ts', import.meta.url).href)}; + import { loadCompiler } from ${JSON.stringify(new URL('../../../plugin-utils/src/index.ts', import.meta.url).href)}; + const native = loadCompiler('native'), wasm = loadCompiler('wasm'); + const primedWasm = loadWasm('wasm'); // Resolve the old loader dependency at its installed location. + const root = ${JSON.stringify(root)}; + assert.equal(realpathSync.native(process.cwd()), realpathSync.native(root)); + try { + mkdirSync(join(root, 'src/app'), { recursive: true }); + writeFileSync(join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { jsx: 'react-jsx' }, include: ['src'] })); + writeFileSync(join(root, 'src/tokens.ts'), "export const tone = 'teal';"); + const source = "import {Box} from '@devup-ui/react'; import {tone} from '../tokens'; export default function Page(){return ;}"; + const resourcePath = join(root, 'src/app/page.tsx'); + writeFileSync(resourcePath, source); + native.resetStateForTesting(); wasm.resetStateForTesting(); + withModuleResolver(primedWasm); // Match normal fixed-cwd supplier resolution after fixture setup. + const before = { native: native.getCss(null, false), wasm: wasm.getCss(null, false) }; + const config = DevupUI({}, { singleCss: true, debug: false }); + const options = config.turbopack.rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'].loaders[0].options; + const code = await new Promise((resolve, reject) => loader.call({ + resourcePath, getOptions: () => options, addDependency() {}, + async: () => (error, code) => error ? reject(error) : resolve(code), + }, Buffer.from(source))); + const after = { native: native.getCss(null, false), wasm: wasm.getCss(null, false) }; + console.info(JSON.stringify({ observed: 'next-default-native', before, after, code })); + assert.equal(typeof code, 'string'); assert(!code.includes(' { + resetCssInit() + const failure = new Error('consumer callback failure', { + cause: new Error('consumer cause'), + }) + let callbacks = 0 + const context = { + resourcePath: 'df/devup-ui/devup-ui.css', + getOptions: () => ({ + watch: false, + defaultFileMap: {}, + defaultClassMap: {}, + defaultSheet: {}, + }), + callback() { + callbacks++ + throw failure + }, + } + expect(() => + Reflect.apply(cssLoader, context, [Buffer.from('ready')]), + ).toThrow(failure) + expect(callbacks).toBe(1) + resetCssInit() + }) + + it('retains original CSS compiler failure and cause in one callback', () => { + resetCssInit() + const cause = new Error('compiler cause') + const failure = new Error('compiler failure', { cause }) + getCssSpy.mockImplementation(() => { + throw failure + }) + const received: (Error | null)[] = [] + Reflect.apply( + cssLoader, + { + resourcePath: 'df/devup-ui/devup-ui.css', + getOptions: () => ({ + watch: true, + sheetFile: 'sheet', + classMapFile: 'classes', + fileMapFile: 'files', + themeFile: 'theme', + }), + callback(error: Error | null) { + received.push(error) + }, + }, + [Buffer.from('ready')], + ) + expect(received).toEqual([failure]) + expect(received[0]?.cause).toBe(cause) + resetCssInit() + }) + + it('caches each selected physical compiler and rejects invalid engines', () => { + setWasmForTesting(undefined) + const native = importGraphModule.loadCompiler('native') + const explicitWasm = importGraphModule.loadCompiler('wasm') + expect(loadWasm()).toBe(native) + expect(loadWasm('native')).toBe(native) + expect(loadWasm('wasm')).toBe(explicitWasm) + expect(loadWasm('wasm')).toBe(explicitWasm) + expect(native).not.toBe(explicitWasm) + expect(() => Reflect.apply(loadWasm, undefined, ['other'])).toThrow( + importGraphModule.InvalidEngineError, + ) + expect(() => Reflect.apply(loadWasm, undefined, [null])).toThrow( + importGraphModule.InvalidEngineError, + ) + }) + + describe('webpack', () => { + it.each(['native', 'wasm'] as const)( + 'retains %s in a deferred Webpack callback', + (engine) => { + delete process.env.TURBOPACK + const options = { engine } + const config = DevupUI({}, options) + options.engine = engine === 'native' ? 'wasm' : 'native' + config.webpack?.(createWebpackConfig(), createWebpackContext()) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( + expect.objectContaining({ engine }), + ) + }, + ) + + it.each([ + ['omitted', {}], + ['undefined', { atomHoist: undefined }], + ['OFF', { atomHoist: 0 }], + ['ON', { atomHoist: 2 }], + ['custom', { atomHoist: 3 }], + ])( + 'default regressions: delegates %s atom policy to webpack', + (_label, options) => { + // Given: the webpack path, whose constructor owns the resolved default. + delete process.env.TURBOPACK + const ret = DevupUI({}, { ...options, singleCss: true }) + // When: Next configures its webpack compilation. + ret.webpack?.(createWebpackConfig(), createWebpackContext()) + // Then: explicit zero/thresholds and singleCss reach the real adapter seam. + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + ...options, + engine: 'native', + singleCss: true, + cssDir: resolve('.next/cache', 'devup-ui'), + productionPrewarmFiles: [], + sourceCache: expect.any(Map), + }) + }, + ) + + it('shares one source cache between the compilers of a production build, none in dev', () => { + // Given + delete process.env.TURBOPACK + const ret = DevupUI({}) + // When: Next configures its server and client compilers, then a dev one + ret.webpack!(createWebpackConfig(), createWebpackContext()) + ret.webpack!(createWebpackConfig(), createWebpackContext()) + ret.webpack!(createWebpackConfig(), { + ...createWebpackContext(), + dev: true, + }) + // Then + const [server, client, dev] = devupUIWebpackPluginSpy.mock.calls.map( + ([options]) => (options as { sourceCache?: unknown }).sourceCache, + ) + expect(server).toBeInstanceOf(Map) + expect(client).toBe(server) + expect(dev).toBeUndefined() + }) + + it('should apply webpack plugin', async () => { + const ret = DevupUI({}) + + ret.webpack!(createWebpackConfig(), createWebpackContext()) + + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + cssDir: resolve('.next/cache', 'devup-ui'), + engine: 'native', + productionPrewarmFiles: [], + sourceCache: expect.any(Map), + }) + }) + + it('hands licenseBanner to the webpack plugin', () => { + DevupUI({}, { licenseBanner: false }).webpack!( + createWebpackConfig(), + createWebpackContext(), + ) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( + expect.objectContaining({ licenseBanner: false }), + ) + }) + + it('reads routes from the project root when it holds app or pages', () => { + // Given: a Next app with `app/` at the root and no `src/`. + existsSyncSpy.mockImplementation( + (path: fs.PathLike) => String(path) === resolve('app'), + ) + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(resolve('app/page.tsx'))) + try { + // When + DevupUI({}).webpack!(createWebpackConfig(), createWebpackContext()) + // Then + expect(graphSpy).toHaveBeenCalledWith( + process.cwd(), + resolve('tsconfig.json'), + ) + } finally { + graphSpy.mockRestore() + } + }) + + it('reads routes and places the CSS under the Next project directory', () => { + // Given: `next build apps/web` started from the workspace root. + const dir = resolve('apps', 'web') + existsSyncSpy.mockImplementation( + (path: fs.PathLike) => String(path) === join(dir, 'app'), + ) + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(join(dir, 'app', 'page.tsx'))) + try { + // When + DevupUI({}).webpack!( + createWebpackConfig(), + createWebpackContext({ dir }), + ) + // Then + expect(graphSpy).toHaveBeenCalledWith(dir, join(dir, 'tsconfig.json')) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith( + expect.objectContaining({ + cssDir: join(dir, '.next', 'cache', 'devup-ui'), + }), + ) + } finally { + graphSpy.mockRestore() + } + }) + + it('places the dev CSS under the Next project directory', () => { + const dir = resolve('apps', 'web') + DevupUI({}).webpack!( + createWebpackConfig(), + createWebpackContext({ dev: true, dir }), + ) + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + cssDir: join(dir, 'df', 'devup-ui_tmpBuildId'), + engine: 'native', + watch: true, + }) + }) + + it('should apply webpack plugin with dev', async () => { + const ret = DevupUI({}) + + ret.webpack!(createWebpackConfig(), createWebpackContext({ dev: true })) + + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + cssDir: resolve('df', 'devup-ui_tmpBuildId'), + engine: 'native', + watch: true, + }) + }) + + it('should apply webpack plugin with config', async () => { + const ret = DevupUI( + {}, + { + package: 'new-package', + }, + ) + + ret.webpack!(createWebpackConfig(), createWebpackContext()) + + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + package: 'new-package', + engine: 'native', + cssDir: resolve('.next/cache', 'devup-ui'), + productionPrewarmFiles: [], + sourceCache: expect.any(Map), + }) + }) + + it('should apply webpack plugin with webpack obj', async () => { + const webpack = mock() + const ret = DevupUI( + { + webpack, + }, + { + package: 'new-package', + }, + ) + + ret.webpack!(createWebpackConfig(), createWebpackContext()) + + expect(devupUIWebpackPluginSpy).toHaveBeenCalledWith({ + package: 'new-package', + engine: 'native', + cssDir: resolve('.next/cache', 'devup-ui'), + productionPrewarmFiles: [], + sourceCache: expect.any(Map), + }) + expect(webpack).toHaveBeenCalled() + }) + }) + describe('turbo', () => { + it('reuses production setup across Next config module reloads', () => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_PROFILE = '1' + getDefaultThemeSpy.mockReturnValue('dark') + const filename = resolve('src/app/page.tsx') + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(filename)) + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx']) + const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) + const normalizeSpy = spyOn(importGraphModule, 'normalizeShorthands') + const handoffFile = join('df', 'setup.bin') + let handoff: Parameters[1] | undefined + writeFileSyncSpy.mockImplementation((path, data) => { + if (String(path) === handoffFile) handoff = data + }) + readFileSyncSpy.mockImplementation((path) => { + if (String(path) === handoffFile && handoff !== undefined) { + return handoff as never + } + return '{}' as never + }) + unlinkSyncSpy.mockImplementation((path) => { + if (String(path) === handoffFile) throw new Error('cleanup failed') + }) + + try { + const first = DevupUI( + {}, + { singleCss: true, shorthands: { bgx: ['backgroundColor'] } }, + ) + reloadTurboSetupModuleForTesting() + const second = DevupUI( + { env: { EXISTING: 'value' } }, + { singleCss: true, shorthands: { bgx: ['background-color'] } }, + ) + + expect(second.turbopack?.rules).toEqual(first.turbopack?.rules) + expect(second.env).toEqual({ + DEVUP_UI_DEFAULT_THEME: 'dark', + EXISTING: 'value', + }) + expect(graphSpy).toHaveBeenCalledTimes(1) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(1) + expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) + expect(normalizeSpy).toHaveBeenCalledTimes(2) + expect(unlinkSyncSpy).toHaveBeenCalledWith(handoffFile) + expect(profileSpy).toHaveBeenCalledWith( + expect.stringContaining('"cacheHit":true'), + ) + } finally { + normalizeSpy.mockRestore() + profileSpy.mockRestore() + compiledSpy.mockRestore() + graphSpy.mockRestore() + } + }) + it.each([true, false])( + 'availability: reuses production setup and warns once across config reloads (singleCss %s)', + (singleCss) => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_PROFILE = '1' + getDefaultThemeSpy.mockReturnValue('dark') + const filename = resolve('src/app/page.tsx') + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(filename)) + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx']) + const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) + const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) + const handoffFile = join('df', 'setup.bin') + let handoff: Parameters[1] | undefined + writeFileSyncSpy.mockImplementation((path, data) => { + if (String(path) === handoffFile) handoff = data + }) + readFileSyncSpy.mockImplementation((path) => { + if (String(path) === handoffFile && handoff !== undefined) { + return handoff as never + } + return '{}' as never + }) + unlinkSyncSpy.mockImplementation((path) => { + if (String(path) === handoffFile) throw new Error('cleanup failed') + }) + + try { + const first = DevupUI({}, { singleCss, atomHoist: 2 }) + reloadTurboSetupModuleForTesting() + const second = DevupUI( + { env: { EXISTING: 'value' } }, + { singleCss, atomHoist: 2 }, + ) + + expect(second.turbopack?.rules).toEqual(first.turbopack?.rules) + expect(second.env).toEqual({ + DEVUP_UI_DEFAULT_THEME: 'dark', + EXISTING: 'value', + }) + expect(graphSpy).toHaveBeenCalledTimes(1) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(1) + expect(startCoordinatorSpy).toHaveBeenCalledTimes(1) + expect(warningSpy).toHaveBeenCalledTimes(singleCss ? 0 : 1) + expect(unlinkSyncSpy).toHaveBeenCalledWith(handoffFile) + expect(profileSpy).toHaveBeenCalledWith( + expect.stringContaining('"cacheHit":true'), + ) + } finally { + warningSpy.mockRestore() + profileSpy.mockRestore() + compiledSpy.mockRestore() + graphSpy.mockRestore() + } + }, + ) + + it('falls back when a production setup handoff is not reusable', () => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + const filename = resolve('src/app/page.tsx') + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(filename)) + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx']) + const handoffFile = join('df', 'setup.bin') + let failHandoffWrite = false + let handoff: Parameters[1] | undefined + writeFileSyncSpy.mockImplementation((path, data) => { + if (String(path) !== handoffFile) return + if (failHandoffWrite) throw new Error('write failed') + handoff = data + }) + readFileSyncSpy.mockImplementation((path) => { + if (String(path) === handoffFile && handoff !== undefined) { + return handoff as never + } + return '{}' as never + }) + + try { + DevupUI({}) + // The same module instance must not consume its own handoff. + DevupUI({}) + reloadTurboSetupModuleForTesting() + handoff = Buffer.from('invalid handoff') + failHandoffWrite = true + + // A corrupt read and a failed replacement write both fall back to the + // complete setup without leaking a token into another config load. + expect(() => DevupUI({})).not.toThrow() + expect(graphSpy).toHaveBeenCalledTimes(3) + expect(process.env.DEVUP_UI_TURBO_SETUP_TOKEN).toBeUndefined() + } finally { + compiledSpy.mockRestore() + graphSpy.mockRestore() + } + }) + + it('compiles every source extension the import graph lists under Turbopack', () => { + process.env.TURBOPACK = '1' + const rules = Object.keys(DevupUI({}).turbopack?.rules ?? {}) + const glob = rules.find((rule) => rule.startsWith('*.{')) + expect(glob?.slice(3, -1).split(',').sort()).toEqual( + importGraphModule.SOURCE_EXTENSIONS.map((extension) => + extension.slice(1), + ).sort(), + ) + }) + + it('should apply turbo config', async () => { + process.env.TURBOPACK = '1' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + const ret = DevupUI({}) + + expect(ret).toEqual({ + turbopack: { + rules: { + './df/devup-ui/*.css': [ + { + loader: '@devup-ui/next-plugin/css-loader', + options: { + engine: 'native', + watch: false, + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + theme: {}, + defaultClassMap: {}, + defaultFileMap: {}, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + }, + }, + ], + '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { + loaders: [ + { + loader: '@devup-ui/next-plugin/loader', + options: { + engine: 'native', + package: '@devup-ui/react', + cssDir: resolve('df', 'devup-ui'), + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + watch: false, + singleCss: false, + theme: {}, + defaultClassMap: {}, + defaultFileMap: {}, + importAliases: { + '@emotion/react': null, + '@emotion/styled': 'styled', + '@emotion/css': null, + '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, + 'styled-components': 'styled', + }, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + }, + }, + ], + condition: { + not: { + path: new RegExp( + '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', + ), + }, + }, + }, + }, + }, + }) + }) + it('should apply turbo config with create df', async () => { + process.env.TURBOPACK = '1' + existsSyncSpy.mockReturnValue(false) + mkdirSyncSpy.mockReturnValue('') + writeFileSyncSpy.mockReturnValue(undefined) + const ret = DevupUI({}) + + expect(ret).toEqual({ + turbopack: { + rules: { + './df/devup-ui/*.css': [ + { + loader: '@devup-ui/next-plugin/css-loader', + options: { + engine: 'native', + watch: false, + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + theme: {}, + defaultClassMap: {}, + defaultFileMap: {}, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + }, + }, + ], + '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { + condition: { + not: { + path: new RegExp( + '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', + ), + }, + }, + loaders: [ + { + loader: '@devup-ui/next-plugin/loader', + options: { + engine: 'native', + package: '@devup-ui/react', + cssDir: resolve('df', 'devup-ui'), + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + importAliases: { + '@emotion/react': null, + '@emotion/styled': 'styled', + '@emotion/css': null, + '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, + 'styled-components': 'styled', + }, + watch: false, + singleCss: false, + theme: {}, + defaultClassMap: {}, + defaultFileMap: {}, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + }, + }, + ], + }, + }, + }, + }) + expect(mkdirSyncSpy).toHaveBeenCalledWith('df', { + recursive: true, + }) + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join('df', '.gitignore'), + '*', + ) + }) + it('should apply turbo config with exists df and devup.json', async () => { + process.env.TURBOPACK = '1' + existsSyncSpy.mockReturnValue(true) + readFileSyncSpy.mockReturnValue(JSON.stringify({ theme: 'theme' })) + mkdirSyncSpy.mockReturnValue('') + writeFileSyncSpy.mockReturnValue(undefined) + const ret = DevupUI({}) + + expect(ret).toEqual({ + turbopack: { + rules: { + './df/devup-ui/*.css': [ + { + loader: '@devup-ui/next-plugin/css-loader', + options: { + engine: 'native', + watch: false, + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + theme: 'theme', + defaultClassMap: {}, + defaultFileMap: {}, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + }, + }, + ], + '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}': { + condition: { + not: { + path: new RegExp( + '((?:^|[\\/\\\\])node_modules[\\/\\\\](?!.*[\\/\\\\]node_modules[\\/\\\\])(?!(?:@devup-ui|@devup-editor)(?:[\\/\\\\]|$)))|(.mdx.[tj]sx?$)', + ), + }, + }, + loaders: [ + { + loader: '@devup-ui/next-plugin/loader', + options: { + engine: 'native', + package: '@devup-ui/react', + cssDir: resolve('df', 'devup-ui'), + coordinatorPortFile: join('df', 'coordinator.port'), + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + watch: false, + singleCss: false, + theme: 'theme', + defaultClassMap: {}, + defaultFileMap: {}, + importAliases: { + '@emotion/react': null, + '@emotion/styled': 'styled', + '@emotion/css': null, + '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, + 'styled-components': 'styled', + }, + defaultSheet: { + css: {}, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + }, + themeFile: 'devup.json', + themeFiles: [resolve('devup.json')], + }, + }, + ], + }, + }, + }, + }) + // mkdirSync is NOT called when existsSync returns true + expect(mkdirSyncSpy).not.toHaveBeenCalled() + // gitignore is also NOT written when it exists + expect(writeFileSyncSpy).not.toHaveBeenCalledWith( + join('df', '.gitignore'), + '*', + ) + }) + it('should start coordinator even in production mode', () => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + const ret = DevupUI({}) + expect(ret).toEqual({ + turbopack: { + rules: expect.any(Object), + }, + }) + expect(startCoordinatorSpy).toHaveBeenCalledWith({ + distDir: 'df', + wasm: coordinatorModule.openCoordinatorCompiler('df', wasm), + package: '@devup-ui/react', + cssDir: resolve('df', 'devup-ui'), + singleCss: false, + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + importAliases: { + '@emotion/react': null, + '@emotion/styled': 'styled', + '@emotion/css': null, + '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, + 'styled-components': 'styled', + }, + coordinatorPortFile: join('df', 'coordinator.port'), + canonicalMap: expect.any(Object), + expectedBaseFiles: expect.any(Array), + prewarmedFiles: expect.any(Array), + prewarmedOutputs: expect.any(Map), + sourceMap: false, + }) + }) + it('extracts vanilla-extract modules as written', () => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + const filename = resolve('src/styles.css.ts') + const source = `import { style } from '@vanilla-extract/css' +export const box = style({ color: 'red' })` + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue(createSingleFileGraph(filename)) + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/styles.css.ts']) + readFileSyncSpy.mockImplementation((path: fs.PathOrFileDescriptor) => + String(path).endsWith('styles.css.ts') ? source : '{}', + ) + + try { + DevupUI({}) + + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( + 'src/styles.css.ts', + source, + '@devup-ui/react', + expect.any(String), + false, + false, + true, + expect.anything(), + ) + } finally { + graphSpy.mockRestore() + compiledSpy.mockRestore() + } + }) + it('keeps source maps when Next production browser source maps are enabled', () => { + setNodeEnv('production') + process.env.TURBOPACK = '1' + + DevupUI({ productionBrowserSourceMaps: true }) + + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ sourceMap: true }), + ) + }) + it('keeps configuring Turbopack when the import graph cannot be read', () => { + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_PROFILE = '1' + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockImplementation(() => { + throw new Error('unreadable') + }) + const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) + const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) + try { + expect(DevupUI({}).turbopack?.rules).toBeDefined() + expect(profileSpy).toHaveBeenCalledWith( + expect.stringContaining('"failed":true'), + ) + expect(warnSpy).toHaveBeenCalledWith( + '[devup-ui] Turbopack import graph failed: unreadable. Classes are not merged across files only one module imports, and the production stylesheet waits for extraction to go quiet instead of for every compiled file.', + ) + } finally { + profileSpy.mockRestore() + warnSpy.mockRestore() + graphSpy.mockRestore() + } + }) + it.each([ + [{}, false], + [{ debug: true }, true], + ])('sets debug class names from %j', (options, debug) => { + process.env.TURBOPACK = '1' + const setDebugSpy = spyOn(wasm, 'setDebug').mockReturnValue(undefined) + try { + DevupUI({}, options) + expect(setDebugSpy).toHaveBeenCalledWith(debug) + } finally { + setDebugSpy.mockRestore() + } + }) + it('should create theme.d.ts file', async () => { + process.env.TURBOPACK = '1' + existsSyncSpy.mockReturnValue(true) + getThemeInterfaceSpy.mockReturnValue('interface code') + readFileSyncSpy.mockReturnValue(JSON.stringify({ theme: 'theme' })) + mkdirSyncSpy.mockReturnValue('') + writeFileSyncSpy.mockReturnValue(undefined) + DevupUI({}) + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join('df', 'theme.d.ts'), + 'interface code', + ) + // mkdirSync is NOT called when existsSync returns true + expect(mkdirSyncSpy).not.toHaveBeenCalled() + }) + it('should set DEVUP_UI_DEFAULT_THEME when getDefaultTheme returns a value', async () => { + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_DEFAULT_THEME = '' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + getDefaultThemeSpy.mockReturnValue('dark') + const config: any = {} + const ret = DevupUI(config) + + expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('dark') + expect(ret.env).toEqual({ + DEVUP_UI_DEFAULT_THEME: 'dark', + }) + expect(config.env).toEqual({ + DEVUP_UI_DEFAULT_THEME: 'dark', + }) + }) + it('should not set DEVUP_UI_DEFAULT_THEME when getDefaultTheme returns undefined', async () => { + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_DEFAULT_THEME = '' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + getDefaultThemeSpy.mockReturnValue(undefined) + const config: any = {} + const ret = DevupUI(config) + + expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('') + expect(ret.env).toBeUndefined() + expect(config.env).toBeUndefined() + }) + it('should set DEVUP_UI_DEFAULT_THEME and preserve existing env vars', async () => { + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_DEFAULT_THEME = '' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + getDefaultThemeSpy.mockReturnValue('light') + const config: any = { + env: { + CUSTOM_VAR: 'value', + }, + } + const ret = DevupUI(config) + + expect(process.env.DEVUP_UI_DEFAULT_THEME).toBe('light') + expect(ret.env).toEqual({ + CUSTOM_VAR: 'value', + DEVUP_UI_DEFAULT_THEME: 'light', + }) + expect(config.env).toEqual({ + CUSTOM_VAR: 'value', + DEVUP_UI_DEFAULT_THEME: 'light', + }) + }) + it('should call setPrefix when prefix option is provided', async () => { + process.env.TURBOPACK = '1' + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + DevupUI({}, { prefix: 'my-prefix' }) + expect(setPrefixSpy).toHaveBeenCalledWith('my-prefix') + }) + it.each([ + [undefined, true], + [true, true], + [false, false], + ] as const)( + 'sets the license banner from licenseBanner=%s under Turbopack', + (licenseBanner, expected) => { + process.env.TURBOPACK = '1' + using setLicenseBanner = spyOn( + wasm, + 'setLicenseBanner', + ).mockReturnValue(undefined) + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + DevupUI({}, { licenseBanner }) + expect(setLicenseBanner).toHaveBeenCalledWith(expected) + }, + ) + it('numbers the files the scan finds, and survives a failing scan', () => { + process.env.TURBOPACK = '1' + const collectSpy = spyOn(importGraphModule, 'collectNumberedFiles') + const seedSpy = spyOn(wasm, 'seedFileMap').mockReturnValue(undefined) + try { + collectSpy.mockImplementation((options: any) => { + expect(options.roots).toEqual( + ['src', 'app', 'pages'].map((dir) => resolve(dir)), + ) + expect(options.toId(resolve('src', 'a.tsx'))).toBe('src/a.tsx') + return ['src/a.tsx'] + }) + DevupUI({}, { include: ['@acme/ui'] }) + expect(seedSpy).toHaveBeenCalledWith(['src/a.tsx']) + expect(collectSpy.mock.calls[0][0]).toMatchObject({ + include: ['@acme/ui'], + }) + collectSpy.mockImplementation(() => { + throw 'scan boom' + }) + const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) + try { + DevupUI({}, {}) + expect(warnSpy).toHaveBeenCalledWith( + '[devup-ui] Turbopack file numbering failed: scan boom. Stylesheet file numbers follow the order Turbopack compiles files in, so they can differ between builds of the same source.', + ) + } finally { + warnSpy.mockRestore() + } + } finally { + collectSpy.mockRestore() + seedSpy.mockRestore() + } + }) + it('reserves shared class slots in path order before next dev extracts', () => { + process.env.TURBOPACK = '1' + const reserve = mock() + const reservationSpy = spyOn( + importGraphModule, + 'createSharedSlotReservation', + ).mockReturnValue({ + dependencies: [], + packageManifests: [], + invalidate: mock(), + reserve, + }) + try { + // One-shot builds take their order from the sorted prewarm instead. + DevupUI({}) + expect(reservationSpy).not.toHaveBeenCalled() + + setNodeEnv('development') + DevupUI({}, { include: ['@acme/ui'], singleCss: true }) + // Into the app's own engine session, never the shared engine. + expect(reservationSpy).toHaveBeenCalledWith( + coordinatorModule.openCoordinatorCompiler('df', wasm), + ) + const [discovery, options] = reserve.mock.calls[0] as Parameters< + ReturnType< + typeof importGraphModule.createSharedSlotReservation + >['reserve'] + > + expect(discovery).toMatchObject({ + roots: ['src', 'app', 'pages'].map((dir) => resolve(dir)), + include: ['@acme/ui'], + cwd: process.cwd(), + tsconfigPath: resolve('tsconfig.json'), + package: '@devup-ui/react', + }) + // The coordinator's own filename and CSS directory for each file. + expect(discovery.toId?.(resolve('src', 'a.tsx'))).toBe('src/a.tsx') + expect(options).toMatchObject({ + singleCss: true, + importMainCssInCode: false, + importMainCssInCss: true, + }) + expect( + options.cssDir({ + filename: 'src/app/page.tsx', + physicalPath: resolve('src', 'app', 'page.tsx'), + code: '', + }), + ).toBe('./../../df/devup-ui') + + // A failing reservation leaves extraction in arrival order. + reserve.mockImplementation(() => { + throw new Error('reserve boom') + }) + const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}) + try { + expect(() => DevupUI({})).not.toThrow() + expect(warnSpy).toHaveBeenCalledWith( + '[devup-ui] Turbopack shared class-slot reservation failed: reserve boom. Classes several files share take their names in the order `next dev` extracts them, so they can differ between dev sessions.', + ) + } finally { + warnSpy.mockRestore() + } + } finally { + reservationSpy.mockRestore() + } + }) + describe('restoreSessionState', () => { + const files = ['sheet.json', 'classMap.json', 'fileMap.json'] as const + const engine = () => ({ + importSheet: mock(), + importClassMap: mock(), + importFileMap: mock(), + resetBuildState: mock(), + }) + + it('imports nothing unless every file reads', () => { + readFileSyncSpy.mockImplementation((path: string) => { + if (path === 'fileMap.json') throw new Error('ENOENT') + return '{}' + }) + const restored = engine() + restoreSessionState(restored, files) + expect(restored.importSheet).not.toHaveBeenCalled() + expect(restored.importClassMap).not.toHaveBeenCalled() + expect(restored.importFileMap).not.toHaveBeenCalled() + }) + + it('imports nothing when one file is corrupt', () => { + readFileSyncSpy.mockImplementation((path: string) => + path === 'classMap.json' ? '{"a":' : '{}', + ) + const restored = engine() + restoreSessionState(restored, files) + expect(restored.importSheet).not.toHaveBeenCalled() + }) + + it('drops a state that does not import', () => { + readFileSyncSpy.mockImplementation((path: string) => + JSON.stringify({ path }), + ) + const restored = engine() + restored.importClassMap.mockImplementation(() => { + throw new Error('older release') + }) + restoreSessionState(restored, files) + expect(restored.importSheet).toHaveBeenCalledWith({ + path: 'sheet.json', + }) + expect(restored.importFileMap).not.toHaveBeenCalled() + expect(restored.resetBuildState).toHaveBeenCalledTimes(1) + }) + }) + it('should import previous session state on restart', () => { + process.env.TURBOPACK = '1' + existsSyncSpy + .mockReturnValueOnce(true) // distDir + .mockReturnValueOnce(true) // cssDir + .mockReturnValueOnce(true) // gitignoreFile + .mockReturnValueOnce(false) // devupFile in loadDevupConfigSync + + // Simulate previous session state files on disk + const prevSheet = { + css: { a: 'color:red' }, + font_faces: {}, + global_css_files: [], + imports: {}, + keyframes: {}, + properties: {}, + } + const prevClassMap = { a: 0 } + const prevFileMap = { 'src/App.tsx': 0 } + + const files: Record = { + [join('df', 'sheet.json')]: JSON.stringify(prevSheet), + [join('df', 'classMap.json')]: JSON.stringify(prevClassMap), + [join('df', 'fileMap.json')]: JSON.stringify(prevFileMap), + } + readFileSyncSpy.mockImplementation((path: string) => files[path] ?? '{}') + + DevupUI({}) + + // Verify previous state was imported before registerTheme + expect(importSheetSpy).toHaveBeenCalledWith(prevSheet) + expect(importClassMapSpy).toHaveBeenCalledWith(prevClassMap) + expect(importFileMapSpy).toHaveBeenCalledWith(prevFileMap) + expect(registerThemeSpy).toHaveBeenCalledWith({}) + + // Verify stale port file was deleted before starting coordinator + expect(unlinkSyncSpy).toHaveBeenCalledWith(join('df', 'coordinator.port')) + }) + it('writes its own state next to another live process on the same distDir', () => { + process.env.TURBOPACK = '1' + const stateDir = join('df', `state.${process.pid}`) + const portSpy = spyOn( + coordinatorPortModule, + 'resolveCoordinatorPortFile', + ).mockReturnValue(join('df', `coordinator.${process.pid}.port`)) + const staleSpy = spyOn( + coordinatorPortModule, + 'removeStaleStateDirs', + ).mockReturnValue(undefined) + const prevSheet = { css: { a: 'color:red' } } + readFileSyncSpy.mockImplementation((path: string) => + path === join('df', 'sheet.json') ? JSON.stringify(prevSheet) : '{}', + ) + try { + const config = DevupUI({}) + + expect(staleSpy).toHaveBeenCalledWith('df') + expect(mkdirSyncSpy).toHaveBeenCalledWith(stateDir, { recursive: true }) + // It still restores what the shared state holds... + expect(importSheetSpy).toHaveBeenCalledWith(prevSheet) + // ...but writes only its own files. + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + coordinatorPortFile: join('df', `coordinator.${process.pid}.port`), + sheetFile: join(stateDir, 'sheet.json'), + classMapFile: join(stateDir, 'classMap.json'), + fileMapFile: join(stateDir, 'fileMap.json'), + }), + ) + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join(stateDir, 'canonicalMap.json'), + expect.any(String), + ) + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join(stateDir, 'setup.bin'), + expect.anything(), + ) + const rule = config.turbopack?.rules?.[ + '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}' + ] as { + loaders: { options: { sheetFile: string } }[] + } + expect(rule.loaders[0].options.sheetFile).toBe( + join(stateDir, 'sheet.json'), + ) + } finally { + portSpy.mockRestore() + staleSpy.mockRestore() + } + }) + it('should handle missing state files gracefully on first run', () => { + process.env.TURBOPACK = '1' + existsSyncSpy + .mockReturnValueOnce(false) // distDir — doesn't exist + .mockReturnValueOnce(false) // cssDir + .mockReturnValueOnce(false) // gitignoreFile + .mockReturnValueOnce(false) // devupFile + + // readFileSync throws for state files (they don't exist) + readFileSyncSpy.mockImplementation((path: string) => { + throw new Error(`ENOENT: no such file or directory, open '${path}'`) + }) + + // Should not throw — try-catch handles missing files + DevupUI({}) + + // importSheet should NOT have been called (readFileSync threw) + expect(importSheetSpy).not.toHaveBeenCalled() + expect(importClassMapSpy).not.toHaveBeenCalled() + expect(importFileMapSpy).not.toHaveBeenCalled() + + // registerTheme should still be called with empty theme + expect(registerThemeSpy).toHaveBeenCalledWith({}) + }) + it('should start coordinator in development mode', async () => { + process.env.TURBOPACK = '1' + setNodeEnv('development') + existsSyncSpy + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + writeFileSyncSpy.mockReturnValue(undefined) + + const closeMock = mock() as () => void + startCoordinatorSpy.mockReturnValue({ close: closeMock }) + + const exitHandlers: (() => void)[] = [] + const processOnSpy = spyOn(process, 'on').mockImplementation( + (event: string, handler: (...args: unknown[]) => void) => { + if (event === 'exit') exitHandlers.push(handler as () => void) + return process + }, + ) + + try { + DevupUI({}) + + // Verify coordinator was started with correct options + expect(startCoordinatorSpy).toHaveBeenCalledWith({ + distDir: 'df', + wasm: coordinatorModule.openCoordinatorCompiler('df', wasm), + package: '@devup-ui/react', + cssDir: resolve('df', 'devup-ui'), + singleCss: false, + sheetFile: join('df', 'sheet.json'), + classMapFile: join('df', 'classMap.json'), + fileMapFile: join('df', 'fileMap.json'), + importAliases: { + '@emotion/react': null, + '@emotion/styled': 'styled', + '@emotion/css': null, + '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, + 'styled-components': 'styled', + }, + coordinatorPortFile: join('df', 'coordinator.port'), + canonicalMap: expect.any(Object), + expectedBaseFiles: expect.any(Array), + prewarmedFiles: [], + prewarmedOutputs: expect.any(Map), + sourceMap: true, + theme: { + files: [resolve('devup.json')], + reload: expect.any(Function), + }, + }) + // The coordinator registers an edited theme through the same path. + const { theme } = startCoordinatorSpy.mock.calls[0]![0] as { + theme: { reload: () => string[] } + } + registerThemeSpy.mockClear() + expect(theme.reload()).toEqual([resolve('devup.json')]) + expect(registerThemeSpy).toHaveBeenCalledWith({}) + expect(codeExtractSpy).not.toHaveBeenCalled() + expect(codeExtractWithoutSourceMapSpy).not.toHaveBeenCalled() + + // Verify initial CSS file is written + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join(resolve('df', 'devup-ui'), 'devup-ui.css'), + '', + ) + + // Verify exit handler was registered and calls coordinator.close() + expect(exitHandlers.length).toBeGreaterThan(0) + exitHandlers[0]!() + expect(closeMock).toHaveBeenCalledTimes(1) + + // Verify --inspect-brk env vars are NOT set + expect(process.env.TURBOPACK_DEBUG_JS).toBeUndefined() + expect(process.env.NODE_OPTIONS ?? '').not.toContain('--inspect-brk') + } finally { + processOnSpy.mockRestore() + } + }) + + it('registers the Tailwind CSS theme and watches its files', () => { + process.env.TURBOPACK = '1' + const tailwindSpy = spyOn( + importGraphModule, + 'findTailwindCss', + ).mockReturnValue({ + file: resolve('app.css'), + files: [resolve('app.css'), resolve('tokens.css')], + css: '@import "tailwindcss";', + }) + try { + const config = DevupUI({}) + + expect(registerThemeSpy).toHaveBeenCalledWith({ + tailwindCss: '@import "tailwindcss";', + }) + const rule = config.turbopack?.rules?.[ + '*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}' + ] as { + loaders: { options: { themeFiles: string[] } }[] + } + expect(rule.loaders[0].options.themeFiles).toEqual([ + resolve('devup.json'), + resolve('app.css'), + resolve('tokens.css'), + ]) + } finally { + tailwindSpy.mockRestore() + } + }) + + it('hands the coordinator the full compiled-file set, not the static-only route map', () => { + process.env.TURBOPACK = '1' + process.env.DEVUP_UI_PROFILE = '1' + const profileSpy = spyOn(console, 'info').mockImplementation(() => {}) + // The base sheet must wait for lazily-loaded modules too, so + // expectedBaseFiles comes from computeCompiledFiles (static + dynamic + // edges) rather than computeFileRoutes (static edges only). Using the + // route map here served the sheet before any dynamic() module extracted. + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx', 'src/lazy/panel.tsx']) + const routesSpy = spyOn( + importGraphModule, + 'computeFileRoutes', + ).mockReturnValue({ 'src/app/page.tsx': [0] }) + const events: string[] = [] + codeExtractWithoutSourceMapSpy.mockImplementation( + (filename: string, contents: string) => { + events.push(`extract:${filename}`) + return Object.assign(createCodeExtractResult(contents), { + dependencies: [`${filename}.tokens.ts`], + }) + }, + ) + startCoordinatorSpy.mockImplementation(() => { + events.push('startCoordinator') + return { close: mock() as () => void } + }) + try { + DevupUI({}, { atomHoist: 0 }) + + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + expectedBaseFiles: ['src/app/page.tsx', 'src/lazy/panel.tsx'], + prewarmedFiles: ['src/app/page.tsx', 'src/lazy/panel.tsx'], + }), + ) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( + 'src/app/page.tsx', + '{}', + '@devup-ui/react', + expect.any(String), + false, + false, + true, + expect.anything(), + ) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( + 'src/lazy/panel.tsx', + '{}', + '@devup-ui/react', + expect.any(String), + false, + false, + true, + expect.anything(), + ) + expect(events).toEqual([ + 'extract:src/app/page.tsx', + 'extract:src/lazy/panel.tsx', + 'startCoordinator', + ]) + const coordinatorOptions = startCoordinatorSpy.mock.calls[0]?.[0] + expect(coordinatorOptions?.prewarmedOutputs).toEqual( + new Map([ + [ + 'src/app/page.tsx', + expect.objectContaining({ + code: '{}', + source: '{}', + dependencies: ['src/app/page.tsx.tokens.ts'], + }), + ], + [ + 'src/lazy/panel.tsx', + expect.objectContaining({ + code: '{}', + source: '{}', + dependencies: ['src/lazy/panel.tsx.tokens.ts'], + }), + ], + ]), + ) + const profiles: Record[] = profileSpy.mock.calls + .map(([value]) => value) + .filter( + (value): value is string => + typeof value === 'string' && + value.startsWith('[devup-ui:profile] '), + ) + .map((value) => JSON.parse(value.slice('[devup-ui:profile] '.length))) + const prewarmProfile = profiles.find( + ({ phase }) => phase === 'next.prewarm', + ) + expect(prewarmProfile).toMatchObject({ + collectMs: expect.any(Number), + extractMs: expect.any(Number), + files: 2, + phase: 'next.prewarm', + readMs: expect.any(Number), + sourceBytes: Buffer.byteLength('{}') * 2, + }) + expect(profiles).toEqual( + expect.arrayContaining([ + expect.objectContaining({ phase: 'next.initialCss' }), + expect.objectContaining({ phase: 'next.stateSnapshot' }), + expect.objectContaining({ phase: 'next.setup' }), + ]), + ) + // the static-only route map is not consulted outside atom-hoist mode + expect(routesSpy).not.toHaveBeenCalled() + } finally { + profileSpy.mockRestore() + compiledSpy.mockRestore() + routesSpy.mockRestore() + } + }) + + it('prewarms source candidates hidden from the route closure', () => { + process.env.TURBOPACK = '1' + const page = resolve('src/app/page.tsx') + const templateTarget = resolve('src/demos/template-target.tsx') + const graphSpy = spyOn( + importGraphModule, + 'buildStaticImportGraph', + ).mockReturnValue({ + files: [page, templateTarget], + fileSet: new Set([page, templateTarget]), + staticImports: new Map([ + [page, new Set()], + [templateTarget, new Set()], + ]), + staticImporters: new Map([ + [page, new Set()], + [templateTarget, new Set()], + ]), + dynamicTargets: new Set(), + dynamicImports: new Map([ + [page, new Set()], + [templateTarget, new Set()], + ]), + externalImports: new Map([ + [page, new Set()], + [templateTarget, new Set()], + ]), + }) + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx']) + try { + DevupUI({}) + + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + expectedBaseFiles: ['src/app/page.tsx'], + prewarmedFiles: [ + 'src/app/page.tsx', + 'src/demos/template-target.tsx', + ], + }), + ) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) + } finally { + graphSpy.mockRestore() + compiledSpy.mockRestore() + } + }) + + it('prewarms the same complete file set in singleCss mode', () => { + process.env.TURBOPACK = '1' + const compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/page.tsx', 'src/app/card.tsx']) + try { + DevupUI({}, { singleCss: true }) + + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledTimes(2) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( + 'src/app/card.tsx', + '{}', + '@devup-ui/react', + expect.any(String), + true, + false, + true, + expect.anything(), + ) + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + singleCss: true, + prewarmedFiles: ['src/app/card.tsx', 'src/app/page.tsx'], + }), + ) + } finally { + compiledSpy.mockRestore() + } + }) + + it('does not enable atom hoisting when atomHoist is explicitly zero', () => { + process.env.TURBOPACK = '1' + const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( + undefined, + ) + const importFileRoutesSpy = spyOn( + wasm, + 'importFileRoutes', + ).mockReturnValue(undefined) + const importCanonicalMapSpy = spyOn( + wasm, + 'importCanonicalMap', + ).mockReturnValue(undefined) + try { + DevupUI({}, { atomHoist: 0 }) + expect(setAtomHoistSpy).not.toHaveBeenCalled() + expect(importFileRoutesSpy).not.toHaveBeenCalled() + // single-importer collapse still runs (it is the always-on default) + expect(importCanonicalMapSpy).toHaveBeenCalled() + } finally { + setAtomHoistSpy.mockRestore() + importFileRoutesSpy.mockRestore() + importCanonicalMapSpy.mockRestore() + } + }) + + describe('default regressions', () => { + let canonicalSpy: ReturnType + let routesSpy: ReturnType + let compiledSpy: ReturnType + let importRoutesSpy: ReturnType + let thresholdSpy: ReturnType + + beforeEach(() => { + process.env.TURBOPACK = '1' + setNodeEnv('production') + canonicalSpy = spyOn( + importGraphModule, + 'buildCanonicalMap', + ).mockReturnValue({}) + routesSpy = spyOn( + importGraphModule, + 'computeFileRoutes', + ).mockReturnValue({ + 'src/app/layout.tsx': [0, 1], + 'src/app/a/page.tsx': [0], + 'src/app/b/page.tsx': [1], + }) + compiledSpy = spyOn( + importGraphModule, + 'computeCompiledFiles', + ).mockReturnValue(['src/app/a/page.tsx', 'src/app/b/page.tsx']) + importRoutesSpy = spyOn(wasm, 'importFileRoutes').mockReturnValue( + undefined, + ) + thresholdSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue(undefined) + }) + + afterEach(() => { + canonicalSpy.mockRestore() + routesSpy.mockRestore() + compiledSpy.mockRestore() + importRoutesSpy.mockRestore() + thresholdSpy.mockRestore() + }) + + it.each([undefined, 0, -1, NaN, Infinity, -Infinity, 0.5, 1, 2, 3])( + 'availability: keeps per-file mode for request %s', + (atomHoist) => { + // Given: multi-route reach and legacy whole-file hoisting are available. + process.env.DEVUP_HOIST_V = '3' + const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) + try { + // When: Turbopack receives the numeric request. + DevupUI({}, { atomHoist }) + // Then: only explicit finite positive requests warn; none install atoms. + expect(routesSpy).not.toHaveBeenCalled() + expect(importRoutesSpy).not.toHaveBeenCalled() + expect(thresholdSpy).not.toHaveBeenCalled() + expect(canonicalSpy).toHaveBeenCalledWith( + expect.objectContaining({ hoistV: 3 }), + ) + expect(warningSpy).toHaveBeenCalledTimes( + atomHoist !== undefined && + Number.isFinite(atomHoist) && + atomHoist > 0 + ? 1 + : 0, + ) + } finally { + warningSpy.mockRestore() + } + }, + ) + + it.each([ + ['omitted', {}], + ['undefined', { atomHoist: undefined }], + ])( + 'keeps omitted atomHoist %s silent without consulting route reach', + (_label, options) => { + const warningSpy = spyOn(console, 'warn').mockImplementation(() => {}) + try { + DevupUI({}, options) + expect(routesSpy).not.toHaveBeenCalled() + expect(importRoutesSpy).not.toHaveBeenCalled() + expect(thresholdSpy).not.toHaveBeenCalled() + expect(warningSpy).not.toHaveBeenCalled() + } finally { + warningSpy.mockRestore() + } + }, + ) + + it.each([0, -1, NaN, Infinity, -Infinity])( + 'keeps legacy OFF for atomHoist %s', + (atomHoist) => { + // Given: a valid multi-route fixture, so fallback cannot hide enabling. + // When: an explicitly disabled numeric option is supplied. + DevupUI({}, { atomHoist }) + // Then: collapse remains active but atom reach is not consulted. + expect(canonicalSpy).toHaveBeenCalled() + expect(routesSpy).not.toHaveBeenCalled() + expect(importRoutesSpy).not.toHaveBeenCalled() + expect(thresholdSpy).not.toHaveBeenCalled() + }, + ) + + it('defers a custom threshold above the minimum until reservation lands', () => { + // Given: two routes; the threshold must not be replaced by the default. + // When: the caller requests three routes. + DevupUI({}, { atomHoist: 3 }) + // Then: unavailable atom hoisting never installs a threshold. + expect(thresholdSpy).not.toHaveBeenCalled() + expect(routesSpy).not.toHaveBeenCalled() + }) + + it.each([ + ['omitted', {}], + ['undefined', { atomHoist: undefined }], + ['enabled', { atomHoist: 2 }], + ])( + 'ignores %s atomHoist before planning in actual singleCss mode', + (_label, options) => { + // Given: legacy whole-file hoisting and an explicit-OFF single sheet. + process.env.DEVUP_HOIST_V = '3' + const off = DevupUI({}, { singleCss: true, atomHoist: 0 }) + const offExtractions = [...codeExtractWithoutSourceMapSpy.mock.calls] + expect(offExtractions).toHaveLength(2) + codeExtractWithoutSourceMapSpy.mockClear() + canonicalSpy.mockClear() + + // When: only the atom option changes. + const on = DevupUI({}, { singleCss: true, ...options }) + + // Then: reach/threshold, legacy policy, IDs, imports and loader config agree. + expect(routesSpy).not.toHaveBeenCalled() + expect(importRoutesSpy).not.toHaveBeenCalled() + expect(thresholdSpy).not.toHaveBeenCalled() + expect(canonicalSpy).toHaveBeenCalledWith( + expect.objectContaining({ hoistV: 3 }), + ) + expect(codeExtractWithoutSourceMapSpy.mock.calls).toEqual( + offExtractions, + ) + expect(codeExtractWithoutSourceMapSpy).toHaveBeenCalledWith( + 'src/app/a/page.tsx', + '{}', + '@devup-ui/react', + expect.any(String), + true, + false, + true, + expect.anything(), + ) + expect(on.turbopack?.rules).toEqual(off.turbopack?.rules) + }, + ) + }) + + it('preserves single-importer collapse but defers atom reach when atomHoist is set', () => { + process.env.TURBOPACK = '1' + // 4 distinct leaf routes (ids 0..3); layout shared by all four. + const computeSpy = spyOn( + importGraphModule, + 'computeFileRoutes', + ).mockReturnValue({ + 'src/app/layout.tsx': [0, 1, 2, 3], + 'src/app/a/page.tsx': [0], + 'src/app/b/page.tsx': [1], + 'src/app/c/page.tsx': [2], + 'src/app/d/page.tsx': [3], + }) + const importFileRoutesSpy = spyOn( + wasm, + 'importFileRoutes', + ).mockReturnValue(undefined) + const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( + undefined, + ) + // Collapse must still run while atom hoisting is unavailable. + const importCanonicalMapSpy = spyOn( + wasm, + 'importCanonicalMap', + ).mockReturnValue(undefined) + try { + DevupUI({}, { atomHoist: 2 }) + expect(computeSpy).not.toHaveBeenCalled() + expect(importFileRoutesSpy).not.toHaveBeenCalled() + expect(setAtomHoistSpy).not.toHaveBeenCalled() + // composition: collapse pre-pass also ran + expect(importCanonicalMapSpy).toHaveBeenCalled() + } finally { + computeSpy.mockRestore() + importFileRoutesSpy.mockRestore() + setAtomHoistSpy.mockRestore() + importCanonicalMapSpy.mockRestore() + } + }) + + it('defers even the former minimum-clamped atomHoist request', () => { + process.env.TURBOPACK = '1' + const computeSpy = spyOn( + importGraphModule, + 'computeFileRoutes', + ).mockReturnValue({ + 'src/app/a/page.tsx': [0], + 'src/app/b/page.tsx': [1], + }) + const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( + undefined, + ) + try { + DevupUI({}, { atomHoist: 1 }) + expect(computeSpy).not.toHaveBeenCalled() + expect(setAtomHoistSpy).not.toHaveBeenCalled() + } finally { + computeSpy.mockRestore() + setAtomHoistSpy.mockRestore() + } + }) + + it('keeps atom hoisting off when fewer than two routes exist', () => { + process.env.TURBOPACK = '1' + const computeSpy = spyOn( + importGraphModule, + 'computeFileRoutes', + ).mockReturnValue({ 'src/app/a/page.tsx': [0] }) + const setAtomHoistSpy = spyOn(wasm, 'setAtomHoist').mockReturnValue( + undefined, + ) + try { + DevupUI({}, { atomHoist: 2 }) + expect(setAtomHoistSpy).not.toHaveBeenCalled() + } finally { + computeSpy.mockRestore() + setAtomHoistSpy.mockRestore() + } + }) + }) +}) diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index a9dc21d09..c2b65172e 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -26,9 +26,12 @@ import { normalizeShorthands, normalizeStylexOptions, readJsxImportSource, + readSource, seedFileNumbers, + type SourceCache, type StaticImportGraph, type WasmImportAliases, + withSourceCache, } from '@devup-ui/plugin-utils' import { type NextConfig } from 'next' @@ -427,13 +430,18 @@ export function DevupUI( // `[]` (idle fallback) when no routes are detected or the pre-pass fails. let expectedBaseFiles: string[] = [] let staticGraph: StaticImportGraph | undefined + // The graph and the prewarm read the same sources + const sourceCache: SourceCache = new Map() const graphStartedAt = profileStart() try { const srcDir = sourceDir(process.cwd()) const tsconfigPath = resolve(process.cwd(), 'tsconfig.json') const cwd = process.cwd() // One scan+parse of the source tree, shared by all three consumers below. - const graph = buildStaticImportGraph(srcDir, tsconfigPath) + const graph = withSourceCache( + () => buildStaticImportGraph(srcDir, tsconfigPath), + sourceCache, + ) staticGraph = graph const hoistV = process.env.DEVUP_HOIST_V ? Number(process.env.DEVUP_HOIST_V) @@ -538,13 +546,18 @@ export function DevupUI( const cwd = process.cwd() const collectStartedAt = prewarmStartedAt === undefined ? undefined : performance.now() - const prewarmFiles = collectProductionPrewarmFiles({ - cwd, - graph: staticGraph, - expectedBaseFiles, - libPackage, - include, - }) + const graph = staticGraph + const prewarmFiles = withSourceCache( + () => + collectProductionPrewarmFiles({ + cwd, + graph, + expectedBaseFiles, + libPackage, + include, + }), + sourceCache, + ) const collectDurationMs = elapsedMs(collectStartedAt) for (const filename of prewarmFiles) { const resourcePath = resolve(cwd, filename) @@ -554,7 +567,10 @@ export function DevupUI( ).replaceAll('\\', '/')}` const readStartedAt = prewarmStartedAt === undefined ? undefined : performance.now() - const source = readFileSync(resourcePath, 'utf-8') + const source = withSourceCache( + () => readSource(resourcePath), + sourceCache, + ) if (readStartedAt !== undefined) { prewarmReadMs += performance.now() - readStartedAt prewarmSourceBytes += Buffer.byteLength(source) @@ -794,6 +810,9 @@ export function DevupUI( const { webpack } = config let productionPrewarmFiles: readonly string[] | undefined + // A production build runs its compilers in turn: their plugins read each + // source once + const sourceCache: SourceCache = new Map() config.webpack = (config, _options) => { const { DevupUIWebpackPlugin } = loadWebpackPlugin() // Next's project directory, which it also hands webpack as `context`: the @@ -808,19 +827,21 @@ export function DevupUI( const cwd = root const srcDir = sourceDir(cwd) const tsconfigPath = resolve(cwd, 'tsconfig.json') - const graph = buildStaticImportGraph(srcDir, tsconfigPath) - productionPrewarmFiles = collectProductionPrewarmFiles({ - cwd, - graph, - expectedBaseFiles: computeCompiledFiles({ + productionPrewarmFiles = withSourceCache(() => { + const graph = buildStaticImportGraph(srcDir, tsconfigPath) + return collectProductionPrewarmFiles({ cwd, - srcDir, - tsconfigPath, graph, - }), - libPackage: options.package ?? '@devup-ui/react', - include: options.include ?? [], - }) + expectedBaseFiles: computeCompiledFiles({ + cwd, + srcDir, + tsconfigPath, + graph, + }), + libPackage: options.package ?? '@devup-ui/react', + include: options.include ?? [], + }) + }, sourceCache) } config.plugins.push( new DevupUIWebpackPlugin({ @@ -830,6 +851,7 @@ export function DevupUI( productionPrewarmFiles: _options.dev ? undefined : productionPrewarmFiles, + sourceCache: _options.dev ? undefined : sourceCache, }), ) if (typeof webpack === 'function') return webpack(config, _options) diff --git a/packages/next-plugin/src/prewarm.ts b/packages/next-plugin/src/prewarm.ts index 8564ed492..cf74392ea 100644 --- a/packages/next-plugin/src/prewarm.ts +++ b/packages/next-plugin/src/prewarm.ts @@ -1,9 +1,10 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import { extname, isAbsolute, relative, resolve } from 'node:path' import { createModuleResolver, parseImports, + readSource, SOURCE_FILE_REGEX, type StaticImportGraph, } from '@devup-ui/plugin-utils' @@ -100,8 +101,7 @@ export function collectProductionPrewarmFiles({ if (!SOURCE_FILE_REGEX.test(filename) || visited.has(filename)) continue visited.add(filename) files.add(toKey(resolvedCwd, filename)) - const source = - filename === module.path ? module.code : readFileSync(filename, 'utf-8') + const source = filename === module.path ? module.code : readSource(filename) for (const imported of parseImports(filename, source)) { queue.push({ importer: filename, specifier: imported.specifier }) } diff --git a/packages/plugin-utils/src/__tests__/source-cache.test.ts b/packages/plugin-utils/src/__tests__/source-cache.test.ts new file mode 100644 index 000000000..4de17fd6a --- /dev/null +++ b/packages/plugin-utils/src/__tests__/source-cache.test.ts @@ -0,0 +1,103 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it } from 'bun:test' + +import { + fileStamp, + readSource, + type SourceCache, + withSourceCache, +} from '../source-cache' + +describe('readSource', () => { + let dir: string + let file: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'devup-ui-source-cache-')) + file = join(dir, 'a.tsx') + writeFileSync(file, 'on disk') + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + /** A cache already holding `code` for the file as it is now */ + function holding(code: string): SourceCache { + return new Map([[resolve(file), { stamp: fileStamp(file) ?? '', code }]]) + } + + it('reads the disk outside a cache', () => { + expect(readSource(file)).toBe('on disk') + expect(globalThis.__devupSourceCache).toBeUndefined() + }) + + it('serves an unchanged file from the cache, under any spelling of its path', () => { + // Given + const cache = holding('cached') + // When + const read = withSourceCache( + () => [readSource(file), readSource(join(dir, '.', 'a.tsx'))], + cache, + ) + // Then + expect(read).toEqual(['cached', 'cached']) + }) + + it('reads a changed file again and keeps it', () => { + // Given + const cache = holding('stale') + // When + writeFileSync(file, 'changed text') + // Then + expect(withSourceCache(() => readSource(file), cache)).toBe('changed text') + expect(cache.get(resolve(file))).toEqual({ + stamp: fileStamp(file) ?? '', + code: 'changed text', + }) + }) + + it('reads a file once into an empty cache', () => { + const cache: SourceCache = new Map() + expect(withSourceCache(() => readSource(file), cache)).toBe('on disk') + expect(cache.get(resolve(file))?.code).toBe('on disk') + }) + + it('reports a deleted file and forgets it', () => { + // Given + const cache = holding('cached') + // When + rmSync(file) + // Then + expect(() => withSourceCache(() => readSource(file), cache)).toThrow() + expect(cache.size).toBe(0) + }) + + it('keeps the outer cache in a nested run and restores none after', () => { + // Given + const outer: SourceCache = new Map() + const inner: SourceCache = new Map() + // When + withSourceCache(() => withSourceCache(() => readSource(file), inner), outer) + // Then + expect(outer.size).toBe(1) + expect(inner.size).toBe(0) + expect(globalThis.__devupSourceCache).toBeUndefined() + }) + + it('restores the outer cache when the run throws', () => { + expect(() => + withSourceCache(() => { + throw new Error('boom') + }, new Map()), + ).toThrow('boom') + expect(globalThis.__devupSourceCache).toBeUndefined() + }) + + it('stamps no missing file', () => { + expect(fileStamp(join(dir, 'missing.tsx'))).toBeUndefined() + }) +}) diff --git a/packages/plugin-utils/src/import-graph.ts b/packages/plugin-utils/src/import-graph.ts index 30c341b0c..246a0a782 100644 --- a/packages/plugin-utils/src/import-graph.ts +++ b/packages/plugin-utils/src/import-graph.ts @@ -18,6 +18,7 @@ import { } from 'node:path' import { PackageManifestShapeError } from './package-manifest' +import { fileStamp, readSource } from './source-cache' import { SOURCE_EXTENSIONS, SOURCE_FILE_REGEX, @@ -175,7 +176,7 @@ export function buildStaticImportGraph( } for (const file of files) { - const imports = parseImports(file, readFileSync(file, 'utf-8')) + const imports = parseImports(file, readSource(file)) for (const importRef of imports) { const target = resolveImport(importRef.specifier, file, context) if (!target) { @@ -1239,11 +1240,11 @@ export function createModuleResolver({ return path } /** The file's code, read again only once its stamp changes. */ - const readSource = (path: string) => { + const readCode = (path: string) => { const stamp = fileStamp(path) const cached = sources.get(path) if (cached && cached.stamp === stamp) return cached.code - const code = readFileSync(path, 'utf-8') + const code = readSource(path) sources.set(path, { stamp, code }) return code } @@ -1262,29 +1263,19 @@ export function createModuleResolver({ ((allowPackage?.(specifier) ?? true) ? resolveCachedPackage(specifier, from) : undefined)) - return path ? { path: toId(path), code: readSource(path) } : undefined + return path ? { path: toId(path), code: readCode(path) } : undefined } } -interface CachedPackage { - manifest: string - stamp: string | undefined - path: string -} - interface CachedSource { stamp: string | undefined code: string } -/** Changes whenever the file is written; `undefined` once it is gone. */ -function fileStamp(path: string): string | undefined { - try { - const { mtimeNs, ctimeNs, size } = statSync(path, { bigint: true }) - return `${mtimeNs}:${ctimeNs}:${size}` - } catch { - return undefined - } +interface CachedPackage { + manifest: string + stamp: string | undefined + path: string } /** `resolveFile`, also completing a name like `theme.css` to `theme.css.ts`. */ diff --git a/packages/plugin-utils/src/index.ts b/packages/plugin-utils/src/index.ts index 469daa733..4508c4b8e 100644 --- a/packages/plugin-utils/src/index.ts +++ b/packages/plugin-utils/src/index.ts @@ -100,6 +100,7 @@ export { ShorthandConfigError, type ShorthandErrorLocation, } from './shorthands' +export { readSource, type SourceCache, withSourceCache } from './source-cache' export { SOURCE_EXTENSIONS, SOURCE_FILE_REGEX } from './source-extensions' export { createStateWriter, diff --git a/packages/plugin-utils/src/reservation-discovery.ts b/packages/plugin-utils/src/reservation-discovery.ts index 670aa29c9..b66aec437 100644 --- a/packages/plugin-utils/src/reservation-discovery.ts +++ b/packages/plugin-utils/src/reservation-discovery.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { contextImports } from './context-imports' @@ -14,6 +13,7 @@ import { reservationSource, } from './reservation-source' import { createNodeModulesExcludeRegex } from './shared' +import { readSource } from './source-cache' import type { WasmImportAliases } from './types' export type ReservationInput = { @@ -151,7 +151,7 @@ export function collectReservationInputs( const code = overlay?.code ?? sources.get(key) ?? - reservationSource(() => readFileSync(physicalPath, 'utf-8')) + reservationSource(() => readSource(physicalPath)) if (code === undefined) continue const filename = overlay?.filename ?? toId(physicalPath) sources.set(key, code) diff --git a/packages/plugin-utils/src/source-cache.ts b/packages/plugin-utils/src/source-cache.ts new file mode 100644 index 000000000..86fcbd33c --- /dev/null +++ b/packages/plugin-utils/src/source-cache.ts @@ -0,0 +1,65 @@ +import { readFileSync, statSync } from 'node:fs' +import { resolve } from 'node:path' + +interface CachedSource { + readonly stamp: string + readonly code: string +} + +/** The sources one build has read, by absolute path */ +export type SourceCache = Map + +declare global { + var __devupSourceCache: SourceCache | undefined +} + +/** Changes whenever the file is written; `undefined` once it is gone. */ +export function fileStamp(path: string): string | undefined { + try { + const { mtimeNs, ctimeNs, size } = statSync(path, { bigint: true }) + return `${mtimeNs}:${ctimeNs}:${size}` + } catch { + return undefined + } +} + +/** + * Run `run` with `cache` holding the sources it reads through `readSource`, + * so the passes of one build that run before the bundler (the import graph, + * the class-slot reservation, the prewarm; in Next once per compiler) read + * each file from disk once. Only a one-shot build passes one cache to several + * runs: in watch mode each run starts from a fresh one, as without it. A run + * inside another uses the outer cache. The plugins and their loaders load + * separate copies of this module, so the active cache lives on `globalThis`. + */ +export function withSourceCache(run: () => T, cache: SourceCache): T { + const outer = globalThis.__devupSourceCache + globalThis.__devupSourceCache = outer ?? cache + try { + return run() + } finally { + globalThis.__devupSourceCache = outer + } +} + +/** + * The UTF-8 text of `path`. Inside `withSourceCache` it is read from disk + * again only once the file changes: checking its stamp costs a fraction of + * reading it. + */ +export function readSource(path: string): string { + const cache = globalThis.__devupSourceCache + if (cache === undefined) return readFileSync(path, 'utf-8') + const key = resolve(path) + const stamp = fileStamp(key) + if (stamp === undefined) { + // Gone: the read reports why, as it would without the cache + cache.delete(key) + return readFileSync(key, 'utf-8') + } + const cached = cache.get(key) + if (cached?.stamp === stamp) return cached.code + const code = readFileSync(key, 'utf-8') + cache.set(key, { stamp, code }) + return code +} diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index ca2499b9d..0b0ab4b47 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -1514,6 +1514,32 @@ describe('devupUIWebpackPlugin', () => { } }) + it("prewarms from the build's shared sources, read once by an earlier compiler", () => { + // Given a source an earlier compiler of the build already read. + const file = import.meta.path + const sourceCache: pluginUtils.SourceCache = new Map() + pluginUtils.withSourceCache( + () => pluginUtils.readSource(file), + sourceCache, + ) + const [[key, entry]] = [...sourceCache] + sourceCache.set(key, { ...entry, code: 'read before' }) + const plugin = new DevupUIWebpackPlugin({ + engine: 'wasm', + productionPrewarmFiles: [file], + sourceCache, + }) + const compiler = createCompiler() + // When this compiler prepares its compilation. + plugin.apply(asCompiler(compiler)) + compiler.hooks.run.tap.mock.calls[0][1]() + // Then it extracts what was read, without reading the file again. + expect(codeExtractSpy.mock.calls.map(([, code]) => code)).toEqual([ + 'read before', + ]) + expect(globalThis.__devupSourceCache).toBeUndefined() + }) + it.each([false, true])( 'does not prewarm when the complete set is empty or watch=%s', (watch) => { diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 7874c3b83..f39f519c1 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -31,15 +31,18 @@ import { normalizeStylexOptions, planAtomHoist, readJsxImportSource, + readSource, registerMarkerLedger, resolveDevupFile, resolveProjectPath, seedFileNumbers, setupWarning, SOURCE_FILE_REGEX, + type SourceCache, type StylexStyleResolution, tailwindCssFiles, type WasmImportAliases, + withSourceCache, withTailwindCss, } from '@devup-ui/plugin-utils' import { type Compiler, type RuleSetRule } from 'webpack' @@ -83,6 +86,12 @@ export interface DevupUIWebpackPluginOptions extends Pick< importAliases?: ImportAliases /** Adapter-owned complete extraction set; undefined keeps generic entry reachability. */ readonly productionPrewarmFiles?: readonly string[] + /** + * Adapter-owned: the sources a one-shot build read, shared by the plugins of + * its compilers so each file is read once. Undefined reads them again for + * every compiler and compilation. + */ + readonly sourceCache?: SourceCache } export class DevupUIWebpackPlugin { @@ -103,6 +112,7 @@ export class DevupUIWebpackPlugin { private root = process.cwd() /** What the scan and the loaders report of component-selector markers */ private readonly markers = new ComponentMarkerLedger() + private readonly sourceCache: SourceCache | undefined constructor({ package: libPackage = '@devup-ui/react', @@ -120,8 +130,10 @@ export class DevupUIWebpackPlugin { stylex, atomHoist = 2, productionPrewarmFiles, + sourceCache, importAliases: userImportAliases, }: Partial = {}) { + this.sourceCache = sourceCache this.normalizedShorthands = normalizeShorthands(shorthands ?? {}) this.styleResolution = normalizeStylexOptions(stylex) this.compiler = loadCompiler(engine) @@ -314,7 +326,7 @@ export class DevupUIWebpackPlugin { if (!relCssDir.startsWith('./')) relCssDir = `./${relCssDir}` const output = this.compiler.codeExtract( relativePath, - readFileSync(file, 'utf-8'), + readSource(file), this.options.package, relCssDir, this.options.singleCss, @@ -362,7 +374,10 @@ export class DevupUIWebpackPlugin { const endBuild = beginBuild(this.compiler) try { compiler.hooks.shutdown?.tap('DevupUIWebpackPlugin', endBuild) - this.initialize(compiler) + withSourceCache( + () => this.initialize(compiler), + this.sourceCache ?? new Map(), + ) } catch (error) { // Webpack cannot return the compiler when apply throws, so no caller can close it. endBuild() @@ -525,7 +540,8 @@ export class DevupUIWebpackPlugin { this.compiler, ) registerMarkerLedger(compiler, this.markers) - const reserveBeforeCompile = () => { + // The reservation and the prewarm read the same sources + const prepare = () => { this.markers.clear() reserve(compiler.options) this.markers.scanned( @@ -543,6 +559,8 @@ export class DevupUIWebpackPlugin { compiler.options, ) } + const reserveBeforeCompile = () => + withSourceCache(prepare, this.sourceCache ?? new Map()) compiler.hooks.run.tap( 'DevupUIWebpackPluginReservation', reserveBeforeCompile, From 7ae9121e41249a35d0e09d280b6313ede55b41fd Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Thu, 19 Nov 2026 16:53:08 +0900 Subject: [PATCH 2/2] test(next-plugin): read the one-route layout from the coordinator options The Turbopack loader options no longer carry singleCss (#1036), so the one-route test (#1035) checks what the coordinator extracts into. Co-Authored-By: Claude Opus 5.5 --- .../next-plugin/src/__tests__/plugin.test.ts | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index 4348ee4f7..8f54fa9c8 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -695,19 +695,11 @@ describe('DevupUINextPlugin', () => { ).mockReturnValue(true) try { // When - const config = DevupUI({}, options) as { - turbopack: { - rules: Record< - string, - { loaders: { options: { singleCss: boolean } }[] } - > - } - } - // Then the loaders extract into the layout chosen - expect( - config.turbopack.rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'] - .loaders[0].options.singleCss, - ).toBe(expected) + DevupUI({}, options) + // Then the coordinator extracts into the layout chosen + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ singleCss: expected }), + ) } finally { singleRoute.mockRestore() graphSpy.mockRestore()