diff --git a/.changepacks/changepack_log_theme_errors_fail_build.json b/.changepacks/changepack_log_theme_errors_fail_build.json new file mode 100644 index 000000000..c06990a02 --- /dev/null +++ b/.changepacks/changepack_log_theme_errors_fail_build.json @@ -0,0 +1,11 @@ +{ + "changes": { + "packages/vite-plugin/package.json": "Patch", + "packages/webpack-plugin/package.json": "Patch", + "packages/rsbuild-plugin/package.json": "Patch", + "packages/next-plugin/package.json": "Patch", + "packages/bun-plugin/package.json": "Patch" + }, + "note": "A theme that cannot be loaded or registered (a broken `devup.json`, an invalid token name, or two token kinds that become the same CSS variable) now fails production builds with that error instead of building with an empty theme. Dev servers and watch builds keep running on an empty theme and report the error: Vite shows it in the error overlay in place of the reload, webpack, Next.js (webpack) and Rsbuild add it to every compilation's errors until it is fixed, and a Bun reload logs it", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 3d8ffb172..9d656825a 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -312,16 +312,75 @@ describe('registered Bun hooks', () => { expect(mkdir).not.toHaveBeenCalled() }) - it('registers an empty theme when reading configuration fails', async () => { + it('fails registration when reading configuration fails', async () => { exists.mockReturnValue(true) const error = new Error('unreadable fixture config') readConfig.mockRejectedValue(error) const logged = spyOn(console, 'error').mockReturnValue(undefined) + try { + await expect(register({ engine: 'wasm' })).rejects.toBe(error) + hooks.expectedErrors.add(error) + expect(logged).not.toHaveBeenCalled() + } finally { + logged.mockRestore() + } + }) + + it('fails registration when the theme cannot be registered', async () => { + exists.mockReturnValue(true) + readConfig.mockResolvedValue( + '{"theme":{"colors":{"default":{"card":"#fff"}},"shadows":{"default":{"card":"0 1px #000"}}}}', + ) + const clash = new Error('clash') + const registration = spyOn(wasm, 'registerTheme').mockImplementationOnce( + () => { + throw clash + }, + ) + try { + await expect(register({ engine: 'wasm' })).rejects.toBe(clash) + hooks.expectedErrors.add(clash) + expect(registration).toHaveBeenCalledTimes(1) + } finally { + registration.mockRestore() + } + }) + + it('reports a failed reload of a changed Tailwind CSS and clears the theme', async () => { + const tailwind = join(root, 'reload-tailwind.css') + await Bun.write(tailwind, '@theme { --color-brand: #0af; }') + const listeners: (() => void)[] = [] + const watching = spyOn(fs, 'watch').mockImplementation((( + _file: string, + _options: object, + listener: () => void, + ) => { + listeners.push(listener) + return { on() {}, close() {} } + }) as unknown as typeof fs.watch) + exists.mockReturnValue(true) + readConfig.mockResolvedValueOnce( + JSON.stringify({ + tailwind: { css: tailwind }, + theme: { colors: { default: { primary: '#123456' } } }, + }), + ) + const error = new Error('broken devup.json') + readConfig.mockRejectedValueOnce(error) + const logged = spyOn(console, 'error').mockReturnValue(undefined) try { await register({ engine: 'wasm' }) - expect(wasm.getDefaultTheme()).toBeUndefined() + expect(wasm.getDefaultTheme()).toBe('default') + expect(listeners).toHaveLength(1) + + listeners[0]!() + for (let tick = 0; tick < 100 && logged.mock.calls.length === 0; tick++) + await Bun.sleep(1) + expect(logged).toHaveBeenCalledWith(error) + expect(wasm.getDefaultTheme()).toBeUndefined() } finally { + watching.mockRestore() logged.mockRestore() } }) diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index f85f7fe90..0e2b55754 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -56,19 +56,26 @@ export interface DevupUIBunPluginOptions { type SourceLoader = 'tsx' | 'ts' | 'jsx' | 'js' -async function writeDataFiles(compiler: DevupCompiler): Promise { - let theme = {} +/** + * Load devup.json into the compiler. The first load fails on a theme that + * cannot be loaded or registered: Bun runs once, and an empty theme would + * leave every token unstyled. A reload for a changed Tailwind CSS runs in a + * process that is already up, so it reports the error and clears the theme. + */ +async function writeDataFiles( + compiler: DevupCompiler, + reloading = false, +): Promise { let tailwindFiles: string[] = [] try { const config = await loadDevupConfig(devupFile) - theme = withTailwindCss(config.theme ?? {}, config) tailwindFiles = tailwindCssFiles(config) + compiler.registerTheme(withTailwindCss(config.theme ?? {}, config)) } catch (error) { - // A broken devup.json clears the theme, as in the other plugins; the - // error says which file and how to fix it. + if (!reloading) throw error console.error(error) + compiler.registerTheme({}) } - compiler.registerTheme(theme) // Generate theme interface after registration (always write, even if empty) await writeFile( @@ -178,8 +185,8 @@ async function loadSourceFile( function DevupUI(options: DevupUIBunPluginOptions = {}) { const shorthands = normalizeShorthands(options.shorthands ?? {}) const compiler = loadCompiler(options.engine) - const watchTailwindCss = createTailwindWatcher( - writeDataFiles.bind(undefined, compiler), + const watchTailwindCss = createTailwindWatcher(() => + writeDataFiles(compiler, true), ) return { name: 'devup-ui', diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 07834754b..caf8b5d04 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -280,28 +280,164 @@ describe('DevupUIRsbuildPlugin', () => { expect(writeFileSyncSpy).not.toHaveBeenCalled() }) - it('should error when write data files', async () => { + it.each([ + ['rsbuild build', 'build'], + ['an rsbuild without an action', undefined], + ])('fails %s on a theme error', async (_name, action) => { const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined) try { - readFileSpy.mockRejectedValueOnce('error') - existsSyncSpy.mockImplementation((path: string) => { - if (path === 'devup.json') return true - return false + const clash = new Error( + "theme: color token 'card' and shadow token 'card' both become the CSS variable --card", + ) + registerThemeSpy.mockImplementationOnce(() => { + throw clash }) - const plugin = DevupUI() - expect(plugin).toBeDefined() - expect(plugin.setup).toBeDefined() + existsSyncSpy.mockImplementation((path: string) => path === 'devup.json') const transform = mock() - const modifyRsbuildConfig = mock() - await plugin.setup( - createSetupContext({ - transform, - modifyRsbuildConfig, - }), + + await expect( + DevupUI().setup( + createSetupContext({ + transform, + context: { rootPath: process.cwd(), action }, + } as Partial), + ), + ).rejects.toBe(clash) + + expect(console.error).not.toHaveBeenCalled() + expect(transform).not.toHaveBeenCalled() + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it.each([ + ['an Error', new Error('bad token'), '[devup-ui] bad token'], + ['a thrown string', 'error', '[devup-ui] error'], + ])( + 'reports a theme error that is %s in every dev compilation until it loads again', + async (_name, thrown, message) => { + const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined) + const statSpy = spyOn(fsPromises, 'stat') + const readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue( + '@theme { --color-brand: #0af; }', ) - expect(console.error).toHaveBeenCalledWith('error') + try { + registerThemeSpy.mockImplementationOnce(() => { + throw thrown + }) + readFileSpy.mockResolvedValue( + JSON.stringify({ tailwind: { css: 'tailwind.css' } }), + ) + existsSyncSpy.mockImplementation( + (path: string) => path === 'devup.json', + ) + const modifyRspackConfig = mock() + await DevupUI({ atomHoist: 0 }).setup( + createSetupContext({ + modifyRspackConfig, + context: { rootPath: process.cwd(), action: 'dev' }, + } as Partial), + ) + expect(console.error).toHaveBeenCalledWith(thrown) + expect(registerThemeSpy).toHaveBeenLastCalledWith({}) + + const taps: Record unknown> = {} + const tap = + (hook: string) => + (_: unknown, fn: (...args: unknown[]) => unknown) => { + taps[hook] = fn + } + const compiler = { + options: {}, + rspack: { + WebpackError: Error, + Compilation: { PROCESS_ASSETS_STAGE_REPORT: 5000 }, + }, + hooks: { + run: { tap: tap('run') }, + watchRun: { tap: tap('watchRun') }, + invalid: { tap: tap('invalid') }, + thisCompilation: { tap: tap('start') }, + }, + } + const config: { plugins?: { apply(compiler: unknown): void }[] } = {} + modifyRspackConfig.mock.calls[0][0](config) + const tapPromise = mock() + config.plugins![0]!.apply({ hooks: { watchRun: { tapPromise } } }) + modifyRspackConfig.mock.calls[1][0](config, { + environment: { name: 'web' }, + }) + config.plugins![1]!.apply(compiler) + const compile = () => { + const compilation = { + errors: [] as Error[], + assets: {}, + hooks: { + finishModules: { tap: mock() }, + processAssets: { tap: mock() }, + needAdditionalPass: { tap: mock() }, + }, + } + taps.start!(compilation) + return compilation.errors.map((error) => error.message) + } + expect(compile()).toEqual([message]) + expect(compile()).toEqual([message]) + + // The theme loads again once its files change + const watchRun = tapPromise.mock.calls[0][1] as () => Promise + statSpy.mockResolvedValueOnce({ mtimeMs: 1 } as fs.Stats) + await watchRun() + expect(compile()).toEqual([message]) + statSpy.mockResolvedValueOnce({ mtimeMs: 2 } as fs.Stats) + await watchRun() + expect(compile()).toEqual([]) + } finally { + consoleErrorSpy.mockRestore() + statSpy.mockRestore() + readFileSyncSpy.mockRestore() + readFileSpy.mockResolvedValue('{}') + } + }, + ) + + it('keeps a dev server running when a reload fails to register the theme', async () => { + const consoleErrorSpy = spyOn(console, 'error').mockReturnValue(undefined) + const statSpy = spyOn(fsPromises, 'stat') + const readFileSyncSpy = spyOn(fs, 'readFileSync').mockReturnValue( + '@theme { --color-brand: #0af; }', + ) + try { + readFileSpy.mockResolvedValue( + JSON.stringify({ tailwind: { css: 'tailwind.css' } }), + ) + existsSyncSpy.mockImplementation((path: string) => path === 'devup.json') + const modifyRspackConfig = mock() + // A build run: only its first load fails the build + await DevupUI({}).setup(createSetupContext({ modifyRspackConfig })) + const config: { plugins?: { apply: (compiler: unknown) => void }[] } = {} + modifyRspackConfig.mock.calls[0][0](config) + const tapPromise = mock() + config.plugins?.[0].apply({ hooks: { watchRun: { tapPromise } } }) + const watchRun = tapPromise.mock.calls[0][1] as () => Promise + const failure = new Error('bad token') + registerThemeSpy.mockImplementationOnce(() => { + throw failure + }) + + statSpy.mockResolvedValueOnce({ mtimeMs: 1 } as fs.Stats) + await watchRun() + statSpy.mockResolvedValueOnce({ mtimeMs: 2 } as fs.Stats) + await watchRun() + + expect(console.error).toHaveBeenCalledWith(failure) + expect(registerThemeSpy).toHaveBeenLastCalledWith({}) } finally { consoleErrorSpy.mockRestore() + statSpy.mockRestore() + readFileSyncSpy.mockRestore() + readFileSpy.mockResolvedValue('{}') } }) diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 72905a53b..7a792a4a4 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -78,14 +78,17 @@ async function writeDataFiles( 'extractCss' | 'debug' | 'include' >, compiler: DevupCompiler, -): Promise { + watching: boolean, +): Promise<{ tailwindFiles: string[]; themeError: unknown }> { let tailwindFiles: string[] = [] + let themeError: unknown try { const config = await loadDevupConfig(options.devupFile) const theme = config.theme ?? {} - compiler.registerTheme(withTailwindCss(theme, config)) + // Watched even when the theme fails, so fixing the Tailwind CSS reloads it tailwindFiles = tailwindCssFiles(config) + compiler.registerTheme(withTailwindCss(theme, config)) // Written even when empty, so tokens removed from the theme leave no // stale declarations behind. await writeFile( @@ -94,8 +97,13 @@ async function writeDataFiles( 'utf-8', ) } catch (error) { + // A one-shot build fails on a theme it cannot load or register: an empty + // theme would ship unstyled output. A watcher keeps running, since + // devup.json may be mid-edit, and reports the error until it is fixed. + if (!watching) throw error console.error(error) compiler.registerTheme({}) + themeError = error } // Sequential: writing into cssDir concurrently with its own mkdir loses the // race on a cold start (no `df/`) and fails the build with ENOENT. @@ -108,7 +116,7 @@ async function writeDataFiles( compiler.getCss(null, false), ) } - return tailwindFiles + return { tailwindFiles, themeError } } /** @@ -166,7 +174,9 @@ export const DevupUI = ({ 'utf-8', ) - let tailwindFiles = await writeDataFiles( + // `rsbuild dev` outlives a broken devup.json; every compilation reports + // it until it loads again + let { tailwindFiles, themeError } = await writeDataFiles( { package: libPackage, cssDir, @@ -175,6 +185,7 @@ export const DevupUI = ({ singleCss, }, compiler, + api.context.action === 'dev', ) if (!extractCss) return @@ -205,7 +216,7 @@ export const DevupUI = ({ ) ).join() if (stamp !== undefined && stamp !== current) { - tailwindFiles = await writeDataFiles( + ;({ tailwindFiles, themeError } = await writeDataFiles( { package: libPackage, cssDir, @@ -214,7 +225,8 @@ export const DevupUI = ({ singleCss, }, compiler, - ) + true, + )) } stamp = current }, @@ -384,6 +396,12 @@ export const DevupUI = ({ reservation.reserve() }) compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + if (themeError !== undefined) + compilation.errors.push( + new compiler.rspack.WebpackError( + `[devup-ui] ${themeError instanceof Error ? themeError.message : String(themeError)}`, + ), + ) const basePath = join(cssDir, 'devup-ui.css') const base = stylesheet(basePath) writeChanged(basePath, base) diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index c0205164c..6ded9635e 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -130,6 +130,7 @@ interface ViteTestPlugin { ) => ViteConfig configResolved: (config?: { command?: 'serve' | 'build' + build?: { watch?: object | null } root?: string plugins?: readonly object[] }) => Promise @@ -1479,23 +1480,116 @@ describe('devupUIVitePlugin', () => { } }) - it('should reset data files when load error', async () => { - writeFileSpy.mockResolvedValueOnce(undefined) - getThemeInterfaceSpy.mockReturnValue('interface code') + it('should fail the build when the theme cannot be loaded', async () => { existsSyncSpy.mockReturnValue(true) + const error = new Error('unreadable devup.json') readFileSpy.mockImplementation(() => { - throw new Error('error') + throw error }) const plugin = createPlugin({}) - await plugin.configResolved() - expect(registerThemeSpy).toHaveBeenCalledWith({}) - expect(writeFileSpy).toHaveBeenCalledWith( - join('df', '.gitignore'), - '*', - 'utf-8', + + await expect(plugin.configResolved({ command: 'build' })).rejects.toBe( + error, + ) + + expect(registerThemeSpy).not.toHaveBeenCalledWith({}) + expect(console.error).not.toHaveBeenCalled() + }) + + it('should fail the build when the theme cannot be registered', async () => { + existsSyncSpy.mockReturnValue(true) + readFileSpy.mockResolvedValue( + JSON.stringify({ theme: { colors: { default: { card: '#fff' } } } }), + ) + const clash = new Error( + "theme: color token 'card' and shadow token 'card' both become the CSS variable --card", + ) + registerThemeSpy.mockImplementationOnce(() => { + throw clash + }) + const plugin = createPlugin({}) + + await expect(plugin.configResolved({ command: 'build' })).rejects.toBe( + clash, ) }) + it.each([ + ['the dev server', { command: 'serve' }], + ['vite build --watch', { command: 'build', build: { watch: {} } }], + ])( + 'should report a theme error and keep %s running on an empty theme', + async (_name, config) => { + writeFileSpy.mockResolvedValueOnce(undefined) + getThemeInterfaceSpy.mockReturnValue('interface code') + existsSyncSpy.mockReturnValue(true) + const error = new Error('error') + readFileSpy.mockImplementation(() => { + throw error + }) + const plugin = createPlugin({}) + await plugin.configResolved(config) + expect(console.error).toHaveBeenCalledWith(error) + expect(registerThemeSpy).toHaveBeenCalledWith({}) + expect(writeFileSpy).toHaveBeenCalledWith( + join('df', '.gitignore'), + '*', + 'utf-8', + ) + }, + ) + + it.each([ + ['an Error', new Error('bad token'), 'bad token', true], + ['an Error without a stack', new Error('bad token'), 'bad token', false], + ['a thrown string', 'bad token', 'bad token', true], + ])( + 'should show the overlay instead of reloading when a devup.json update throws %s', + async (_name, thrown, message, keepStack) => { + if (thrown instanceof Error && !keepStack) thrown.stack = undefined + existsSyncSpy.mockReturnValue(true) + readFileSpy.mockResolvedValue( + JSON.stringify({ theme: { colors: { default: {} } } }), + ) + registerThemeSpy.mockImplementation((theme: object) => { + if (Object.keys(theme).length > 0) throw thrown + }) + const send = mock() + const environment = createHotUpdateEnvironment('client') + const plugin = createPlugin({}) + + await plugin.handleHotUpdate({ + file: 'devup.json', + server: { + moduleGraph: { + invalidateModule: mock(), + getModulesByFile: () => undefined, + }, + ws: { send }, + }, + modules: [], + timestamp: 1, + }) + await plugin.hotUpdate.call( + { environment }, + { file: 'devup.json', modules: [], timestamp: 2 }, + ) + + const overlay = { + type: 'error', + err: { + message, + stack: keepStack ? expect.any(String) : '', + plugin: 'devup-ui', + }, + } + expect(send).toHaveBeenCalledWith(overlay) + expect(send).not.toHaveBeenCalledWith({ type: 'full-reload' }) + expect(environment.hot.send).toHaveBeenCalledWith(overlay) + expect(console.error).toHaveBeenCalledWith(thrown) + }, + ) + it('should watch change', async () => { writeFileSpy.mockResolvedValueOnce(undefined) getThemeInterfaceSpy.mockReturnValue('interface code') diff --git a/packages/vite-plugin/src/plugin.ts b/packages/vite-plugin/src/plugin.ts index 46142b69d..814f5d1a0 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -277,7 +277,9 @@ async function writeDataFiles( options: Omit, inputs: Set, publishTailwind: (files: string[]) => void, -): Promise { + watching: boolean, +): Promise { + let themeError: unknown try { const config = await loadDevupConfig(options.devupFile, inputs) const theme = config.theme ?? {} @@ -292,8 +294,13 @@ async function writeDataFiles( 'utf-8', ) } catch (error) { + // A one-shot build fails on a theme it cannot load or register: an empty + // theme would ship unstyled output. A watcher keeps running, since + // devup.json may be mid-edit, and reports the error until it is fixed. + if (!watching) throw error console.error(error) compiler.registerTheme({}) + themeError = error } // Sequential: writing into cssDir concurrently with its own mkdir loses the // race on a cold start (no `df/`) and fails the build with ENOENT. @@ -306,6 +313,25 @@ async function writeDataFiles( compiler.getCss(null, false), ) } + return themeError +} + +/** + * The dev server's answer to a devup.json update: a reload, or the error + * overlay when the theme failed, since a reload would hide it. + */ +function themeUpdate(themeError: unknown) { + if (themeError === undefined) return { type: 'full-reload' as const } + const error = + themeError instanceof Error ? themeError : new Error(String(themeError)) + return { + type: 'error' as const, + err: { + message: error.message, + stack: error.stack ?? '', + plugin: 'devup-ui', + }, + } } export function DevupUI({ @@ -435,7 +461,7 @@ export function DevupUI({ let refreshTail = Promise.resolve() const isConfigFile = (file: string) => configFiles.has(resolve(file)) || activeConfigFiles.has(resolve(file)) - async function refreshConfig() { + async function refreshConfig(watching: boolean): Promise { configState.generation++ configState.refreshing++ const previous = refreshTail @@ -445,7 +471,7 @@ export function DevupUI({ try { await previous activeConfigFiles = inputs - await writeDataFiles( + const themeError = await writeDataFiles( compiler, { package: libPackage, @@ -459,9 +485,11 @@ export function DevupUI({ activeTailwindFiles = files watchConfigInputs?.() }, + watching, ) if (singleCss) await writeCssFile('devup-ui.css', compiler.getCss(null, false)) + return themeError } finally { configFiles = inputs tailwindFiles = activeTailwindFiles @@ -524,7 +552,8 @@ export function DevupUI({ createCompatTypes(importAliases), 'utf-8', ) - await refreshConfig() + // A dev server or `vite build --watch` outlives a broken devup.json + await refreshConfig(isServe || !!config?.build?.watch) try { // Numbers come from the sorted paths of every file the build can @@ -636,7 +665,7 @@ export function DevupUI({ if (change?.event === 'delete') await own(removeSource)(id) if (isConfigFile(id) || (isTailwindFile(id) && existsSync(id))) { try { - await own(refreshConfig)() + await own(refreshConfig)(true) } catch (error) { console.error(error) } @@ -674,7 +703,7 @@ export function DevupUI({ return } - await own(refreshConfig)() + const themeError = await own(refreshConfig)(true) const invalidatedModules = new Set() // A Tailwind class compiles from the definitions of the Tailwind CSS, so @@ -694,7 +723,7 @@ export function DevupUI({ true, ) } - environment.hot.send({ type: 'full-reload' }) + environment.hot.send(themeUpdate(themeError)) return [] }, // Vite 5 fallback: Vite 6+ does not call this hook when `hotUpdate` exists. @@ -716,7 +745,7 @@ export function DevupUI({ return } - await own(refreshConfig)() + const themeError = await own(refreshConfig)(true) const invalidatedModules = new Set() for (const mod of isTailwind @@ -734,7 +763,7 @@ export function DevupUI({ true, ) } - server.ws.send({ type: 'full-reload' }) + server.ws.send(themeUpdate(themeError)) return [] }, resolveId(id, importer) { diff --git a/packages/webpack-plugin/src/__tests__/config-errors.test.ts b/packages/webpack-plugin/src/__tests__/config-errors.test.ts index fa10a0678..15a873d00 100644 --- a/packages/webpack-plugin/src/__tests__/config-errors.test.ts +++ b/packages/webpack-plugin/src/__tests__/config-errors.test.ts @@ -9,16 +9,21 @@ import { DevupUIWebpackPlugin } from '../plugin' const wasm = loadCompiler('wasm') -it('clears the theme and creates the CSS directory when configuration cannot be read', () => { +function withUnreadableConfig( + test: (paths: { config: string; root: string; cssDir: string }) => void, +) { const root = mkdtempSync(join(tmpdir(), 'devup-webpack-config-')) const config = join(root, 'devup.json') - const cssDir = join(root, 'dist/css') mkdirSync(config) - wasm.registerTheme({ colors: { default: { brand: '#123456' } } }) - expect(wasm.getDefaultTheme()).toBe('default') - const registered = spyOn(wasm, 'registerTheme') - const logged = spyOn(console, 'error').mockReturnValue(undefined) try { + test({ config, root, cssDir: join(root, 'dist/css') }) + } finally { + rmSync(root, { recursive: true, force: true }) + } +} + +it('fails a one-shot build when configuration cannot be read', () => { + withUnreadableConfig(({ config, root, cssDir }) => { const plugin = new DevupUIWebpackPlugin({ engine: 'wasm', devupFile: config, @@ -27,17 +32,38 @@ it('clears the theme and creates the CSS directory when configuration cannot be watch: false, }) - plugin.writeDataFiles() + expect(() => plugin.writeDataFiles()).toThrow() + expect(plugin.themeError).toBeUndefined() + }) +}) + +it('clears the theme and creates the CSS directory when configuration cannot be read in watch mode', () => { + withUnreadableConfig(({ config, root, cssDir }) => { + wasm.registerTheme({ colors: { default: { brand: '#123456' } } }) + expect(wasm.getDefaultTheme()).toBe('default') + const registered = spyOn(wasm, 'registerTheme') + const logged = spyOn(console, 'error').mockReturnValue(undefined) + try { + const plugin = new DevupUIWebpackPlugin({ + engine: 'wasm', + devupFile: config, + distDir: join(root, 'dist'), + cssDir, + watch: true, + }) - expect(registered).toHaveBeenCalledTimes(1) - expect(registered).toHaveBeenCalledWith({}) - expect(wasm.getDefaultTheme()).toBeUndefined() - expect(logged).toHaveBeenCalledTimes(1) - expect(logged).toHaveBeenCalledWith(expect.any(Error)) - expect(existsSync(cssDir)).toBe(true) - } finally { - registered.mockRestore() - logged.mockRestore() - rmSync(root, { recursive: true, force: true }) - } + plugin.writeDataFiles() + + expect(registered).toHaveBeenCalledTimes(1) + expect(registered).toHaveBeenCalledWith({}) + expect(wasm.getDefaultTheme()).toBeUndefined() + expect(logged).toHaveBeenCalledTimes(1) + expect(logged).toHaveBeenCalledWith(expect.any(Error)) + expect(plugin.themeError).toBeInstanceOf(Error) + expect(existsSync(cssDir)).toBe(true) + } finally { + registered.mockRestore() + logged.mockRestore() + } + }) }) diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index ba12cb13f..1e833b362 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -148,6 +148,7 @@ interface MockCompiler { watchMode?: boolean webpack: { DefinePlugin: ReturnType + WebpackError: typeof Error Compilation: { PROCESS_ASSETS_STAGE_REPORT: number } } hooks: { @@ -277,6 +278,7 @@ function createCompiler(): MockCompiler { }, webpack: { DefinePlugin: mock(), + WebpackError: Error, Compilation: { PROCESS_ASSETS_STAGE_REPORT: 5000 }, }, hooks: { @@ -643,6 +645,67 @@ describe('devupUIWebpackPlugin', () => { expect(importFileMapSpy).toHaveBeenCalledWith({}) }) + it('fails a one-shot build on a theme error', () => { + const clash = new Error( + "theme: color token 'card' and shadow token 'card' both become the CSS variable --card", + ) + registerThemeSpy.mockImplementationOnce(() => { + throw clash + }) + const plugin = new DevupUIWebpackPlugin({ engine: 'wasm' }) + const compiler = createCompiler() + + expect(() => plugin.apply(asCompiler(compiler))).toThrow(clash) + + expect(registerThemeSpy).toHaveBeenCalledTimes(1) + expect(consoleErrorSpy).not.toHaveBeenCalled() + expect(compiler.options.module.rules).toEqual([]) + }) + + it.each([ + ['an Error', new Error('bad token'), '[devup-ui] bad token'], + ['a thrown string', 'bad token', '[devup-ui] bad token'], + ])( + 'reports a theme error that is %s in every watch compilation until devup.json loads again', + async (_name, thrown, message) => { + registerThemeSpy.mockImplementationOnce(() => { + throw thrown + }) + existsSyncSpy.mockImplementation((path: string) => path === 'devup.json') + statSpy.mockResolvedValueOnce(createStats(1)) + statSpy.mockResolvedValueOnce(createStats(2)) + const plugin = new DevupUIWebpackPlugin({ engine: 'wasm', watch: true }) + const compiler = createCompiler() + + plugin.apply(asCompiler(compiler)) + + expect(consoleErrorSpy).toHaveBeenCalledWith(thrown) + expect(registerThemeSpy).toHaveBeenLastCalledWith({}) + const setup = compiler.hooks.thisCompilation.tap.mock.calls.find( + ([name]) => name === 'DevupUIWebpackPluginWatchCss', + )?.[1] as (compilation: object) => void + const compile = () => { + const compilation = { + errors: [] as Error[], + hooks: { finishModules: { tapPromise: mock() } }, + } + setup(compilation) + return compilation.errors.map((error) => error.message) + } + expect(compile()).toEqual([message]) + expect(compile()).toEqual([message]) + + const watchRun = compiler.hooks.watchRun.tapPromise.mock.calls.find( + ([name]) => name === 'DevupUIWebpackPlugin', + )?.[1] as () => Promise + await watchRun() + await watchRun() + + expect(plugin.themeError).toBeUndefined() + expect(compile()).toEqual([]) + }, + ) + describe('Tailwind CSS definitions', () => { const tailwindFile = resolve('styles/tailwind.css') diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index accff8952..3dcc5927e 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -143,6 +143,12 @@ export class DevupUIWebpackPlugin { /** The files the project's Tailwind CSS is read from */ tailwindFiles: string[] = [] + /** + * Why the theme is empty in watch mode: every compilation reports it until + * devup.json loads again. + */ + themeError: unknown = undefined + writeDataFiles() { try { const config = loadDevupConfigSync(this.options.devupFile) @@ -159,9 +165,15 @@ export class DevupUIWebpackPlugin { ), { encoding: 'utf-8' }, ) + this.themeError = undefined } catch (error) { + // A one-shot build fails on a theme it cannot load or register: an + // empty theme would ship unstyled output. A watcher keeps running, since + // devup.json may be mid-edit, and reports the error until it is fixed. + if (!this.options.watch) throw error console.error(error) this.compiler.registerTheme({}) + this.themeError = error } if (!existsSync(this.options.cssDir)) mkdirSync(this.options.cssDir, { recursive: true }) @@ -448,7 +460,15 @@ export class DevupUIWebpackPlugin { if (this.options.watch) { compiler.hooks.thisCompilation.tap( 'DevupUIWebpackPluginWatchCss', - (compilation) => reconcileWatchCss(compilation, this.compiler), + (compilation) => { + if (this.themeError !== undefined) + compilation.errors.push( + new compiler.webpack.WebpackError( + `[devup-ui] ${this.themeError instanceof Error ? this.themeError.message : String(this.themeError)}`, + ), + ) + reconcileWatchCss(compilation, this.compiler) + }, ) let lastModifiedTime: string | null = null compiler.hooks.watchRun.tapPromise('DevupUIWebpackPlugin', async () => {