Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changepacks/changepack_log_devup_config_errors.json
Original file line number Diff line number Diff line change
@@ -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: `<file> is not valid JSON: <cause>`, `<file> 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"
}
13 changes: 10 additions & 3 deletions packages/bun-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
6 changes: 4 additions & 2 deletions packages/bun-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@ async function writeDataFiles(compiler: DevupCompiler): Promise<string[]> {
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)

Expand Down
6 changes: 3 additions & 3 deletions packages/next-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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?$')

Expand Down
82 changes: 78 additions & 4 deletions packages/plugin-utils/src/__tests__/load-config.test.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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<string>()

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 })
Expand Down
64 changes: 54 additions & 10 deletions packages/plugin-utils/src/load-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,40 @@ export function deepMerge<T, U>(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]
}

/**
Expand Down Expand Up @@ -86,14 +112,23 @@ function mergeExtendedConfigs(
export function loadDevupConfigSync(
configPath: string,
inputs?: Set<string>,
): DevupConfig {
return loadConfigSync(configPath, inputs, [])
}

function loadConfigSync(
configPath: string,
inputs: Set<string> | 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) {
Expand All @@ -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),
),
)
}
Expand All @@ -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<string>,
): Promise<DevupConfig> {
return loadConfig(configPath, inputs, [])
}

async function loadConfig(
configPath: string,
inputs: Set<string> | undefined,
parents: readonly string[],
): Promise<DevupConfig> {
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) {
Expand All @@ -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),
)
}

Expand Down
29 changes: 29 additions & 0 deletions packages/rsbuild-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,35 @@ const App = () => <Box></Box>`,
}
})

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<undefined>((done) =>
setTimeout(() => {
made = true
done(undefined)
}, 5),
),
)
const writtenAfterMkdir = new Map<string, boolean>()
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(
Expand Down
38 changes: 17 additions & 21 deletions packages/rsbuild-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
6 changes: 3 additions & 3 deletions packages/vite-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
)
})
Expand Down
Loading
Loading