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
1 change: 1 addition & 0 deletions .changepacks/changepack_log_next_turbo_theme_reload.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"changes":{"packages/next-plugin/package.json":"Patch"},"note":"Reload the theme under Turbopack next dev when devup.json, a config it extends or the project's Tailwind CSS changes, and re-run the loaders that depend on it","date":"2026-11-15T00:00:00.000Z"}
87 changes: 87 additions & 0 deletions packages/next-plugin/src/__tests__/coordinator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1651,6 +1651,93 @@ describe('coordinator per-bucket completion', () => {
})
})

describe('coordinator theme reload', () => {
async function start(theme: CoordinatorOptions['theme']) {
const coordinator = startCoordinator(makeOptions({ theme }))
await new Promise((r) => setTimeout(r, 100))
const port = parseInt(
(writeFileSyncSpy.mock.calls[0] as [string, string])[1],
)
return { coordinator, port }
}

function extract(port: number) {
return httpRequest(
port,
'POST',
'/extract',
JSON.stringify({
filename: 'src/A.tsx',
code: 'c',
resourcePath: join(process.cwd(), 'src', 'A.tsx'),
}),
)
}

it('registers the theme again once one of its files changes', async () => {
codeExtractSpy.mockReturnValue({
code: 'code',
map: undefined,
cssFile: undefined,
updatedBaseStyle: false,
free: mock(),
[Symbol.dispose]: mock(),
})
getCssSpy.mockReturnValue('css')
const devupFile = join(tmpDir, 'theme-devup.json')
const extended = join(tmpDir, 'theme-extended.json')
await Bun.write(devupFile, '{}')
// `extended` does not exist yet: creating it is a change too.
const reload = mock(() => [devupFile, extended])
const { coordinator, port } = await start({
files: [devupFile, extended],
reload,
})

await httpRequest(port, 'GET', '/css')
await extract(port)
expect(reload).not.toHaveBeenCalled()

await Bun.write(devupFile, '{"theme":{"colors":{}}}')
expect((await httpRequest(port, 'GET', '/css')).status).toBe(200)
expect(reload).toHaveBeenCalledTimes(1)
await httpRequest(port, 'GET', '/css')
expect(reload).toHaveBeenCalledTimes(1)

await Bun.write(extended, '{}')
expect((await extract(port)).status).toBe(200)
expect(reload).toHaveBeenCalledTimes(2)

coordinator.close()
})

it('reports a theme that fails to load and retries on the next request', async () => {
const devupFile = join(tmpDir, 'theme-broken.json')
await Bun.write(devupFile, '{}')
const reload = mock((): string[] => {
throw new Error('invalid theme')
})
const { coordinator, port } = await start({ files: [devupFile], reload })

await Bun.write(devupFile, '{"theme":1}')
const css = await httpRequest(port, 'GET', '/css')
expect(css).toEqual({ status: 500, body: 'invalid theme' })
reload.mockImplementation(() => {
throw 'still invalid'
})
expect(await httpRequest(port, 'GET', '/css')).toEqual({
status: 500,
body: 'still invalid',
})
const extracted = await extract(port)
expect(extracted.status).toBe(500)
expect(JSON.parse(extracted.body)).toEqual({ error: 'still invalid' })
expect(reload).toHaveBeenCalledTimes(3)

coordinator.close()
})
})

describe('coordinator deleted sources', () => {
it('forgets the files deleted since when a file is extracted again', async () => {
// Given: three extracted files, two of which are deleted later
Expand Down
8 changes: 8 additions & 0 deletions packages/next-plugin/src/__tests__/css-loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ describe('devupUICssLoader', () => {
p === portFile ? String(port) : '{}',
)

const addDependency = mock()
const result = await new Promise<string>((resolve, reject) => {
const asyncCallback = mock((err: Error | null, content?: string) => {
if (err) reject(err)
Expand All @@ -191,10 +192,12 @@ describe('devupUICssLoader', () => {
devupUICssLoader.bind({
async: () => asyncCallback,
addContextDependency: mock(),
addDependency,
getOptions: () => ({
...defaultOptions,
watch: true,
coordinatorPortFile: portFile,
themeFiles: ['/project/devup.json', '/project/app.css'],
}),
resourcePath: 'devup-ui-1.css',
} as unknown as CssLoaderThis)(
Expand All @@ -205,6 +208,11 @@ describe('devupUICssLoader', () => {
})

expect(result).toBe('.a{color:red}')
// A theme edit re-fetches the sheet with its new variables.
expect(addDependency.mock.calls).toEqual([
['/project/devup.json'],
['/project/app.css'],
])

// NO WASM functions should be called
expect(getCssSpy).not.toHaveBeenCalled()
Expand Down
4 changes: 4 additions & 0 deletions packages/next-plugin/src/__tests__/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,7 @@ export const a = <div css={{ color: 'red' }} />`
watch: true,
singleCss: true,
coordinatorPortFile: 'coordinator.port',
themeFiles: [resolve('devup.json'), resolve('base.json')],
}),
async: mock().mockReturnValue(asyncCallback),
resourcePath: join(process.cwd(), 'src', 'App.tsx'),
Expand All @@ -618,6 +619,9 @@ export const a = <div css={{ color: 'red' }} />`
)
})

// A theme edit re-runs the loader under Turbopack.
expect(t.addDependency).toHaveBeenCalledWith(resolve('devup.json'))
expect(t.addDependency).toHaveBeenCalledWith(resolve('base.json'))
expect(t.addDependency).toHaveBeenCalledWith(resolve('src/tokens.ts'))
expect(t.addDependency).not.toHaveBeenCalledWith(resolve('1'))

Expand Down
46 changes: 46 additions & 0 deletions packages/next-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,7 @@ describe('DevupUINextPlugin', () => {
classMapFile: join('df', 'classMap.json'),
fileMapFile: join('df', 'fileMap.json'),
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
theme: {},
defaultClassMap: {},
defaultFileMap: {},
Expand Down Expand Up @@ -739,6 +740,7 @@ describe('DevupUINextPlugin', () => {
classMapFile: join('df', 'classMap.json'),
fileMapFile: join('df', 'fileMap.json'),
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
watch: false,
singleCss: false,
theme: {},
Expand Down Expand Up @@ -795,6 +797,7 @@ describe('DevupUINextPlugin', () => {
classMapFile: join('df', 'classMap.json'),
fileMapFile: join('df', 'fileMap.json'),
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
theme: {},
defaultClassMap: {},
defaultFileMap: {},
Expand Down Expand Up @@ -849,6 +852,7 @@ describe('DevupUINextPlugin', () => {
properties: {},
},
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
},
},
],
Expand Down Expand Up @@ -886,6 +890,7 @@ describe('DevupUINextPlugin', () => {
classMapFile: join('df', 'classMap.json'),
fileMapFile: join('df', 'fileMap.json'),
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
theme: 'theme',
defaultClassMap: {},
defaultFileMap: {},
Expand Down Expand Up @@ -940,6 +945,7 @@ describe('DevupUINextPlugin', () => {
properties: {},
},
themeFile: 'devup.json',
themeFiles: [resolve('devup.json')],
},
},
],
Expand Down Expand Up @@ -1277,7 +1283,18 @@ export const box = style({ color: 'red' })`
prewarmedFiles: [],
prewarmedOutputs: expect.any(Map),
sourceMap: true,
theme: {
files: [resolve('devup.json')],
reload: expect.any(Function),
},
})
// The coordinator registers an edited theme through the same path.
const { theme } = startCoordinatorSpy.mock.calls[0]![0] as {
theme: { reload: () => string[] }
}
registerThemeSpy.mockClear()
expect(theme.reload()).toEqual([resolve('devup.json')])
expect(registerThemeSpy).toHaveBeenCalledWith({})
expect(codeExtractSpy).not.toHaveBeenCalled()
expect(codeExtractWithoutSourceMapSpy).not.toHaveBeenCalled()

Expand All @@ -1300,6 +1317,35 @@ export const box = style({ color: 'red' })`
}
})

it('registers the Tailwind CSS theme and watches its files', () => {
process.env.TURBOPACK = '1'
const tailwindSpy = spyOn(
importGraphModule,
'findTailwindCss',
).mockReturnValue({
file: resolve('app.css'),
files: [resolve('app.css'), resolve('tokens.css')],
css: '@import "tailwindcss";',
})
try {
const config = DevupUI({})

expect(registerThemeSpy).toHaveBeenCalledWith({
tailwindCss: '@import "tailwindcss";',
})
const rule = config.turbopack?.rules?.['*.{tsx,ts,jsx,js,mjs}'] as {
loaders: { options: { themeFiles: string[] } }[]
}
expect(rule.loaders[0].options.themeFiles).toEqual([
resolve('devup.json'),
resolve('app.css'),
resolve('tokens.css'),
])
} finally {
tailwindSpy.mockRestore()
}
})

it('hands the coordinator the full compiled-file set, not the static-only route map', () => {
process.env.TURBOPACK = '1'
process.env.DEVUP_UI_PROFILE = '1'
Expand Down
56 changes: 55 additions & 1 deletion packages/next-plugin/src/coordinator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, writeFile, writeFileSync } from 'node:fs'
import { existsSync, statSync, writeFile, writeFileSync } from 'node:fs'
import { createServer, type IncomingMessage, type Server } from 'node:http'
import { basename, dirname, join, relative } from 'node:path'

Expand Down Expand Up @@ -67,6 +67,16 @@ export interface CoordinatorOptions {
* open. Defaults to 60000. Exposed for tests; the plugin omits it.
*/
maxWaitMs?: number
/**
* Development only: the files the registered theme was read from, and how
* to register it again. Before each `/css` and `/extract` the coordinator
* re-registers the theme once one of those files changed, since Next does
* not reload next.config for devup.json. `reload` returns the new file list.
*/
theme?: {
files: string[]
reload: () => string[]
}
}

export interface PrewarmedOutput {
Expand Down Expand Up @@ -172,6 +182,36 @@ function readBody(req: IncomingMessage): Promise<string> {

let server: Server | null = null

interface ThemeWatch {
files: string[]
stamp: string
reload: () => string[]
}

let themeWatch: ThemeWatch | undefined

/** What changes when a theme input is edited, added or deleted. */
function themeStamp(files: string[]): string {
return files
.map((file) => {
try {
const stats = statSync(file)
return `${stats.mtimeMs}:${stats.size}`
} catch {
return 'missing'
}
})
.join('|')
}

/** Register the theme again when one of its input files has changed. */
function refreshTheme(): void {
if (!themeWatch || themeStamp(themeWatch.files) === themeWatch.stamp) return
// A throwing reload keeps the old stamp, so the next request retries.
const files = themeWatch.reload()
themeWatch = { ...themeWatch, files, stamp: themeStamp(files) }
}

// Extraction tracking for waitForIdle.
//
// The CSS loader fetches the live sheet from `/css?waitForIdle=true`. In
Expand Down Expand Up @@ -394,6 +434,10 @@ export function startCoordinator(options: CoordinatorOptions): {
for (const file of options.prewarmedFiles ?? []) extractedFiles.add(file)
extractedSources.clear()
fileNumToBucket.clear()
themeWatch = options.theme && {
...options.theme,
stamp: themeStamp(options.theme.files),
}

// A deleted file is never extracted again, so its styles would stay in the
// sheet; its importers are, once they stop importing it. A repeated
Expand Down Expand Up @@ -433,6 +477,14 @@ export function startCoordinator(options: CoordinatorOptions): {
const shouldWait = url.searchParams.get('waitForIdle') === 'true'
const fileNum = fileNumParam != null ? parseInt(fileNumParam) : undefined

try {
refreshTheme()
} catch (error) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end(error instanceof Error ? error.message : String(error))
return
}

if (shouldWait) {
if (fileNum != null && fileNumToBucket.has(fileNum)) {
// Deterministic: block until every member of this collapsed bucket
Expand Down Expand Up @@ -479,6 +531,7 @@ export function startCoordinator(options: CoordinatorOptions): {
resourcePath: string
}
extractedFilename = filename
refreshTheme()
const repeated = extractedSources.has(filename)
extractedSources.set(filename, resourcePath)

Expand Down Expand Up @@ -738,6 +791,7 @@ export const resetCoordinator = () => {
bucketToMembers = new Map()
canonicalMapRef = {}
expectedBaseFiles = new Set()
themeWatch = undefined
writeChain.clear()
latestContent.clear()
}
5 changes: 5 additions & 0 deletions packages/next-plugin/src/css-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface DevupUICssLoaderOptions {
classMapFile: string
fileMapFile: string
themeFile: string
/** Every file the theme is read from (devup.json, its extends, Tailwind CSS) */
themeFiles?: string[]
theme?: object
defaultSheet: object
defaultClassMap: object
Expand Down Expand Up @@ -86,6 +88,7 @@ const devupUICssLoader: RawLoaderDefinitionFunction<DevupUICssLoaderOptions> =
classMapFile,
fileMapFile,
themeFile,
themeFiles = [],
theme,
defaultClassMap,
defaultFileMap,
Expand All @@ -94,6 +97,8 @@ const devupUICssLoader: RawLoaderDefinitionFunction<DevupUICssLoaderOptions> =

// Coordinator mode: fetch live CSS from coordinator (disk content is stale)
if (coordinatorPortFile) {
// The sheet holds the theme's variables: re-run when the theme changes.
for (const file of themeFiles) this.addDependency(file)
const callback = this.async()
// Check both resourcePath and resourceQuery for ?fileNum=N
// Turbopack may embed query in resourcePath or provide it via resourceQuery
Expand Down
Loading
Loading