From 1a219e69baffbf3c01416577ce86e6203d63edca Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 10:02:47 +0900 Subject: [PATCH 1/2] fix(plugin-utils): report a broken devup.json instead of an empty theme `loadDevupConfig` turned a file that is not valid JSON into `{}`, so a typo silently dropped the whole theme, and it followed `extends` cycles until the stack overflowed. Both are now errors that name the file and how to fix it, as is a config that is not a JSON object. An `extends` target that does not exist yet stays an empty config: the dev servers watch it and load it once it appears. Vite, webpack and Rsbuild already log a config error and clear the theme; Bun swallowed it and now logs it too. `theme.d.ts` is written even when the theme has no tokens, so tokens removed from devup.json leave no stale declarations behind (Vite, webpack, Rsbuild and Next.js; Bun already did). Rsbuild creates the CSS directory before writing into it, like Vite, so a cold start cannot lose the race with ENOENT. Refs #686 (PLG-19, PLG-09, PLG-10) Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_devup_config_errors.json | 12 +++ .../bun-plugin/src/__tests__/plugin.test.ts | 13 ++- packages/bun-plugin/src/plugin.ts | 6 +- packages/next-plugin/src/plugin.ts | 6 +- .../src/__tests__/load-config.test.ts | 82 ++++++++++++++++++- packages/plugin-utils/src/load-config.ts | 64 ++++++++++++--- .../src/__tests__/plugin.test.ts | 29 +++++++ packages/rsbuild-plugin/src/plugin.ts | 38 ++++----- .../vite-plugin/src/__tests__/plugin.test.ts | 6 +- packages/vite-plugin/src/plugin.ts | 16 ++-- .../src/__tests__/plugin.test.ts | 22 ++--- packages/webpack-plugin/src/plugin.ts | 16 ++-- 12 files changed, 233 insertions(+), 77 deletions(-) create mode 100644 .changepacks/changepack_log_devup_config_errors.json diff --git a/.changepacks/changepack_log_devup_config_errors.json b/.changepacks/changepack_log_devup_config_errors.json new file mode 100644 index 000000000..ea7247e9a --- /dev/null +++ b/.changepacks/changepack_log_devup_config_errors.json @@ -0,0 +1,12 @@ +{ + "changes": { + "packages/plugin-utils/package.json": "Patch", + "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 broken `devup.json` is reported instead of silently loading an empty theme. New errors: ` is not valid JSON: `, ` must hold a JSON object`, and `devup.json extends form a cycle: a -> b -> a` (previously a cycle recursed until the stack overflowed). Vite, webpack, Rsbuild and Bun log the error and clear the theme as before (Bun used to swallow it); the Next.js Turbopack setup fails with it. `theme.d.ts` is now overwritten even when the theme has no tokens, so removed tokens leave no stale declarations. Rsbuild creates the CSS directory before writing into it, so a cold start no longer fails with ENOENT", + "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 6e2ea54a2..ac88f08db 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -287,9 +287,16 @@ describe('registered Bun hooks', () => { it('registers an empty theme when reading configuration fails', async () => { exists.mockReturnValue(true) - readConfig.mockRejectedValue(new Error('unreadable fixture config')) - await register({ engine: 'wasm' }) - expect(wasm.getDefaultTheme()).toBeUndefined() + const error = new Error('unreadable fixture config') + readConfig.mockRejectedValue(error) + const logged = spyOn(console, 'error').mockReturnValue(undefined) + try { + await register({ engine: 'wasm' }) + expect(wasm.getDefaultTheme()).toBeUndefined() + expect(logged).toHaveBeenCalledWith(error) + } finally { + logged.mockRestore() + } }) it('resolves generated stylesheets and loads their runtime placeholder', async () => { diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 284772623..40c52bc28 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -61,8 +61,10 @@ async function writeDataFiles(compiler: DevupCompiler): Promise { const config = await loadDevupConfig(devupFile) theme = withTailwindCss(config.theme ?? {}, config) tailwindFiles = tailwindCssFiles(config) - } catch { - // Error reading devup.json, use empty theme + } catch (error) { + // A broken devup.json clears the theme, as in the other plugins; the + // error says which file and how to fix it. + console.error(error) } compiler.registerTheme(theme) diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index aa92f663e..21aa6042a 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -291,9 +291,9 @@ export function DevupUI( const themeInterface = getThemeInterface( ...createThemeInterfaceArgs(libPackage), ) - if (themeInterface) { - writeFileSync(join(distDir, 'theme.d.ts'), themeInterface) - } + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + writeFileSync(join(distDir, 'theme.d.ts'), themeInterface) // disable turbo parallel const excludeRegex = createNodeModulesExcludeRegex(include, '.mdx.[tj]sx?$') diff --git a/packages/plugin-utils/src/__tests__/load-config.test.ts b/packages/plugin-utils/src/__tests__/load-config.test.ts index bc3510ba7..85fa0ffe3 100644 --- a/packages/plugin-utils/src/__tests__/load-config.test.ts +++ b/packages/plugin-utils/src/__tests__/load-config.test.ts @@ -1,5 +1,5 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { join, resolve } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'bun:test' @@ -91,12 +91,64 @@ describe('loadDevupConfigSync', () => { }) }) - it('should return empty object for invalid JSON', () => { + it('should report invalid JSON with its path', () => { const configPath = join(testDir, 'invalid.json') writeFileSync(configPath, 'not valid json {{{') - const result = loadDevupConfigSync(configPath) - expect(result).toEqual({}) + expect(() => loadDevupConfigSync(configPath)).toThrow( + `${resolve(configPath)} is not valid JSON: `, + ) + }) + + it.each([ + ['null', 'null'], + ['[]', 'an array'], + ['"theme"', 'a string'], + ])('should report a %s config that is not an object', (content, kind) => { + const configPath = join(testDir, 'not-object.json') + writeFileSync(configPath, content) + + expect(() => loadDevupConfigSync(configPath)).toThrow( + `${resolve(configPath)} must hold a JSON object such as { "theme": {} }, not ${kind}.`, + ) + }) + + it('should report extends that form a cycle', () => { + const baseDir = join(testDir, 'cycle') + mkdirSync(baseDir, { recursive: true }) + const a = join(baseDir, 'a.json') + const b = join(baseDir, 'b.json') + writeFileSync(a, JSON.stringify({ extends: ['./b.json'] })) + writeFileSync(b, JSON.stringify({ extends: ['./a.json'] })) + + expect(() => loadDevupConfigSync(a)).toThrow( + `devup.json \`extends\` form a cycle: ${resolve(a)} -> ${resolve(b)} -> ${resolve(a)}.`, + ) + }) + + it('should load a file that two extended files both extend', () => { + const baseDir = join(testDir, 'diamond') + mkdirSync(baseDir, { recursive: true }) + writeFileSync( + join(baseDir, 'root.json'), + JSON.stringify({ theme: { colors: { default: { text: 'red' } } } }), + ) + writeFileSync( + join(baseDir, 'left.json'), + JSON.stringify({ extends: ['./root.json'] }), + ) + writeFileSync( + join(baseDir, 'right.json'), + JSON.stringify({ extends: ['./root.json'] }), + ) + writeFileSync( + join(baseDir, 'top.json'), + JSON.stringify({ extends: ['./left.json', './right.json'] }), + ) + + expect(loadDevupConfigSync(join(baseDir, 'top.json'))).toEqual({ + theme: { colors: { default: { text: 'red' } } }, + }) }) it('should resolve extends', () => { @@ -214,6 +266,28 @@ describe('loadDevupConfig', () => { expect(result).toEqual({}) }) + it('should report invalid JSON with its path', async () => { + const configPath = join(testDir, 'async-invalid.json') + writeFileSync(configPath, '{ "theme": ') + + await expect(loadDevupConfig(configPath)).rejects.toThrow( + `${resolve(configPath)} is not valid JSON: `, + ) + }) + + it('should report extends that form a cycle', async () => { + const baseDir = join(testDir, 'async-cycle') + mkdirSync(baseDir, { recursive: true }) + const self = join(baseDir, 'self.json') + writeFileSync(self, JSON.stringify({ extends: ['./self.json'] })) + const inputs = new Set() + + await expect(loadDevupConfig(self, inputs)).rejects.toThrow( + `devup.json \`extends\` form a cycle: ${resolve(self)} -> ${resolve(self)}.`, + ) + expect([...inputs]).toEqual([resolve(self)]) + }) + it('should load and resolve extends asynchronously', async () => { const baseDir = join(testDir, 'async-extends') mkdirSync(baseDir, { recursive: true }) diff --git a/packages/plugin-utils/src/load-config.ts b/packages/plugin-utils/src/load-config.ts index 03b151be1..53e0c8282 100644 --- a/packages/plugin-utils/src/load-config.ts +++ b/packages/plugin-utils/src/load-config.ts @@ -46,14 +46,40 @@ export function deepMerge(base: T, override: U): T { } /** - * Parse JSON content safely + * Parse a config file's content. A file that is not a JSON object is an + * error naming the file: loading it as an empty config would silently drop + * the whole theme. */ -function parseConfig(content: string): DevupConfig { +function parseConfig(content: string, path: string): DevupConfig { + let config: unknown try { - return JSON.parse(content) as DevupConfig - } catch { - return {} + config = JSON.parse(content) + } catch (cause) { + throw new Error( + `${path} is not valid JSON: ${(cause as Error).message}. Fix its syntax; Devup UI does not load the theme until it parses.`, + { cause }, + ) + } + if (!isPlainObject(config)) { + throw new Error( + `${path} must hold a JSON object such as { "theme": {} }, not ${config === null ? 'null' : Array.isArray(config) ? 'an array' : `a ${typeof config}`}.`, + ) + } + return config as DevupConfig +} + +/** + * The `extends` chain that leads to `configPath`, ending with it. A file + * that is already on the chain extends itself through it, which never ends. + */ +function enterConfig(configPath: string, chain: readonly string[]): string[] { + const path = resolve(configPath) + if (chain.includes(path)) { + throw new Error( + `devup.json \`extends\` form a cycle: ${[...chain, path].join(' -> ')}. Remove the \`extends\` entry that points back to an earlier file.`, + ) } + return [...chain, path] } /** @@ -86,14 +112,23 @@ function mergeExtendedConfigs( export function loadDevupConfigSync( configPath: string, inputs?: Set, +): DevupConfig { + return loadConfigSync(configPath, inputs, []) +} + +function loadConfigSync( + configPath: string, + inputs: Set | undefined, + parents: readonly string[], ): DevupConfig { inputs?.add(resolve(configPath)) + const chain = enterConfig(configPath, parents) if (!existsSync(configPath)) { return {} } const content = readFileSync(configPath, 'utf-8') - const config = parseConfig(content) + const config = parseConfig(content, chain[chain.length - 1]) // If no extends, return the config as-is if (!config.extends || config.extends.length === 0) { @@ -105,7 +140,7 @@ export function loadDevupConfigSync( return mergeExtendedConfigs( config, config.extends.map((extendPath) => - loadDevupConfigSync(resolve(configDir, extendPath), inputs), + loadConfigSync(resolve(configDir, extendPath), inputs, chain), ), ) } @@ -117,17 +152,26 @@ export function loadDevupConfigSync( * @param configPath - Path to the devup.json file * @returns Resolved configuration with all extends merged */ -export async function loadDevupConfig( +export function loadDevupConfig( configPath: string, inputs?: Set, +): Promise { + return loadConfig(configPath, inputs, []) +} + +async function loadConfig( + configPath: string, + inputs: Set | undefined, + parents: readonly string[], ): Promise { inputs?.add(resolve(configPath)) + const chain = enterConfig(configPath, parents) if (!existsSync(configPath)) { return {} } const content = await readFile(configPath, 'utf-8') - const config = parseConfig(content) + const config = parseConfig(content, chain[chain.length - 1]) // If no extends, return the config as-is if (!config.extends || config.extends.length === 0) { @@ -140,7 +184,7 @@ export async function loadDevupConfig( const extendedConfigs: DevupConfig[] = [] for (const extendPath of config.extends) { extendedConfigs.push( - await loadDevupConfig(resolve(configDir, extendPath), inputs), + await loadConfig(resolve(configDir, extendPath), inputs, chain), ) } diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 15afbd3ad..688257336 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -688,6 +688,35 @@ const App = () => `, } }) + it('overwrites theme.d.ts when the theme has no tokens and creates cssDir before writing into it', async () => { + getThemeInterfaceSpy.mockReturnValue('') + const cssDir = resolve('df', 'devup-ui') + let made = false + mkdirSpy.mockImplementation( + () => + new Promise((done) => + setTimeout(() => { + made = true + done(undefined) + }, 5), + ), + ) + const writtenAfterMkdir = new Map() + writeFileSpy.mockImplementation((path: string) => { + writtenAfterMkdir.set(path, made) + return Promise.resolve() + }) + const plugin = DevupUI({ atomHoist: 0 }) + await plugin.setup(createSetupContext()) + expect(writeFileSpy).toHaveBeenCalledWith( + join('df', 'theme.d.ts'), + '', + 'utf-8', + ) + expect(mkdirSpy).toHaveBeenCalledWith(cssDir, { recursive: true }) + expect(writtenAfterMkdir.get(join(cssDir, 'devup-ui.css'))).toBe(true) + }) + it('should call setPrefix when prefix option is provided', async () => { const plugin = DevupUI({ prefix: 'my-prefix' }) await plugin.setup( diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 91dae66c8..842e1c91b 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -84,32 +84,28 @@ async function writeDataFiles( compiler.registerTheme(withTailwindCss(theme, config)) tailwindFiles = tailwindCssFiles(config) - const interfaceCode = compiler.getThemeInterface( - ...createThemeInterfaceArgs(options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + await writeFile( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', ) - - if (interfaceCode) { - await writeFile( - join(options.distDir, 'theme.d.ts'), - interfaceCode, - 'utf-8', - ) - } } catch (error) { console.error(error) compiler.registerTheme({}) } - await Promise.all([ - !existsSync(options.cssDir) - ? mkdir(options.cssDir, { recursive: true }) - : Promise.resolve(), - !options.singleCss - ? writeFile( - join(options.cssDir, 'devup-ui.css'), - compiler.getCss(null, false), - ) - : Promise.resolve(), - ]) + // Sequential: writing into cssDir concurrently with its own mkdir loses the + // race on a cold start (no `df/`) and fails the build with ENOENT. + if (!existsSync(options.cssDir)) { + await mkdir(options.cssDir, { recursive: true }) + } + if (!options.singleCss) { + await writeFile( + join(options.cssDir, 'devup-ui.css'), + compiler.getCss(null, false), + ) + } return tailwindFiles } diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index cbc3643da..610e1c418 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -1939,15 +1939,15 @@ describe('devupUIVitePlugin', () => { ).toEqual(expect.any(String)) }) - it('should not write interface code when no theme', async () => { + it('overwrites the interface code with nothing when the theme has no tokens', async () => { readFileSpy.mockResolvedValueOnce(JSON.stringify({})) getThemeInterfaceSpy.mockReturnValue('') existsSyncSpy.mockReturnValue(true) const plugin = createPlugin({}) await plugin.configResolved() - expect(writeFileSpy).not.toHaveBeenCalledWith( + expect(writeFileSpy).toHaveBeenCalledWith( join('df', 'theme.d.ts'), - expect.any(String), + '', 'utf-8', ) }) diff --git a/packages/vite-plugin/src/plugin.ts b/packages/vite-plugin/src/plugin.ts index f9ce736fc..1b573a0d5 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -283,17 +283,13 @@ async function writeDataFiles( compiler.registerTheme(withTailwindCss(theme, config)) publishTailwind(tailwindCssFiles(config)) - const interfaceCode = compiler.getThemeInterface( - ...createThemeInterfaceArgs(options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + await writeFile( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', ) - - if (interfaceCode) { - await writeFile( - join(options.distDir, 'theme.d.ts'), - interfaceCode, - 'utf-8', - ) - } } catch (error) { console.error(error) compiler.registerTheme({}) diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index f22c489e3..b2773541f 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -498,25 +498,21 @@ describe('devupUIWebpackPlugin', () => { 'CustomShadows', 'DevupTheme', ) - if (_options.getThemeInterface) - expect(writeFileSyncSpy).toHaveBeenCalledWith( - join(options.distDir, 'theme.d.ts'), - _options.getThemeInterface, - { - encoding: 'utf-8', - }, - ) - else expect(writeFileSyncSpy).toHaveBeenCalledTimes(options.watch ? 1 : 0) + // Written even when empty, so removed tokens leave no stale declarations. + expect(writeFileSyncSpy).toHaveBeenCalledWith( + join(options.distDir, 'theme.d.ts'), + _options.getThemeInterface, + { + encoding: 'utf-8', + }, + ) if (options.watch) expect(writeFileSyncSpy).toHaveBeenCalledWith( join(options.cssDir, 'devup-ui.css'), _options.getCss, ) - else - expect(writeFileSyncSpy).toHaveBeenCalledTimes( - _options.getThemeInterface ? 1 : 0, - ) + expect(writeFileSyncSpy).toHaveBeenCalledTimes(options.watch ? 2 : 1) }) }) diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 2c5bd2ed0..718e4e68c 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -148,15 +148,15 @@ export class DevupUIWebpackPlugin { this.compiler.registerTheme(withTailwindCss(theme, config)) this.tailwindFiles = tailwindCssFiles(config) - const interfaceCode = this.compiler.getThemeInterface( - ...createThemeInterfaceArgs(this.options.package), + // Written even when empty, so tokens removed from the theme leave no + // stale declarations behind. + writeFileSync( + join(this.options.distDir, 'theme.d.ts'), + this.compiler.getThemeInterface( + ...createThemeInterfaceArgs(this.options.package), + ), + { encoding: 'utf-8' }, ) - - if (interfaceCode) { - writeFileSync(join(this.options.distDir, 'theme.d.ts'), interfaceCode, { - encoding: 'utf-8', - }) - } } catch (error) { console.error(error) this.compiler.registerTheme({}) From 140017ab2c69c673121f05c20a1c3ae3b6dde8d2 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 10:41:18 +0900 Subject: [PATCH 2/2] fix(plugins): fail production builds on theme errors instead of an empty theme writeDataFiles in the Vite, webpack, Rsbuild and Bun plugins caught every error from loading devup.json and registering the theme, logged it and went on with an empty theme, so an invalid token or a CSS variable clash between token kinds shipped unstyled output from a build that succeeded. One-shot builds now rethrow the error. Watchers keep running on an empty theme, since devup.json may be mid-edit, and report it through the bundler: Vite sends the error overlay in place of the reload, webpack (and Next.js on webpack) and Rsbuild push it into every compilation's errors until the theme loads again, and a Bun reload logs it. Rsbuild now reads the Tailwind CSS files before registering the theme, so a failed registration still watches them. Refs #686 Co-Authored-By: Claude Opus 5.5 --- ...hangepack_log_theme_errors_fail_build.json | 11 ++ .../bun-plugin/src/__tests__/plugin.test.ts | 63 ++++++- packages/bun-plugin/src/plugin.ts | 23 ++- .../src/__tests__/plugin.test.ts | 166 ++++++++++++++++-- packages/rsbuild-plugin/src/plugin.ts | 30 +++- .../vite-plugin/src/__tests__/plugin.test.ts | 114 ++++++++++-- packages/vite-plugin/src/plugin.ts | 47 ++++- .../src/__tests__/config-errors.test.ts | 62 +++++-- .../src/__tests__/plugin.test.ts | 63 +++++++ packages/webpack-plugin/src/plugin.ts | 22 ++- 10 files changed, 532 insertions(+), 69 deletions(-) create mode 100644 .changepacks/changepack_log_theme_errors_fail_build.json 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 ac88f08db..047b80216 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -285,16 +285,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 40c52bc28..54c4101e6 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -54,19 +54,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( @@ -177,8 +184,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 688257336..d3b3f7c28 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 842e1c91b..62a6124ba 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -76,14 +76,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( @@ -92,8 +95,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. @@ -106,7 +114,7 @@ async function writeDataFiles( compiler.getCss(null, false), ) } - return tailwindFiles + return { tailwindFiles, themeError } } /** @@ -163,7 +171,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, @@ -172,6 +182,7 @@ export const DevupUI = ({ singleCss, }, compiler, + api.context.action === 'dev', ) if (!extractCss) return @@ -202,7 +213,7 @@ export const DevupUI = ({ ) ).join() if (stamp !== undefined && stamp !== current) { - tailwindFiles = await writeDataFiles( + ;({ tailwindFiles, themeError } = await writeDataFiles( { package: libPackage, cssDir, @@ -211,7 +222,8 @@ export const DevupUI = ({ singleCss, }, compiler, - ) + true, + )) } stamp = current }, @@ -364,6 +376,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 610e1c418..7951a8963 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 @@ -1471,23 +1472,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 1b573a0d5..47d5b883d 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -276,7 +276,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 ?? {} @@ -291,8 +293,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. @@ -305,6 +312,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({ @@ -433,7 +459,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 @@ -443,7 +469,7 @@ export function DevupUI({ try { await previous activeConfigFiles = inputs - await writeDataFiles( + const themeError = await writeDataFiles( compiler, { package: libPackage, @@ -457,9 +483,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 @@ -508,7 +536,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 @@ -612,7 +641,7 @@ export function DevupUI({ reservation.invalidate(id) if (isConfigFile(id) || (isTailwindFile(id) && existsSync(id))) { try { - await own(refreshConfig)() + await own(refreshConfig)(true) } catch (error) { console.error(error) } @@ -650,7 +679,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 @@ -670,7 +699,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. @@ -692,7 +721,7 @@ export function DevupUI({ return } - await own(refreshConfig)() + const themeError = await own(refreshConfig)(true) const invalidatedModules = new Set() for (const mod of isTailwind @@ -710,7 +739,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 b2773541f..c05224cc5 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: { @@ -590,6 +592,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 718e4e68c..19cfe2369 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -141,6 +141,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) @@ -157,9 +163,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 }) @@ -403,7 +415,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 () => {